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:
Why do I have different results calculating True Positive rate in Keras Neural Network?
I'm training a neural network using Python Keras package. I care about the True Positive rate, so I added it to Callbacks and Metrics. Surprisingly, I'm getting different results using the same formula (Callbacks shows 81%, whi... | Why do I have different results calculating True Positive rate in Keras Neural Network? | I'm training a neural network using Python Keras package. I care about the True Positive rate, so I added it to Callbacks and Metrics. Surprisingly, I'm getting different results using the same formula (Callbacks shows 81%, which is correct: I can see the same manually after I join Labels and Predictions; Metrics shows... | [
"The simplest way, you can use true positive, true negative, false positive, and false negative as metrics, then calculate True Positive Rate manually.\nHere modification to your code...\nmodel.compile(loss='binary_crossentropy',\n optimizer=keras.optimizers.Adam(lr=0.0001, beta_1=0.9, beta_2=0.999, ep... | [
0
] | [] | [] | [
"callback",
"keras",
"metrics",
"neural_network",
"python"
] | stackoverflow_0053208646_callback_keras_metrics_neural_network_python.txt |
Q:
Insert $ in front of numbers in column using Pandas
I wish to add dollar symbol in front of all the values in my column.
Data
ID Price
aa 800
bb 2
cc 300
cc 4
Desired
ID Price
aa $800
bb $2
cc $300
cc $4
Doing
df.loc["Price"] ='$'+ df["Price"].map('{:,.0f}'.format)
I believe I have to map this, not 10... | Insert $ in front of numbers in column using Pandas | I wish to add dollar symbol in front of all the values in my column.
Data
ID Price
aa 800
bb 2
cc 300
cc 4
Desired
ID Price
aa $800
bb $2
cc $300
cc $4
Doing
df.loc["Price"] ='$'+ df["Price"].map('{:,.0f}'.format)
I believe I have to map this, not 100% sure. Any suggestion is appreciated.
| [
"You can also try\ndf[\"Price\"] = '$' + df[\"Price\"].astype(str)\n\n",
"We could use str.replace here:\ndf[\"Price\"] = df[\"Price\"].astype(str).str.replace(r'^', '$', regex=True)\n\n"
] | [
2,
1
] | [] | [] | [
"numpy",
"pandas",
"python"
] | stackoverflow_0074568184_numpy_pandas_python.txt |
Q:
TypeError: unsupported operand type(s) for /: 'list' and 'int' solution is an array
import numpy as np
from sympy import symbols, solve
x = symbols('x')
expr1 = -2*x + x**2 + 1
a = solve(expr1)
print(a)
p = a/2
expr2 = -4*x + x**2 + a
z = solve(expr2)
print(z)
5 a = solve(expr1)
6 print(a)
----> 7 p = a/2
... | TypeError: unsupported operand type(s) for /: 'list' and 'int' solution is an array | import numpy as np
from sympy import symbols, solve
x = symbols('x')
expr1 = -2*x + x**2 + 1
a = solve(expr1)
print(a)
p = a/2
expr2 = -4*x + x**2 + a
z = solve(expr2)
print(z)
5 a = solve(expr1)
6 print(a)
----> 7 p = a/2
8 expr2 = -4*x + x**2 + a
9 z = solve(expr2)
TypeError: unsupported operand ... | [
"I see you want to \"use the answer for a new equation\".\nThe previous equation solution is a, a list with 1 element [1]\nthen you can use a[0] in your next equation\nexpr2 = -4*x + x**2 + a[0]\nz = solve(expr2)\nprint(z)\n\nand p=a/2 is totally useless, you didn't use p after that.\n"
] | [
0
] | [] | [] | [
"arrays",
"python"
] | stackoverflow_0074568247_arrays_python.txt |
Q:
Browser quit automatically by using selenium on chrome
The simple code like this:
from selenium import webdriver
driver = webdriver.Chrome()
driver.get('https://www.baidu.com')
It runs well , but! The opened browser quit automatically.
Some infos below
i have more selenium develop experience , this ... | Browser quit automatically by using selenium on chrome | The simple code like this:
from selenium import webdriver
driver = webdriver.Chrome()
driver.get('https://www.baidu.com')
It runs well , but! The opened browser quit automatically.
Some infos below
i have more selenium develop experience , this issue i met it these days on teaching my students.
chromedri... | [
"You have to use Options:\nfrom selenium.webdriver.chrome.service import Service\nfrom selenium.webdriver.chrome.options import Options\n\noptions = Options()\noptions.add_experimental_option(\"detach\", True)\n\ndriver = webdriver.Chrome(service=Service(<chromedriver.exe path>), options=options)\n\n"
] | [
0
] | [] | [] | [
"python",
"selenium",
"selenium_chromedriver"
] | stackoverflow_0074567988_python_selenium_selenium_chromedriver.txt |
Q:
Bianary Search algorithm comparisons
I created a python program that sorts a list of numbers by using a binary search algorithm, but now i need to include a comparisons counter that counts the number of comparisons it made. I am struggling to figure out where to put the counters because I get errors in the test co... | Bianary Search algorithm comparisons | I created a python program that sorts a list of numbers by using a binary search algorithm, but now i need to include a comparisons counter that counts the number of comparisons it made. I am struggling to figure out where to put the counters because I get errors in the test code given to me or with my program itself.
... | [
"since you already set comparisons as global variable, you don't need to return comparisons in your function actually.\ninstead, just after your global comparisons, put\ncomparisons += 1\n\nwill be enough.\nand in the end of your program, print(comparisons)\n"
] | [
0
] | [] | [] | [
"algorithm",
"comparison",
"python"
] | stackoverflow_0074568378_algorithm_comparison_python.txt |
Q:
How do I reinitialize a frame in tkinter?
I have a program that deals a lot with creating objects from data in files with the ability to edit the objects and then save them in the same file. I am implementing a GUI, and I am using tkinter to do it. The problem I am facing is the problem of frames not updating when... | How do I reinitialize a frame in tkinter? | I have a program that deals a lot with creating objects from data in files with the ability to edit the objects and then save them in the same file. I am implementing a GUI, and I am using tkinter to do it. The problem I am facing is the problem of frames not updating when I jump back and forth between frames, since th... | [
"You can't get the \"printed out word\" to change because the constructor for Homescreen is only run once. You need another method that changes the entry when you raise the Frame. The changes are commented below. There are only 4.\nimport tkinter as tk\n\nclass App(tk.Tk):\n def __init__(self):\n tk.Tk.__... | [
0
] | [] | [] | [
"frames",
"python",
"tkinter"
] | stackoverflow_0074567783_frames_python_tkinter.txt |
Q:
Warning : X has feature names, but DecisionTreeClassifier was fitted without feature names
I am training csv file with sklearn using DecesionTreeClassifier, RandomForestClassifier and SVC.
when i run it all of them give me the warning says "X has feature names, but Classifier was fitted without feature names" 4 ti... | Warning : X has feature names, but DecisionTreeClassifier was fitted without feature names | I am training csv file with sklearn using DecesionTreeClassifier, RandomForestClassifier and SVC.
when i run it all of them give me the warning says "X has feature names, but Classifier was fitted without feature names" 4 times each.
I get the data with pandas and i split the data like this
x = dataset_df.drop(columns=... | [
"In think, you are loading a model fitted using previous versions of sklearn.\nWith the latest version of sklearn, I don't get any error/warning with the following snippet.\nX, y = datasets.make_classification(random_state=21)\nx_df = pd.DataFrame(X)\nx_train, x_test, y_train, y_test = model_selection.train_test_sp... | [
0
] | [] | [] | [
"decisiontreeclassifier",
"python",
"scikit_learn",
"svc",
"warnings"
] | stackoverflow_0074562712_decisiontreeclassifier_python_scikit_learn_svc_warnings.txt |
Q:
Messing around with flask , my form page is not functioning the button is not working. It should display a string that says thank you for submitting
I have created a flask application of the soccer tournament. I am having issues with the form page, the submit button should display a text "Hello" + string + "for su... | Messing around with flask , my form page is not functioning the button is not working. It should display a string that says thank you for submitting | I have created a flask application of the soccer tournament. I am having issues with the form page, the submit button should display a text "Hello" + string + "for submitting!". I created a additional html page named display that displays this. Once, I filled out the form it did not do nothing.
#import the flask modul... | [
"In addition to the other comments, you likely wanted this line:\nif request.method == \"POST\" and request.form.get('submit'):\n\nto be\nif request.method == \"POST\" and request.form.get('user'):\n\nto check for the user parameter in the form. This would redirect you to display.html, but following this you woul... | [
1,
0
] | [] | [] | [
"forms",
"python"
] | stackoverflow_0074568388_forms_python.txt |
Q:
Derivative using Numpy or Other Library for lambda sin function
So i have this newton optimation problem where i must found the value f'(x) and f''(x) where x = 2.5 and the f = 2 * sin(x) - ((x)**2/10) for calculating, but i tried using sympy and np.diff for the First and Second Derivative but no clue, cause it ke... | Derivative using Numpy or Other Library for lambda sin function | So i have this newton optimation problem where i must found the value f'(x) and f''(x) where x = 2.5 and the f = 2 * sin(x) - ((x)**2/10) for calculating, but i tried using sympy and np.diff for the First and Second Derivative but no clue, cause it keep getting error so i go back using manual derivate, Any clue how to ... | [
"In your case, the derivates can be calculated using the scipy library as follows:\nfrom scipy.misc import derivative\n\ndef f(x):\n return 2 * sin(x) - ((x)**2/10)\n\nprint(\"First derivative:\" , derivative(f, 2.5, dx=1e-9))\nprint(\"Second derivative\", derivative(f, 2.5, n=2, dx=0.02))\n\nHere the first and ... | [
3
] | [] | [] | [
"derivative",
"numpy",
"python",
"sympy"
] | stackoverflow_0074568086_derivative_numpy_python_sympy.txt |
Q:
Python - Find second smallest number
I found this code on this site to find the second largest number:
def second_largest(numbers):
m1, m2 = None, None
for x in numbers:
if x >= m1:
m1, m2 = x, m1
elif x > m2:
m2 = x
return m2
Source: Get the second largest numb... | Python - Find second smallest number | I found this code on this site to find the second largest number:
def second_largest(numbers):
m1, m2 = None, None
for x in numbers:
if x >= m1:
m1, m2 = x, m1
elif x > m2:
m2 = x
return m2
Source: Get the second largest number in a list in linear time
Is it possible... | [
"a = [6,5,4,4,2,1,10,1,2,48]\ns = set(a) # used to convert any of the list/tuple to the distinct element and sorted sequence of elements\n# Note: above statement will convert list into sets \nprint sorted(s)[1] \n\n",
"The function can indeed be modified to find the second smallest:\ndef second_smallest(numbers):... | [
28,
22,
11,
4,
2,
0,
0,
0,
0,
0
] | [
"Here we want to keep an invariant while we scan the list of numbers, for every sublist it must be\n\nm1<=m2<={all other elements}\n\nthe minimum length of a list for which the question (2nd smallest) is sensible is 2, so we establish the invariant examining the first and the second element of the list (no need for... | [
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-2
] | [
"python"
] | stackoverflow_0026779618_python.txt |
Q:
player.update wont take key input and make character move pygame
I am new to pygame and this code I created by following a tutorial is not working. The white box i made on the screen should be moving with my arrow keys but its not. Does anyone know why? Also can someone explain what self means in the class and def... | player.update wont take key input and make character move pygame | I am new to pygame and this code I created by following a tutorial is not working. The white box i made on the screen should be moving with my arrow keys but its not. Does anyone know why? Also can someone explain what self means in the class and defs?
import pygame
from pygame.locals import (
K_UP,
K_DOWN,
... | [
"You always draw the player in the center of the screen:\n\nscreen.blit(player.surf,(SCREEN_WIDTH/2,SCREEN_HEIGHT/2))\n\n\nYou have to draw the player at player.rect:\nscreen.blit(player.surf, player.rect)\n\n\nHowever, since you use pygame.sprite.Sprite you should also use pygame.sprite.Group and you should limit ... | [
0
] | [] | [] | [
"pygame",
"python"
] | stackoverflow_0074568288_pygame_python.txt |
Q:
Greedy graph coloring using networkx
I have attached my code below. I created a complete graph and tried to use greedy_color() function so that no nodes next to each other are assigned the same color. But the problem is, greedy_color() function is returning number same as the node (Not using least colors possible)... | Greedy graph coloring using networkx | I have attached my code below. I created a complete graph and tried to use greedy_color() function so that no nodes next to each other are assigned the same color. But the problem is, greedy_color() function is returning number same as the node (Not using least colors possible). How can I solve this?
import networkx a... | [
"Your code is correct, however complete graph means every node is next to each other, so each node will have a unique colour.\nFor example, modifying the graph to a different one gives the following:\nfrom networkx import greedy_color\nfrom networkx import karate_club_graph\n\nG = karate_club_graph()\nprint(greedy_... | [
1
] | [] | [] | [
"graph",
"graph_theory",
"networkx",
"python",
"python_3.x"
] | stackoverflow_0074568522_graph_graph_theory_networkx_python_python_3.x.txt |
Q:
TypeError: '>' not supported between instances of 'str' and 'int' - Python
I'm trying to save user inputs into a file but I keep getting a TypeError. How do I fix it
from passenger import *
file = open("passenger.txt", 'w')
continue_record = True
while continue_record:
record = input("\nRecord passenger (y/n... | TypeError: '>' not supported between instances of 'str' and 'int' - Python | I'm trying to save user inputs into a file but I keep getting a TypeError. How do I fix it
from passenger import *
file = open("passenger.txt", 'w')
continue_record = True
while continue_record:
record = input("\nRecord passenger (y/n): ")
if record == 'n':
continue_record = False
else:
d... | [
"You are returning the elements in a different order of unpacking them.\nreturn passenger_name, distance, passenger_type\n\nYou unpack as the following (note that distance is actually the passenger_name).\ndistance, name, passenger_type = input_passenger()\n\nYou want\nname, distance, passenger_type = input_passeng... | [
0
] | [] | [] | [
"file",
"python"
] | stackoverflow_0074568371_file_python.txt |
Q:
How would you find a list that contains only unique elements in a list of lists?
I am trying to create a program which takes an input of a list of lists, and gives an output of lists with only distinct elements.
For example, if I had this list:
[[1,2,3,4],[1,3,6,7],[5,8,9]]
my output should just be
[5,8,9]
becau... | How would you find a list that contains only unique elements in a list of lists? | I am trying to create a program which takes an input of a list of lists, and gives an output of lists with only distinct elements.
For example, if I had this list:
[[1,2,3,4],[1,3,6,7],[5,8,9]]
my output should just be
[5,8,9]
because only [5,8,9] contain elements which are not found in any other list.
I have created... | [
"Using collections.Counter and itertools.chain.from_iterable:\nfrom collections import Counter\nfrom itertools import chain\n\nlists = [[1, 2, 3, 4], [1, 3, 6, 7], [5, 8, 9]]\ncounts = Counter(chain.from_iterable(lists))\n\nunique = [\n element\n for element in lists\n if all(counts[e] == 1 for e in elemen... | [
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0074568425_python.txt |
Q:
How to disable SQLAlchemy caching?
I have a caching problem when I use sqlalchemy.
I use sqlalchemy to insert data into a MySQL database. Then, I have another application process this data, and update it directly.
But sqlalchemy always returns the old data rather than the updated data. I think sqlalchemy cached ... | How to disable SQLAlchemy caching? | I have a caching problem when I use sqlalchemy.
I use sqlalchemy to insert data into a MySQL database. Then, I have another application process this data, and update it directly.
But sqlalchemy always returns the old data rather than the updated data. I think sqlalchemy cached my request ... so ... how should I disab... | [
"The usual cause for people thinking there's a \"cache\" at play, besides the usual SQLAlchemy identity map which is local to a transaction, is that they are observing the effects of transaction isolation. SQLAlchemy's session works by default in a transactional mode, meaning it waits until session.commit() is ca... | [
52,
21,
4,
3,
1
] | [
"First, there is no cache for SQLAlchemy.\nBased on your method to fetch data from DB, you should do some test after database is updated by others, see whether you can get new data.\n(1) use connection:\nconnection = engine.connect()\nresult = connection.execute(\"select username from users\")\nfor row in result:\n... | [
-1,
-4
] | [
"innodb",
"mysql",
"python",
"sqlalchemy"
] | stackoverflow_0010210080_innodb_mysql_python_sqlalchemy.txt |
Q:
Extract information about education institute, grades, year and degree from text using NLP in Python
I want to extract information about education institute, degree, year of passing and grades (CGPA/GPA/Percentage) from text using NLP in Python.
For example, if I have the input:
NBN Sinhgad School Of Engineering,... | Extract information about education institute, grades, year and degree from text using NLP in Python | I want to extract information about education institute, degree, year of passing and grades (CGPA/GPA/Percentage) from text using NLP in Python.
For example, if I have the input:
NBN Sinhgad School Of Engineering,Pune 2016 - 2020 Bachelor of Engineering Computer Science CGPA: 8.78 Vidya Bharati Chinmaya Vidyalaya,Jams... | [
"yes it is possible to parse the data without training any custom NER model. you have\nto build the custom rules to parse the data.\nIn your example case, you can the extract data by regex and pattern identification like institute always before the year of passing or something. if it is not unordered,you have to go... | [
1
] | [] | [] | [
"nlp",
"nltk",
"python",
"spacy"
] | stackoverflow_0074552512_nlp_nltk_python_spacy.txt |
Q:
How to get the name of nested tag from xml python
I want to get the name of all tags of nested tag. here is the code that I tried
soup = BeautifulSoup('''
<AlternativeIdentifiers>
<NationalLocationCode>513100</NationalLocationCode>
</AlternativeIdentifiers>
<Name>Abbey Wood</Name>
<SixteenCharacterName>ABBEY WO... | How to get the name of nested tag from xml python | I want to get the name of all tags of nested tag. here is the code that I tried
soup = BeautifulSoup('''
<AlternativeIdentifiers>
<NationalLocationCode>513100</NationalLocationCode>
</AlternativeIdentifiers>
<Name>Abbey Wood</Name>
<SixteenCharacterName>ABBEY WOOD.</SixteenCharacterName>
<Address>
<com:PostalAddres... | [
"Just invoke the find_all method, then you will get the desired ResultSet.\nfrom bs4 import BeautifulSoup\n\nsoup = BeautifulSoup('''\n<AlternativeIdentifiers>\n <NationalLocationCode>513100</NationalLocationCode>\n</AlternativeIdentifiers>\n<Name>Abbey Wood</Name>\n<SixteenCharacterName>ABBEY WOOD.</SixteenChar... | [
0
] | [
"when you define the soup variable like this the tag names get changed.\ntry to print soup variable you will get your answer.\ndo print(soup) once\n"
] | [
-1
] | [
"beautifulsoup",
"parsing",
"python",
"xml"
] | stackoverflow_0074568521_beautifulsoup_parsing_python_xml.txt |
Q:
Measure CPU clock cycles per operation in python
I'd like to know how'd you measure the amount of clock cycles per instruction say copy int from one place to another?
I know you can time it down to nano seconds but with today's cpu's that resolution is too low to get a correct reading for the oprations that take j... | Measure CPU clock cycles per operation in python | I'd like to know how'd you measure the amount of clock cycles per instruction say copy int from one place to another?
I know you can time it down to nano seconds but with today's cpu's that resolution is too low to get a correct reading for the oprations that take just a few clock cycles?
It there a way to confirm how ... | [
"This is a very interesting question that can easily throw you into the rabbit's hole. Basically any CPU cycle measurements depends on your processors and compilers RDTSC implementation.\nFor python there is a package called hwcounter that can be used as follows:\n# pip install hwcounter \n\nfrom hwcounter import T... | [
0
] | [] | [] | [
"cpu_cycles",
"cpu_usage",
"python"
] | stackoverflow_0071340309_cpu_cycles_cpu_usage_python.txt |
Q:
django migration error on changing FK field to regular field
Part of my model looked like this, initially. I'm using PostgreSQL.
class RealTimeLocation(models.Model):
name = models.CharField(max_length=80)
latlng = models.PointField(default=None)
class CabLog(models.Model):
location = models.Foreign... | django migration error on changing FK field to regular field | Part of my model looked like this, initially. I'm using PostgreSQL.
class RealTimeLocation(models.Model):
name = models.CharField(max_length=80)
latlng = models.PointField(default=None)
class CabLog(models.Model):
location = models.ForeignKey(RealTimeLocation,
on_delete=models.CASC... | [
"You got this error because you run only makemigrations and migrate.\nYou must run sqlmigrate also.\nTry these three commands:\npython manage.py makemigrations appname\n\npython manage.py sqlmigrate appname 0001 #You didn't run this command after makemigrations that's why you got that error\n\npython manage.py migr... | [
0
] | [] | [] | [
"django",
"django_migrations",
"python"
] | stackoverflow_0074567616_django_django_migrations_python.txt |
Q:
Guardian pattern. Trying to understand why/how the length of 'no input' can be greater than 0 when evaluated
while True:
line = input('> ')
if len(line) > 0 and line[0] == '#' :
continue
if line == 'done':
break
print line
print ("done!")
#So if there are no zeroth character then t... | Guardian pattern. Trying to understand why/how the length of 'no input' can be greater than 0 when evaluated | while True:
line = input('> ')
if len(line) > 0 and line[0] == '#' :
continue
if line == 'done':
break
print line
print ("done!")
#So if there are no zeroth character then the length of the line is greater than 0?
| [
"I think it is a logical error:\nEven if the length of the string return by this function len() is 0 for empty input it won't stop since the breaking criteria only meets when the input string is \"done\"\nso the length of no input i.e empty input is 0 but the terminal condition didn't meet\n"
] | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074568534_python.txt |
Q:
copy the values of one rows into remaining rows
I have two dataframes DF1 and DF2.
DF1 DF2
Column1 Column2 Column3 Column4 Column5 Column6
A B C D E F
G H I J
... | copy the values of one rows into remaining rows | I have two dataframes DF1 and DF2.
DF1 DF2
Column1 Column2 Column3 Column4 Column5 Column6
A B C D E F
G H I J
K L M N
I'... | [
"What you need is ffill .\nAssuming final concated DataFrame as df\ndf['Column1'] = df['Column1'].replace('', np.nan).ffill()\ndf['Column2'] = df['Column2'].replace('', np.nan).ffill()\n\nShould Gives #\nColumn1 Column2 Column3 Column4 Column5 Column6\n A B C D E F\n A B ... | [
0
] | [] | [] | [
"numpy",
"pandas",
"python"
] | stackoverflow_0074568672_numpy_pandas_python.txt |
Q:
issue with setting concatenated string variables in __init__ using variables set within __init__ as part of the concatenated string
I am writing a class called "USR" that holds some information about a user who creates an account on my command line e-commerce store (its a college group project that I'm having to d... | issue with setting concatenated string variables in __init__ using variables set within __init__ as part of the concatenated string | I am writing a class called "USR" that holds some information about a user who creates an account on my command line e-commerce store (its a college group project that I'm having to do by myself bc ppl are lazy)
the contents of USR are as follows:
import os
class USR:
def __init__(self,N,a,g,Uname,Pwd,Addr,CC):
... | [
"def __init__(self,N,a,g,Uname,Pwd,Addr,CC):\n Name = N\n age = a\n gender = g\n Username = Uname\n Password = Pwd\n Address = Addr\n CCinfo = CC\n\nYou need to put self. in front of these variable names. self.Name = N, etc.\n"
] | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074568689_python.txt |
Q:
Python watchdog not processing all files in Windows?
Got this watchdog looking at a folder and using a handler to LPR all newly created files to a specific printer (defined on a command prompt batch). Problem is that when you submit a lot of files the watchdog will only process 8, 9, 10 or 11 of them...
What am I ... | Python watchdog not processing all files in Windows? | Got this watchdog looking at a folder and using a handler to LPR all newly created files to a specific printer (defined on a command prompt batch). Problem is that when you submit a lot of files the watchdog will only process 8, 9, 10 or 11 of them...
What am I doing wrong? I'm pretty sure there's something wrong with ... | [
"You should try changing the buffer size of watchdog. Look at this.\ntry to use a bigger buffer size:\nValue to change\n"
] | [
0
] | [] | [] | [
"lpr",
"python",
"watchdog"
] | stackoverflow_0071886564_lpr_python_watchdog.txt |
Q:
Write image to Windows clipboard in python with PIL and win32clipboard?
I'm trying to open an image file and copy the image to the Windows clipboard. Is there a way to fix this:
import win32clipboard
from PIL import Image
def send_to_clipboard(clip_type, data):
win32clipboard.OpenClipboard()
win32clipbo... | Write image to Windows clipboard in python with PIL and win32clipboard? | I'm trying to open an image file and copy the image to the Windows clipboard. Is there a way to fix this:
import win32clipboard
from PIL import Image
def send_to_clipboard(clip_type, data):
win32clipboard.OpenClipboard()
win32clipboard.EmptyClipboard()
win32clipboard.SetClipboardData(clip_type, data)
... | [
"from cStringIO import StringIO\nimport win32clipboard\nfrom PIL import Image\n\ndef send_to_clipboard(clip_type, data):\n win32clipboard.OpenClipboard()\n win32clipboard.EmptyClipboard()\n win32clipboard.SetClipboardData(clip_type, data)\n win32clipboard.CloseClipboard()\n\nfilepath = 'image.jpg'\nimag... | [
9,
1,
1,
0
] | [] | [] | [
"python",
"python_imaging_library",
"pywin32"
] | stackoverflow_0007050448_python_python_imaging_library_pywin32.txt |
Q:
Opencv warning000.211
I've been messing around with cv2 and pytesseract last few days and everything was going well until about an hour ago when I kept getting this error
"[ WARN:0@0.211] global D:\a\opencv-python\opencv-python\opencv\modules\imgcodecs\src\loadsave.cpp (239) cv::findDecoder imread_('hello.png'): ... | Opencv warning000.211 | I've been messing around with cv2 and pytesseract last few days and everything was going well until about an hour ago when I kept getting this error
"[ WARN:0@0.211] global D:\a\opencv-python\opencv-python\opencv\modules\imgcodecs\src\loadsave.cpp (239) cv::findDecoder imread_('hello.png'): can't open/read file: check... | [
"Okay first and foremost thank you both. I figured it out just went into the path where my python.exe was and did the following python39\\python.exe -m pip install opencv-python\n",
"i faced the same issue :\n\"Pictures\\screen1.jpg\" \n[ WARN:0@447.011] global D:\\a\\opencv-python\\opencv-pythonA\\opencv\\module... | [
1,
0
] | [
"Try img = cv2.imread(r'hello.png') and see if it helps.\n\n"
] | [
-1
] | [
"ocr",
"opencv",
"python",
"visual_studio_code"
] | stackoverflow_0070676894_ocr_opencv_python_visual_studio_code.txt |
Q:
Running Python from Atom
In Sublime, we have an easy and convent way to run Python or almost any language for that matter using ⌘ + b (or ctrl + b)
Where the code will run in a small window below the source code and can easily be closed with the escape key when no longer needed.
Is there a way to replicate this fu... | Running Python from Atom | In Sublime, we have an easy and convent way to run Python or almost any language for that matter using ⌘ + b (or ctrl + b)
Where the code will run in a small window below the source code and can easily be closed with the escape key when no longer needed.
Is there a way to replicate this functionally with Github's atom ... | [
"The script package does exactly what you're looking for: https://atom.io/packages/script\nThe package's documentation also contains the key mappings, which you can easily customize.\n",
"Download and Install package here: https://atom.io/packages/script\nTo execute the python command in atom use the below shortc... | [
101,
17,
3,
1,
0,
0,
0
] | [] | [] | [
"atom_editor",
"python"
] | stackoverflow_0025585500_atom_editor_python.txt |
Q:
What is the source code of the Python function intersection()
What is the source code of the Python function intersection()
i don't know where to find the code
A:
It's implemented in c.See the set implementation of the cpython source code:
https://github.com/python/cpython/blob/135ec7cefbaffd516b77362ad2b2ad1025... | What is the source code of the Python function intersection() | What is the source code of the Python function intersection()
i don't know where to find the code
| [
"It's implemented in c.See the set implementation of the cpython source code:\nhttps://github.com/python/cpython/blob/135ec7cefbaffd516b77362ad2b2ad1025af462e/Objects/setobject.c\n"
] | [
1
] | [] | [] | [
"intersection",
"python"
] | stackoverflow_0074568804_intersection_python.txt |
Q:
Django AllAuth - How to manually send a reset-password email?
In my application I am using Django Allauth. I don't have any registration form for users. The admin is going to register users by uploading an excel file that contains user info. I have done all of this and users are saved in the user table by auto gen... | Django AllAuth - How to manually send a reset-password email? | In my application I am using Django Allauth. I don't have any registration form for users. The admin is going to register users by uploading an excel file that contains user info. I have done all of this and users are saved in the user table by auto generating passwords. After I upload user lists and save them in datab... | [
"It's possible. My solution implements a User model post_save signal to call the Allauth Password reset view which will send the user the email. The first thing to consider is to make the user email address mandatory in the admin user create form (as explained here). And then use this code:\nfrom allauth.account.vi... | [
15,
4,
0
] | [] | [] | [
"django",
"django_allauth",
"email",
"python"
] | stackoverflow_0045845846_django_django_allauth_email_python.txt |
Q:
Pandas: How to subtract value from columns by rows from different dataframes
Using Pandas data frames, how do I subtract to find the differences in columns '(x$1000)'
and 'PRN AMT' between data frames based on 'CUSIP'(which acts as a unique id)? The dataset I provided is a sample, so the solution must be able to c... | Pandas: How to subtract value from columns by rows from different dataframes | Using Pandas data frames, how do I subtract to find the differences in columns '(x$1000)'
and 'PRN AMT' between data frames based on 'CUSIP'(which acts as a unique id)? The dataset I provided is a sample, so the solution must be able to contend with a different order. I've tried reading documentation on dataframe.subtr... | [
"Create MultiIndex by CUSIP,TICKER and subtract by DataFrame.sub, last DataFrame.reset_index and change order of columns by DataFrame.reindex:\ndf = (df_1.set_index(['CUSIP','TICKER'])\n .sub(df_2.set_index(['CUSIP','TICKER']))\n .reset_index()\n .reindex(df_1.columns, axis=1))\nprint (df... | [
3
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074568697_pandas_python.txt |
Q:
How do I get multiple output dataframes into one large dataframe from web scraping multiple pages?
I am very new to python and have no idea where to begin to get this problem resolved. I have been able to get multiple pages of tables formated to a pandas dataframe, but I would like them to be in one large data fra... | How do I get multiple output dataframes into one large dataframe from web scraping multiple pages? |
I am very new to python and have no idea where to begin to get this problem resolved. I have been able to get multiple pages of tables formated to a pandas dataframe, but I would like them to be in one large data frame rather than multiple small ones
from bs4 import BeautifulSoup
import requests
import pandas as pd
... | [
"Here is how you can achieve your goal:\nimport requests\nfrom bs4 import BeautifulSoup as bs\nimport pandas as pd\nfrom tqdm import tqdm ## if using Jupyter: from tqdm.notebook import tqdm \n\npd.set_option('display.max_columns', None)\npd.set_option('display.max_colwidth', None)\n\nheaders = {\n 'User-Agent': ... | [
0
] | [] | [] | [
"pandas",
"python",
"web_scraping"
] | stackoverflow_0074568090_pandas_python_web_scraping.txt |
Q:
Can I measure the time between clocking in and out using python?
So I am making a clock in, out system and I seem to be running into a problem with the code as I am fairly new to the whole programming thing. I don't have a single clue how to start off except the fact that I need the time library help wanted please... | Can I measure the time between clocking in and out using python? | So I am making a clock in, out system and I seem to be running into a problem with the code as I am fairly new to the whole programming thing. I don't have a single clue how to start off except the fact that I need the time library help wanted please lol
I got the lib and started to mess around with the code a bit and ... | [
"You can use the datetime module for this.\nfrom datetime import datetime\n\nclocked_in = \"21/11/22 3:10:52\"\nclocked_out = \"21/11/22 10:30:33\"\n\n#changing to datetime\nt1 = datetime.strptime(clocked_in, \"%d/%m/%y %H:%M:%S\")\nt2 = datetime.strptime(clocked_out, \"%d/%m/%y %H:%M:%S\")\n\n#calculating the time... | [
0
] | [] | [] | [
"python",
"system",
"timer"
] | stackoverflow_0074568747_python_system_timer.txt |
Q:
Saving content of a webpage using BeautifulSoup and extract data
I'm new to Python and i'm trying to extract data from the webpage following info, and export them as save it in a csv file to work on it:
SYNOPS from 65528, Odienne (Cote d'Ivoire)
202211070600 AAXX 07064 65528 42958 51202 10213 20208 39654 40126 850... | Saving content of a webpage using BeautifulSoup and extract data | I'm new to Python and i'm trying to extract data from the webpage following info, and export them as save it in a csv file to work on it:
SYNOPS from 65528, Odienne (Cote d'Ivoire)
202211070600 AAXX 07064 65528 42958 51202 10213 20208 39654 40126 85030 333 20209 58014 79999 85360=
202211061800 AAXX 06184 65528 11458 61... | [
"It's not quite clear how you want to structure the data in the csv, but any pandas DataFrame can be expected to be saved as CSV with .to_csv. For example:\ncsvRows = []\nfor pCont in soup.find_all('pre'): \n csvRows += [( \n ('[About Query]', '\\n'.join([\n ql[1:].strip() for ql in pb.split('\... | [
0
] | [] | [] | [
"beautifulsoup",
"csv",
"python",
"text_extraction",
"web_scraping"
] | stackoverflow_0074546147_beautifulsoup_csv_python_text_extraction_web_scraping.txt |
Q:
How do you locally load model.tar.gz file from Sagemaker?
I'm new to Sagemaker and I trained a classifier model with the built in XGBoost. It saved a "Model.tar.gz" at an S3. I downloaded the file because I was planning to deploy the model else where. So to experiment, I started loading the file locally first. I t... | How do you locally load model.tar.gz file from Sagemaker? | I'm new to Sagemaker and I trained a classifier model with the built in XGBoost. It saved a "Model.tar.gz" at an S3. I downloaded the file because I was planning to deploy the model else where. So to experiment, I started loading the file locally first. I tried this code.
import pickle as pkl
import tarfile
t = tarfil... | [
"found the answer to my question. Apparently, the sagemaker environment is using an old build of XGBoost, around version 0.9. As the XGboost team make constant upgrades and changes to their library, AWS was unable to keep up with it.\nThat said I was able to run my code below by downgrading the XGBoost library on m... | [
0
] | [] | [] | [
"amazon_sagemaker",
"amazon_web_services",
"machine_learning",
"python"
] | stackoverflow_0074556459_amazon_sagemaker_amazon_web_services_machine_learning_python.txt |
Q:
How to append a list of dataframes by removing header from all list and keeping only first header
I have a list of dataframes
li = [df1, df2,..]
All the dataframes in the list have common headers. I am appending the list of dataframes into a single df as follows:
path ="..."
all_files=glob.glob(path+"*.csv")
all_f... | How to append a list of dataframes by removing header from all list and keeping only first header | I have a list of dataframes
li = [df1, df2,..]
All the dataframes in the list have common headers. I am appending the list of dataframes into a single df as follows:
path ="..."
all_files=glob.glob(path+"*.csv")
all_files
li = []
for filename in all_files:
df=pd.read_csv(filename,index_col=None,header=None)
li.... | [
"Use pd.concat()\nFor more info you can refer\nhttps://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.concat.html\n",
"You can simply concat in loop itself.\nLet's assume csv1 looks like.\n Ref tim\n0 1 mow\n1 2 pak\n2 3 bow\n3 4 tring\n\nLet's assume csv2 looks like.\n ... | [
0,
0
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074568837_dataframe_pandas_python.txt |
Q:
I want to complete the quiz with variables or lists without Python input
import random
number = random.randint(1, 10)
player_name = input("Hello, What's your name?")
number_of_guesses = 0
print('okay! '+ player_name+ ' I am Guessing a number between 1 and 10:')
while number_of_guesses < 5:
guess = int(in... | I want to complete the quiz with variables or lists without Python input | import random
number = random.randint(1, 10)
player_name = input("Hello, What's your name?")
number_of_guesses = 0
print('okay! '+ player_name+ ' I am Guessing a number between 1 and 10:')
while number_of_guesses < 5:
guess = int(input())
number_of_guesses += 1`
if guess < number:
print('Your gues... | [
"See my code .\nCode-:\nimport random\nlis=[1, 2, 3, 4, 5, 8, 9, 10]\nprint('I am Guessing a number between 1 and 10:\\n')\nfor number in lis:\n number_of_guesses = 0\n while number_of_guesses<3:\n guess_number=random.randint(1,10)\n if number<guess_number:\n number_of_guesses+=1\n ... | [
1
] | [] | [] | [
"python"
] | stackoverflow_0074568745_python.txt |
Q:
Post is working in model view set, with functions name post
class Product_List(viewsets.ModelViewSet): # >>> List of products & add product to cart
permission_classes = [IsAuthenticated, ]
queryset = Item.objects.all()
serializer_class = ProductListSerializer
def post(self, request, *ar... | Post is working in model view set, with functions name post |
class Product_List(viewsets.ModelViewSet): # >>> List of products & add product to cart
permission_classes = [IsAuthenticated, ]
queryset = Item.objects.all()
serializer_class = ProductListSerializer
def post(self, request, *args, **kwargs): # <<< post is working
items = get_objec... | [
"Everything is correct just rename your post method with create mentioned below\ndef create(self, request, *args, **kwargs): # <<< post is working\n"
] | [
0
] | [] | [] | [
"django_rest_framework",
"django_rest_viewsets",
"django_views",
"python"
] | stackoverflow_0074569026_django_rest_framework_django_rest_viewsets_django_views_python.txt |
Q:
googletrans stopped working with error 'NoneType' object has no attribute 'group'
I was trying googletrans and it was working quite well. Since this morning I started getting below error. I went through multiple posts from stackoverflow and other sites and found probably my ip is banned to use the service for some... | googletrans stopped working with error 'NoneType' object has no attribute 'group' | I was trying googletrans and it was working quite well. Since this morning I started getting below error. I went through multiple posts from stackoverflow and other sites and found probably my ip is banned to use the service for sometime. I tried using multiple service provider internet that has different ip and stil f... | [
"Update 06.12.20: A new 'official' alpha version of googletrans with a fix was released\nInstall the alpha version like this:\npip install googletrans==3.1.0a0\n\nTranslation example:\ntranslator = Translator()\ntranslation = translator.translate(\"Der Himmel ist blau und ich mag Bananen\", dest='en')\nprint(transl... | [
185,
64,
45,
19,
17,
13,
12,
11,
7,
6,
6,
2,
2,
2,
1,
1,
0,
0
] | [] | [] | [
"google_translate",
"nlp",
"python"
] | stackoverflow_0052455774_google_translate_nlp_python.txt |
Q:
How to reduce steps / line of code for this puzzle in python?
Puzzle
Video Puzzle
Current Code:
for i in range(4):
Dev.step(i+4)
for a in range(3):
Dev.step(i+2)
Dev.turnLeft()
Dev.step(i+2)
From the puzzle it has to be 5 line of code. Currently I'am at 6 line of code. How do I... | How to reduce steps / line of code for this puzzle in python? | Puzzle
Video Puzzle
Current Code:
for i in range(4):
Dev.step(i+4)
for a in range(3):
Dev.step(i+2)
Dev.turnLeft()
Dev.step(i+2)
From the puzzle it has to be 5 line of code. Currently I'am at 6 line of code. How do I make the code simpler ?.
The objective is to get all the Item (blu... | [
"If you can't use semicolons, you can combine the Dev.step(i+4) and Dev.step(i+2) into a single line and changing the sequence of Dev.turnleft() and Dev.step() in the inner loop, so your resulting 5 line solution would something like -\nfor i in range(4):\n Dev.step(2*i+6)\n for a in range(3):\n Dev.tu... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074568999_python.txt |
Q:
GroupBy pandas DataFrame and fill/update with most frequent values
I'm trying to get the most frequent values in a pandas dataframe and fill/update the data with the most frequent value.
Sample Data
import numpy as np
import pandas as pd
test_input = pd.DataFrame(columns=[ 'key', 'value'],
... | GroupBy pandas DataFrame and fill/update with most frequent values | I'm trying to get the most frequent values in a pandas dataframe and fill/update the data with the most frequent value.
Sample Data
import numpy as np
import pandas as pd
test_input = pd.DataFrame(columns=[ 'key', 'value'],
data= [[ 1, 'A' ],
... | [
"Use GroupBy.transform with custom lambda function with Series.mode and iter with next trick for NaNs if empty mode (because missing value(s)):\ntest_input['value'] = (test_input.groupby('key')['value']\n .transform(lambda x: next(iter(x.mode()), np.nan)))\nprint (test_input)\n key... | [
2
] | [] | [] | [
"dataframe",
"group_by",
"pandas",
"python"
] | stackoverflow_0074569127_dataframe_group_by_pandas_python.txt |
Q:
Program exits too early
My code is working properly the only thing I want to change in my program is after congratulations message the program should ask user again to input a number until user input zero as quit.
Til now if I run my code after congratulations message program exits.
import random
import datetime
... | Program exits too early | My code is working properly the only thing I want to change in my program is after congratulations message the program should ask user again to input a number until user input zero as quit.
Til now if I run my code after congratulations message program exits.
import random
import datetime
e = datetime.datetime.now()
p... | [
"since you have not added break inside while loop in playGuessingGame(). so program continuously asking to enter number even though you have entered zero\ndef playGuessingGame(x):\n times = 1\n while number != x:\n times += 1\n if x < number:\n print(\"Too low, try again\")\n ... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074568712_python.txt |
Q:
Best way to get second item of each list inside of a 2D list
I have a 2D list:
items = [['a','b'],['c','d']]
I would like to get a new list containing the last element of each nested list:
new_list = ['b','d']
I can do it like so:
new_list = []
for i in items:
new_list.append(i[-1])
But this feels very clumsy ... | Best way to get second item of each list inside of a 2D list | I have a 2D list:
items = [['a','b'],['c','d']]
I would like to get a new list containing the last element of each nested list:
new_list = ['b','d']
I can do it like so:
new_list = []
for i in items:
new_list.append(i[-1])
But this feels very clumsy for such a simple thing. I was wondering if there was a more elega... | [
"If you have...\nitems = [\n ['a', 'b'],\n ['c', 'd']\n]\n\n...you have a nested list that you can access this way:\n>>> items[0]\n['a', 'b']\n>>> items[0][0]\n\n\nTo have the second element (the element with index 1) of each sublist, I would suggest a list comprehension:\nnew_list = [sublist[1] for sublist i... | [
1,
1,
0,
0
] | [] | [] | [
"list",
"python"
] | stackoverflow_0071115079_list_python.txt |
Q:
compare between the number of dots for 2 strings
I try to compare between two string .
a=1.22.33
b=2.1.33
we can see that the pattern is different:
22 contain 2 number
1 contain 1 number.
my code just compare the first item of the second string and not work on all the loop.
import re
def aa(a,g):
b=re.split(r'... | compare between the number of dots for 2 strings | I try to compare between two string .
a=1.22.33
b=2.1.33
we can see that the pattern is different:
22 contain 2 number
1 contain 1 number.
my code just compare the first item of the second string and not work on all the loop.
import re
def aa(a,g):
b=re.split(r'\.', a)
bb=re.split(r'\.', g)
c=[]
e=[]
... | [
"You are trying to find if substrings contained between dots are the same length:\nd=\"66.22.33\"\nu=\"66.2.33\"\ncompare(d, u)\n>>> False\n\nd=\"66.22.33\"\nu=\"66.11.33\"\ncompare(d, u)\n>>> True\n\nThen you can check it this way:\ndef compare(a, b):\n a = a.split('.')\n b = b.split('.')\n return all(len... | [
0
] | [] | [] | [
"for_loop",
"nested_loops",
"python"
] | stackoverflow_0074569245_for_loop_nested_loops_python.txt |
Q:
How to style the rows of a multiindex dataframe?
I have the following dataframe:
dic = {'US':{'Traffic':{'new':1415, 'repeat':670}, 'Sales':{'new':67068, 'repeat':105677}},
'UK': {'Traffic':{'new':230, 'repeat':156}, 'Sales':{'new':4568, 'repeat':10738}}}
d1 = defaultdict(dict)
for k, v in dic.items():
f... | How to style the rows of a multiindex dataframe? | I have the following dataframe:
dic = {'US':{'Traffic':{'new':1415, 'repeat':670}, 'Sales':{'new':67068, 'repeat':105677}},
'UK': {'Traffic':{'new':230, 'repeat':156}, 'Sales':{'new':4568, 'repeat':10738}}}
d1 = defaultdict(dict)
for k, v in dic.items():
for k1, v1 in v.items():
for k2, v2 in v1.items... | [
"Use custom function with select by DataFrame.loc, then set values by conditions by numpy.where and numpy.select.\nFor me not working light red and light orange color, I use colors hex codes instead:\ndef color(x):\n\n idx = pd.IndexSlice\n\n t = x.loc['Traffic', idx[:, ['new','repeat']]]\n s = x.loc['Sale... | [
1
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074569074_dataframe_pandas_python.txt |
Q:
sum of two arrays of different length
For example I have 2 arrays
arraya[1,1,1,1,1,1,1]
arrayb[0,1,2]
I want to add arrayb to arraya continiously like this:
arraysum[1,2,3,1,2,3,1]
How can I do it?
A:
arraya = [1,1,1,1,1,1,1]
arrayb = [0,1,2]
for i in range(len(arraya)):
arraya[i] += arrayb[i % len(arrayb... | sum of two arrays of different length | For example I have 2 arrays
arraya[1,1,1,1,1,1,1]
arrayb[0,1,2]
I want to add arrayb to arraya continiously like this:
arraysum[1,2,3,1,2,3,1]
How can I do it?
| [
"arraya = [1,1,1,1,1,1,1]\narrayb = [0,1,2]\n\nfor i in range(len(arraya)):\n arraya[i] += arrayb[i % len(arrayb)]\n\nprint arraya\n\nProduces\n[1, 2, 3, 1, 2, 3, 1]\n",
"You can use zip combined with cycle for this:\nif arrayb:\n arraysum = [sum(x) for x in zip(cycle(arrayb), arraya)]\nelse:\n arraysum ... | [
0,
0,
0,
0,
0
] | [] | [] | [
"arrays",
"python",
"python_3.x"
] | stackoverflow_0058061311_arrays_python_python_3.x.txt |
Q:
GCC Fail on Python2.7-alpine Docker Image
I am trying to install librabbitmq and MySQL-python on python:2.7-alpine base image but getting gcc error. I have tried multiple solutions without success. Any help is much appreciated.
Dockerfile
FROM python:2.7-alpine
WORKDIR /usr/src/app
RUN apk add --no-cache gcc g++ ... | GCC Fail on Python2.7-alpine Docker Image | I am trying to install librabbitmq and MySQL-python on python:2.7-alpine base image but getting gcc error. I have tried multiple solutions without success. Any help is much appreciated.
Dockerfile
FROM python:2.7-alpine
WORKDIR /usr/src/app
RUN apk add --no-cache gcc g++ make
RUN apk add --no-cache build-base python2... | [
"Try updating Dockerfile by moving\nRUN apk update\nOn top after your image\nIt worked for me.\n"
] | [
0
] | [] | [] | [
"docker",
"gcc",
"python"
] | stackoverflow_0074551024_docker_gcc_python.txt |
Q:
Get List of Timezones with GMT offset
Can someone help me in getting a list of timezones with GMT/UTC (I believe these are the same) offset like
(GMT+5:30) Asia/Kolkata.
Thank You
A:
Combining Python: datetime tzinfo time zone names documentation and Display the time in a different time zone, you can use
import ... | Get List of Timezones with GMT offset | Can someone help me in getting a list of timezones with GMT/UTC (I believe these are the same) offset like
(GMT+5:30) Asia/Kolkata.
Thank You
| [
"Combining Python: datetime tzinfo time zone names documentation and Display the time in a different time zone, you can use\nimport datetime\nimport zoneinfo\n\n# UTC offsets of time zones depend on the date, so we need a reference date:\ndt = datetime.datetime.now(datetime.timezone.utc)\n\nprint(dt.isoformat(times... | [
0
] | [] | [] | [
"datetime",
"python",
"python_3.x",
"timezone",
"timezone_offset"
] | stackoverflow_0074562252_datetime_python_python_3.x_timezone_timezone_offset.txt |
Q:
How to emit result in Tekton with python script?
I my Tekton pipeline I want to emit a result so that $(results.myresult) can be used in the next pipeline task. The code looks like this:
apiVersion: tekton.dev/v1beta1
kind: Task
name: foo
namespace: bar
...
spec:
results:
- name: myresult
script: |
... | How to emit result in Tekton with python script? | I my Tekton pipeline I want to emit a result so that $(results.myresult) can be used in the next pipeline task. The code looks like this:
apiVersion: tekton.dev/v1beta1
kind: Task
name: foo
namespace: bar
...
spec:
results:
- name: myresult
script: |
#!/usr/bin/env bash
# do some meaningful stuff h... | [
"First thing I would look at .... your sys.stdout.write kind of suggests you are writing stuff ... to stdout. While you mean to write this to your RESULTS ($(results.myresult)).\n"
] | [
0
] | [] | [] | [
"bash",
"linux",
"python",
"shell",
"tekton"
] | stackoverflow_0074547609_bash_linux_python_shell_tekton.txt |
Q:
What are the Best way to learn python for non IT person
As a mechanical engineer how I start to learn python and what I need to learn in python For machine learning in mechanical field
Can anyone Suggest best
A:
Well, there are plenty of the free courses on YouTube. Personally, I am not in the machine learning f... | What are the Best way to learn python for non IT person | As a mechanical engineer how I start to learn python and what I need to learn in python For machine learning in mechanical field
Can anyone Suggest best
| [
"Well, there are plenty of the free courses on YouTube. Personally, I am not in the machine learning field.\nHowever, to get started in Python, I would suggest the following Python video: https://www.youtube.com/watch?v=rfscVS0vtbw\nThis is the same video I used when I first got started in Python.\nOnce you have th... | [
0
] | [] | [] | [
"machine_learning",
"python"
] | stackoverflow_0074569369_machine_learning_python.txt |
Q:
Django filter queryset only if variable is not null
I have a queryset it filter by 2 variables
family = ModelsClass.objects.filter(foo=var1).filter(bar=var2)
If var1 and var2 are not null everything work but var1 and var2 can be Null.
In this case i need to exclude the Null one.
For example, if var1 is Null it mu... | Django filter queryset only if variable is not null | I have a queryset it filter by 2 variables
family = ModelsClass.objects.filter(foo=var1).filter(bar=var2)
If var1 and var2 are not null everything work but var1 and var2 can be Null.
In this case i need to exclude the Null one.
For example, if var1 is Null it must filter only by var2 and the other way around.
Is there... | [
"Why don't you check if variable is null and then filter it? You don't have to do it in one line. Django's queryset objects are lazy evaluated and you can filter or do other things in separate lines.\nfamily_queryset = ModelClass.objects.all()\n\nif var1:\n family_queryset = family_queryset.filter(foo=var1)\n\ni... | [
6,
3,
0
] | [] | [] | [
"django",
"django_queryset",
"python"
] | stackoverflow_0066203834_django_django_queryset_python.txt |
Q:
Modbus missing bytes error using pymodbus as Serial/RTU master with arduino slaves runnning ArduinoModbus
I'm facing some issues with a Modbus RTU implementation. I have 2x Arduino MKR Zeros with RS485 hats/expansions as my 2 slave devices (using the ArduinoModbus library). I am trying to poll the devices from my ... | Modbus missing bytes error using pymodbus as Serial/RTU master with arduino slaves runnning ArduinoModbus | I'm facing some issues with a Modbus RTU implementation. I have 2x Arduino MKR Zeros with RS485 hats/expansions as my 2 slave devices (using the ArduinoModbus library). I am trying to poll the devices from my PC (Windows) using python and the pymodbus library, running at 9600 baud.
I can succesfully transfer data. The ... | [
"The log shows that data is received only partially: Expected 15 bytes Received 11 bytes. This may be caused by wrong inter-character timing, i.e. a silent time between characters is erroneously interpreted as end of message. By specifying client.strict = False the Modbus specification inter-character timing is en... | [
1
] | [] | [] | [
"arduino",
"data_loss",
"modbus",
"pymodbus",
"python"
] | stackoverflow_0074555963_arduino_data_loss_modbus_pymodbus_python.txt |
Q:
What is the meaning of indexing in plt.plot()
I am learning about matplotlib and found code : plt.plot([])[0]. Can u explain what means of index on that code?
Im trying to make animation using matplotlib and one of the example using that code. I dont understand the meaning of index in that code
A:
lets say you p... | What is the meaning of indexing in plt.plot() | I am learning about matplotlib and found code : plt.plot([])[0]. Can u explain what means of index on that code?
Im trying to make animation using matplotlib and one of the example using that code. I dont understand the meaning of index in that code
| [
"lets say you plot multiple lines with plt.plot, e.g. like this\nimport numpy as np\nfrom matplotlib import pyplot as plt\n\n# evenly sampled time at 200ms intervals\nt = np.arange(0., 5., 0.2)\n\n# red dashes, blue squares and green triangles\nplt.plot(t, t, 'r--', t, t**2, 'bs', t, t**3, 'g^')\nplt.show()\n\n\nyo... | [
0
] | [] | [] | [
"animation",
"matplotlib",
"python"
] | stackoverflow_0074569266_animation_matplotlib_python.txt |
Q:
How to draw points of a sphere in a cubic environment?
Given a center point (x0, y0, z0) and a radius (g_radius)
I want to use Python to generate points in a sphere in a cubic world (= Minecraft).
I'm trying to use this algorithm (I found it here on so) but it's not precise and I have to increase the number of sam... | How to draw points of a sphere in a cubic environment? | Given a center point (x0, y0, z0) and a radius (g_radius)
I want to use Python to generate points in a sphere in a cubic world (= Minecraft).
I'm trying to use this algorithm (I found it here on so) but it's not precise and I have to increase the number of samples to a ridiculous huge number to get almost all the point... | [
"This sounds like a job for raster_geometry:\n\nimport raster_geometry\nfrom matplotlib import pyplot as plt\n\n# define degree of rasterization\nradius = 7.5\n\n# create full sphere\nsphere_coords = raster_geometry.sphere(int(2*radius), radius)\n# make it hollow\nsphere_coords = raster_geometry.unfill(sphere_coord... | [
1
] | [] | [] | [
"python"
] | stackoverflow_0074556953_python.txt |
Q:
Error in Level Order Traversal of Binary Tree
What mistake have i done here ?
def levelOrder(root):
#Write your code here
que = []
que.append(root)
while que != []:
coot = que.pop()
print(coot.data,end=" ")
if coot.left is not None:
que.append(coot.left)
if coot.right is not None:
... | Error in Level Order Traversal of Binary Tree | What mistake have i done here ?
def levelOrder(root):
#Write your code here
que = []
que.append(root)
while que != []:
coot = que.pop()
print(coot.data,end=" ")
if coot.left is not None:
que.append(coot.left)
if coot.right is not None:
que.append(coot.right)
OutPut Expected:1 2 5 3 6 ... | [
"You are appending nodes to end end of the list que(using append()). And also removing the nodes from the end of the list que(using list.pop()), this would not preserve the order, so for something like\n 1\n / \\\n 2 3 \n / \\ / \\\n 4 5 6 7 \n\nAfter firs... | [
0
] | [] | [] | [
"binary_search_tree",
"binary_tree",
"python"
] | stackoverflow_0074569462_binary_search_tree_binary_tree_python.txt |
Q:
How to find specific text under multiple spans in Beautifulsoup?
I want to extract the IPA keys under the French section of the wiki page:
https://en.wiktionary.org/wiki/son#French
I want only the data in the french section.
from bs4 import BeautifulSoup
from bs4 import BeautifulSoup
import requests
import pandas ... | How to find specific text under multiple spans in Beautifulsoup? | I want to extract the IPA keys under the French section of the wiki page:
https://en.wiktionary.org/wiki/son#French
I want only the data in the french section.
from bs4 import BeautifulSoup
from bs4 import BeautifulSoup
import requests
import pandas as pd
def main():
test_url_page = 'https://en.wiktionary.or... | [
"Close to your goal, but you have to check if the next elements\nor .find_next_siblings() has your IPA element and break the iteration until there is a <hr>, that defines the next section:\nfrench_section = soup.find('span',{'id':'French'}).parent\nfor tag in french_section.find_next_siblings():\n if tag == 'hr'... | [
1
] | [] | [] | [
"beautifulsoup",
"python",
"web_scraping"
] | stackoverflow_0074569474_beautifulsoup_python_web_scraping.txt |
Q:
django-rest-swagger nested serializers with readonly fields not rendered properly
I'm building an API with django-rest-framework and I started using django-rest-swagger for documentation.
I have a nested serializer with some read_only fields, like this:
# this is the nested serializer
class Nested(serializers.Seri... | django-rest-swagger nested serializers with readonly fields not rendered properly | I'm building an API with django-rest-framework and I started using django-rest-swagger for documentation.
I have a nested serializer with some read_only fields, like this:
# this is the nested serializer
class Nested(serializers.Serializer):
normal_field = serializers.CharField(help_text="normal")
readonly_fiel... | [
"1. of everything please use drf-yasg for documentation .\n2. you can find its implementation in one of my repository Kirpi and learn how to use that.\n3. if you in 3. ; have question,let me know.\n",
"Try to use drf_yasg instead, Swagger will generate the documentation for APIs, but it's not absolutely right!\nI... | [
0,
0
] | [] | [] | [
"django",
"django_rest_framework",
"documentation_generation",
"python"
] | stackoverflow_0029901131_django_django_rest_framework_documentation_generation_python.txt |
Q:
Using postgresql with Django
I keep getting this error in the web page
Using postgresql.
pgadmin 4
Unauthorized
The server could not verify that you are authorized to access the URL requested. You either supplied the wrong credentials (e.g. a bad password), or your browser doesn't understand how to supply the cred... | Using postgresql with Django | I keep getting this error in the web page
Using postgresql.
pgadmin 4
Unauthorized
The server could not verify that you are authorized to access the URL requested. You either supplied the wrong credentials (e.g. a bad password), or your browser doesn't understand how to supply the credentials required.
settings.py
... | [
"I think you did wrong in database in settings.py file. You should use os.environ.get instead of env.\nChange this:\n'NAME': env('DB_NAME'),\n\nTo this:\n'NAME': os.environ.get('DB_NAME'),\n\n"
] | [
0
] | [] | [] | [
"django",
"postgresql",
"python"
] | stackoverflow_0074569630_django_postgresql_python.txt |
Q:
Added items won't print anything
I seem to be stuck on if choice == 3.
It should go like this:
PRINTING LIST...
item1
item2
item3
item4
However, it won't print anything.
Here's my code:
print(" MY GROCERY LIST ")
def addtolist():
print("=====================")
print("What would you like to do?")
pr... | Added items won't print anything | I seem to be stuck on if choice == 3.
It should go like this:
PRINTING LIST...
item1
item2
item3
item4
However, it won't print anything.
Here's my code:
print(" MY GROCERY LIST ")
def addtolist():
print("=====================")
print("What would you like to do?")
print("1 - Add an item")
print("2 - ... | [
"You need to declare shopping list before the while loop, because now you initialise it every time you pick an option\n"
] | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074569572_python.txt |
Q:
How to add different type of files in postgresql on Python
I need to add different types of files (CSV, XML, xlsx, etc.) to the database (Postgresql). I know how I can read it via pandas, but I have some issues with adding this to the database.
What libraries do I need to use? And does it need to convert them into... | How to add different type of files in postgresql on Python | I need to add different types of files (CSV, XML, xlsx, etc.) to the database (Postgresql). I know how I can read it via pandas, but I have some issues with adding this to the database.
What libraries do I need to use? And does it need to convert them into one format?
| [
"\nRead files with pandas:\ncsv_df = pd.read_csv('file.csv')\nxml_df = pd.read_xml('file.xml')\nxlsx_df = pd.read_excel('file.xlsx')\n\nAdd tables in db with columns like in your file\n\nAdd files to db\nxlsx_df.to_sql('table_name', engine, if_exists='replace', index=False)\n\n\n"
] | [
1
] | [] | [] | [
"csv",
"postgresql",
"python",
"xlsx",
"xml"
] | stackoverflow_0074515976_csv_postgresql_python_xlsx_xml.txt |
Q:
Overwriting column data basis multiple condition
Existing Dataframe :
Id last_dt_of_payment Group payer_status
A1 22/08/2022 x 1
A2 21/05/2022 x 1
A3 01/09/2022 y 1
A4 22/01/2022 y ... | Overwriting column data basis multiple condition | Existing Dataframe :
Id last_dt_of_payment Group payer_status
A1 22/08/2022 x 1
A2 21/05/2022 x 1
A3 01/09/2022 y 1
A4 22/01/2022 y 1
A5 26/02/2022 p 1... | [
"EDIT:\ngroups = ['x','y']\n\n#convert to datetimes\ndf['last_dt_of_payment'] = pd.to_datetime(df['last_dt_of_payment'], dayfirst=True)\n\n#create testing Period\ntd = pd.Period('2022-09', freq='m')\n#get column to months periods\nper = df['last_dt_of_payment'].dt.to_period('m')\n\n#chain both mask\nm = df['Group']... | [
1
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074569681_dataframe_pandas_python.txt |
Q:
Python folium problem with editing draw plugin
I would like to make some edits to the Python Folium.draw plugin.
I have the code from the following link:
https://github.com/python-visualization/folium/blob/main/folium/plugins/draw.py
After applying it to my code I have an error:
if self.export:
NameError: name 'se... | Python folium problem with editing draw plugin | I would like to make some edits to the Python Folium.draw plugin.
I have the code from the following link:
https://github.com/python-visualization/folium/blob/main/folium/plugins/draw.py
After applying it to my code I have an error:
if self.export:
NameError: name 'self' is not defined
def __init__(
self,
expo... | [
"Minimal working example:\nimport folium\nfrom branca.element import Element, Figure, MacroElement\nfrom jinja2 import Template\nfrom folium.elements import JSCSSMixin\n\n\nclass Draw(JSCSSMixin, MacroElement):\n def __init__(\n self,\n export=False,\n filename=\"data.geojson\",\n pos... | [
1
] | [] | [] | [
"folium",
"python"
] | stackoverflow_0074536711_folium_python.txt |
Q:
Name "os" is not defined, even tho it has been imported
I have been trying to use os to get the parent directory of a file and then print it. However, when i execute it, i get the following error:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'os' is not defined
The firs... | Name "os" is not defined, even tho it has been imported | I have been trying to use os to get the parent directory of a file and then print it. However, when i execute it, i get the following error:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'os' is not defined
The first line of my code is import os, os.path. This is my code for ... | [] | [] | [
"change first line to:\nimport os\nfrom os import path\n\nif that still doesn't work then you probably have a deeper problem with your setup. It seems like the location you are installing modules to with pip is a different python interpreter than the one you are running. In the python terminal of your vs code, try ... | [
-4
] | [
"python",
"windows"
] | stackoverflow_0074569705_python_windows.txt |
Q:
Bin datetime.date objects to create groups
I have some data that I would like to split into four groups based upon particular points in time - the points in time being given by particular dates.
The data I have is this (assume that df has already been created):
df["date"] = pd.to_datetime(df["date"], format = "%Y-... | Bin datetime.date objects to create groups | I have some data that I would like to split into four groups based upon particular points in time - the points in time being given by particular dates.
The data I have is this (assume that df has already been created):
df["date"] = pd.to_datetime(df["date"], format = "%Y-%m-%d")
df["year"] = df["date"].dt.year
df["mont... | [
"You may want to take a look at pd.cut.\n# toy data\ndf = pd.DataFrame(pd.date_range('2020-01-01', '2022-01-01'), columns = ['date'])\n\n date\n0 2020-01-01\n1 2020-01-02\n2 2020-01-03\n3 2020-01-04\n4 2020-01-05\n.. ...\n\nYou can generate the labels and boundaries for the bins.\nfrom nu... | [
2,
0
] | [] | [] | [
"date",
"datetime",
"pandas",
"python"
] | stackoverflow_0074555185_date_datetime_pandas_python.txt |
Q:
Python code to copy and update excel formulas dynamically
Target: I am trying to split an excel file into multiple files based on some filter given within the sheet.
Problem: An issue is arising while copying the formula columns as it is not updating the row numbers inside the formula while splitting them into mul... | Python code to copy and update excel formulas dynamically | Target: I am trying to split an excel file into multiple files based on some filter given within the sheet.
Problem: An issue is arising while copying the formula columns as it is not updating the row numbers inside the formula while splitting them into multiple sheets.
For Ex: In the master file, the formula is "=LEFT... | [
"def update_formula(df: pd.DataFrame, formula_col):\n '''\n Function to update formulas for each Manager\n :param df: DataFrame for one specific manager.\n '''\n for _col in formula_col:\n col_alpha = formula_col[_col][0]\n formula = formula_col[_col][1]\n index = 2\n for... | [
0
] | [] | [] | [
"automation",
"excel",
"openpyxl",
"pandas",
"python"
] | stackoverflow_0074326614_automation_excel_openpyxl_pandas_python.txt |
Q:
AttributeError: 'tensorflow.python.framework.ops.EagerTensor' object has no attribute 'assign'
I am trying to optimize my machine learning model by using weight pruning. But no matter what I do I cant get rid of the error AttributeError:
'tensorflow.python.framework.ops.EagerTensor' object has no attribute
'assig... | AttributeError: 'tensorflow.python.framework.ops.EagerTensor' object has no attribute 'assign' | I am trying to optimize my machine learning model by using weight pruning. But no matter what I do I cant get rid of the error AttributeError:
'tensorflow.python.framework.ops.EagerTensor' object has no attribute
'assign'
Here is my code for pruning
#pruning
import tensorflow_model_optimization as tfmot
import numpy... | [
"##Pruning \nbase_model = tf.keras.models.load_model('modelclustored2.h5')\nbase_model.load_weights(pretrained_weights) # optional but recommended.\n\nmodel_for_pruning = tfmot.sparsity.keras.prune_low_magnitude(base_model)\ncallbacks = [\n tfmot.sparsity.keras.UpdatePruningStep(),\n # Log sparsity and other ... | [
0
] | [] | [] | [
"pruning",
"python",
"tensorflow",
"tensorflow_lite"
] | stackoverflow_0074543162_pruning_python_tensorflow_tensorflow_lite.txt |
Q:
Flask SQLAlchemy 'dict' object has no attribute '_sa_instance_state'
I am getting the following error when trying to create a new document and associated relationship with an array of counterparties.
AttributeError: 'dict' object has no attribute '_sa_instance_state'
I think the issue must exist with my model de... | Flask SQLAlchemy 'dict' object has no attribute '_sa_instance_state' | I am getting the following error when trying to create a new document and associated relationship with an array of counterparties.
AttributeError: 'dict' object has no attribute '_sa_instance_state'
I think the issue must exist with my model definition, if I remove "backref="documents" for the counterparties relation... | [
"As @MatsLindh alluded to the issue is with types. The solution is here:\nHow to use nested pydantic models for sqlalchemy in a flexible way\nEdit to include solution used:\nCredit to Daan Beverdam:\nI gave every nested pydantic model a Meta class containing the corresponding SQLAlchemy model. Like so:\nfrom pydant... | [
2,
0
] | [] | [] | [
"fastapi",
"python",
"sqlalchemy"
] | stackoverflow_0073122511_fastapi_python_sqlalchemy.txt |
Q:
For loop to check if object already exists in loop not working PYTHON
inventory should be a list with some objects
winner is an object that was randomly selected
for x in inventory:
if x == winner:
print('You got a duplicate, adding 3 pulls')
pullAmount += 3
else:
inventory.append(w... | For loop to check if object already exists in loop not working PYTHON | inventory should be a list with some objects
winner is an object that was randomly selected
for x in inventory:
if x == winner:
print('You got a duplicate, adding 3 pulls')
pullAmount += 3
else:
inventory.append(winner)
break
I want to make it so that there will not be any repeats i... | [] | [] | [
"use is operator it will test 2 objects are same. The test returns True if the two objects are the same object else it will return False.\n"
] | [
-1
] | [
"list",
"python"
] | stackoverflow_0074569867_list_python.txt |
Q:
Pandas to_records() dtype conversion to char / unicode issue
Pandas to_records() throws an error while numpy.array is behaving like expected.
data = [('myID', 5), ('myID', 10)]
myDtype = numpy.dtype([('myID', numpy.str_,4),
('length', numpy.uint16)])
Working:
arr = numpy.array(data, dtype=m... | Pandas to_records() dtype conversion to char / unicode issue | Pandas to_records() throws an error while numpy.array is behaving like expected.
data = [('myID', 5), ('myID', 10)]
myDtype = numpy.dtype([('myID', numpy.str_,4),
('length', numpy.uint16)])
Working:
arr = numpy.array(data, dtype=myDtype)
output: [('myID', 5) ('myID', 10)]
This is not working
d... | [
"Ok so from what I understand, the way you wrote your variable myDtype isn't compatible with the column names your dataframe has.\nYour current dataframe columns are int values of 0 and 1, causing your error (trying to match the int 0 to your naming \"myID\").\n(Not entirely sure about that one so someone might wan... | [
0,
0
] | [] | [] | [
"numpy",
"pandas",
"python"
] | stackoverflow_0074569616_numpy_pandas_python.txt |
Q:
Problem with input shape of Conv1d in tfagents sequential network
I have created a trading environment using tfagent
env = TradingEnv(df=df.head(100000), lkb=1000)
tf_env = tf_py_environment.TFPyEnvironment(env)
and passed a df of 100000 rows from which only closing prices are used which a numpy array of 100000 s... | Problem with input shape of Conv1d in tfagents sequential network | I have created a trading environment using tfagent
env = TradingEnv(df=df.head(100000), lkb=1000)
tf_env = tf_py_environment.TFPyEnvironment(env)
and passed a df of 100000 rows from which only closing prices are used which a numpy array of 100000 stock price time series data
df: Date Open High Low Close volume
0 2015-... | [
"Unfortunately, TF-Agents doesn't support Conv1D layers. Almost all network classes use the EncodingNetwork class to build their networks. If You check out their github code or documentation, they do provide the Conv1D layer in the EncodingNetwork, however, it is set to Conv2D by default and no network class has a ... | [
0
] | [] | [] | [
"conv_neural_network",
"machine_learning",
"python",
"tensorflow",
"tf_agent"
] | stackoverflow_0072679241_conv_neural_network_machine_learning_python_tensorflow_tf_agent.txt |
Q:
How to convert cftime.Datetime360Day to normal datetime
I have an exported csv file that contains extracted climate data from netCDF file, however the Date column has exported as below list, I would like to change this column to normal datetime.
Is there any solution please!
Thanks!
(cftime.Datetime360Day(2006, 1,... | How to convert cftime.Datetime360Day to normal datetime | I have an exported csv file that contains extracted climate data from netCDF file, however the Date column has exported as below list, I would like to change this column to normal datetime.
Is there any solution please!
Thanks!
(cftime.Datetime360Day(2006, 1, 1, 12, 0, 0, 0, has_year_zero=True),)
(cftime.Datetime360Da... | [
"I assume you've tried pandas pd.to_datetime() already, right?\nIf not, give that a shot. It generally works really well.\n",
"Datetime360Day is a calendar with every year being 360 days long (divided into 30 day months)\nGenerally (in around all languages) if there is no means that can help you to do the convers... | [
0,
0
] | [] | [] | [
"datetime",
"netcdf",
"pandas",
"python"
] | stackoverflow_0074565303_datetime_netcdf_pandas_python.txt |
Q:
Adding values for missing data combinations in Pandas
I've got a pandas data frame containing something like the following:
person_id status year count
0 'pass' 1980 4
0 'fail' 1982 1
1 'pass' 1981 2
If I know that all possible values for each field are:
all... | Adding values for missing data combinations in Pandas | I've got a pandas data frame containing something like the following:
person_id status year count
0 'pass' 1980 4
0 'fail' 1982 1
1 'pass' 1981 2
If I know that all possible values for each field are:
all_person_ids = [0, 1, 2]
all_statuses = ['pass', 'fail']
all... | [
"You can use itertools.product to generate all combinations, then construct a df from this, merge it with your original df along with fillna to fill missing count values with 0:\nIn [77]:\nimport itertools\nall_person_ids = [0, 1, 2]\nall_statuses = ['pass', 'fail']\nall_years = [1980, 1981, 1982]\ncombined = [all_... | [
12,
10,
2,
1
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0031786881_pandas_python.txt |
Q:
Can code ignore one iteration in webscrapping? IndexError: pop index out of range
So I have a code, which scraps names+prices of minerals from 14 pages (so far) and saves it to .txt file. I tried with Page1 first only, then I wanted to add more pages for more data. But then code was grabbing something it should no... | Can code ignore one iteration in webscrapping? IndexError: pop index out of range | So I have a code, which scraps names+prices of minerals from 14 pages (so far) and saves it to .txt file. I tried with Page1 first only, then I wanted to add more pages for more data. But then code was grabbing something it should not grab - a random name/string. I didn't expect it to grab that one, but it did, and ass... | [
"You simply need to make the CSS selector more specific, so that only links directly inside the font element (not several levels down) are identified:\nsoup.select(\"table tr td font>a\")\n\nAdding a further criteria that the link is to an individual item rather than the next/prev page links at the bottom of the pa... | [
1,
1
] | [] | [] | [
"beautifulsoup",
"html",
"python",
"selenium",
"web_scraping"
] | stackoverflow_0074569378_beautifulsoup_html_python_selenium_web_scraping.txt |
Q:
How to make a 3x3 matrix that represents weather or not a box on a sudoku board (9x9 matrix) contains x
I am creating a Sudoku bot in python and I need to create a 3x3 matrix where each value represents a box on the board. The value will be False if there is an instance of value in the box and True if not.
Current... | How to make a 3x3 matrix that represents weather or not a box on a sudoku board (9x9 matrix) contains x | I am creating a Sudoku bot in python and I need to create a 3x3 matrix where each value represents a box on the board. The value will be False if there is an instance of value in the box and True if not.
Currently I have
temp_board = ma.masked_where(board == value, board, True)
boxes = np.full((3, 3), False)
for x in r... | [
"One way, not very subtle, but fast, would be to have a lookup index table\nlook=np.zeros((9,9,9), dtype=bool)\nlook[0,:3,:3]=True\nlook[1,:3,3:6]=True\nlook[2,:3,6:]=True\nlook[3,3:6,:3]=True\nlook[4,3:6,3:6]=True\nlook[5,3:6,6:]=True\nlook[6,6:,:3]=True\nlook[7,6:,3:6]=True\nlook[8,6:,6:]=True\n\ndef inblock(boar... | [
1
] | [] | [] | [
"numpy",
"numpy_ndarray",
"python"
] | stackoverflow_0074569356_numpy_numpy_ndarray_python.txt |
Q:
split string index row in dataframe
I would like to split INDEX in df by "_"
dataframe is as below:
column1
column2
catA_gas
abc
abc
catB_green
abc
abc
catA_apple
abc
abc
I would like to make extra column where catA/catB will be separated from the rest of text.
A:
IIUC use Index.str.extract for values befor... | split string index row in dataframe | I would like to split INDEX in df by "_"
dataframe is as below:
column1
column2
catA_gas
abc
abc
catB_green
abc
abc
catA_apple
abc
abc
I would like to make extra column where catA/catB will be separated from the rest of text.
| [
"IIUC use Index.str.extract for values before first _:\ndf['Column3'] = df.index.str.extract(r'([^_]+)', expand=False)\nprint (df)\n column1 column2 Column3\ncatA_gas abc abc catA\ncatB_green abc abc catB\ncatA_apple abc abc catA\n\nOr if need 2 new columns use Index.to_... | [
1
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074570033_dataframe_pandas_python.txt |
Q:
Calculate %-deviation with values from a pandas Dataframe
I am fairly new to python and I have the following dataframe
setting_id subject_id seconds result_id owner_id average duration_id
0 7 1 0 1680.5 2.0 24.000 1.0
1 7 1 3600 ... | Calculate %-deviation with values from a pandas Dataframe | I am fairly new to python and I have the following dataframe
setting_id subject_id seconds result_id owner_id average duration_id
0 7 1 0 1680.5 2.0 24.000 1.0
1 7 1 3600 1690.5 2.0 46.000 2.0
2 7 ... | [
"You can use:\n# identify rows with 0\nm = df['seconds'].eq(0)\n# compute the sum of rows with 0\ns = (df['average'].where(m)\n .groupby([df['setting_id'], df['subject_id']])\n .sum()\n )\n\n# compute the deviation per group\ndeviation = (\n df[['setting_id', 'subject_id']]\n .merge(s, left_on=['setting_... | [
2
] | [] | [] | [
"django",
"pandas",
"python"
] | stackoverflow_0074570007_django_pandas_python.txt |
Q:
split a pdf based on outline
i would like to use pyPdf to split a pdf file based on the outline where each destination in the outline refers to a different page within the pdf.
example outline:
main --> points to page 1
sect1 --> points to page 1
sect2 --> points to page 15
sect3 --> points ... | split a pdf based on outline | i would like to use pyPdf to split a pdf file based on the outline where each destination in the outline refers to a different page within the pdf.
example outline:
main --> points to page 1
sect1 --> points to page 1
sect2 --> points to page 15
sect3 --> points to page 22
it is easy within pyPd... | [
"I figured it out:\nclass Darrell(pyPdf.PdfFileReader):\n\n def getDestinationPageNumbers(self):\n def _setup_outline_page_ids(outline, _result=None):\n if _result is None:\n _result = {}\n for obj in outline:\n if isinstance(obj, pyPdf.pdf.Destination):... | [
9,
1,
0,
0,
0
] | [] | [] | [
"pdf",
"pypdf",
"python"
] | stackoverflow_0001918420_pdf_pypdf_python.txt |
Q:
How to handle with large dataset in spacy
I use the following code to clean my dataset and print all tokens (words).
with open(".data.csv", "r", encoding="utf-8") as file:
text = file.read()
text = re.sub(r"[^a-zA-Z0-9ß\.,!\?-]", " ", text)
text = text.lower()
nlp = spacy.load("de_core_news_sm")
doc = nlp(text... | How to handle with large dataset in spacy | I use the following code to clean my dataset and print all tokens (words).
with open(".data.csv", "r", encoding="utf-8") as file:
text = file.read()
text = re.sub(r"[^a-zA-Z0-9ß\.,!\?-]", " ", text)
text = text.lower()
nlp = spacy.load("de_core_news_sm")
doc = nlp(text)
for token in doc:
print(token.text)
Whe... | [
"de_core_web_sm isn't just tokenizing. It is running a number of pipeline components including a parser and NER, where you are more likely to run out of RAM on long texts. This is why spacy includes this default limit.\nIf you only want to tokenize, use spacy.blank(\"de\") and then you can probably increase nlp.max... | [
1
] | [] | [] | [
"nlp",
"python",
"spacy",
"stringtokenizer",
"tokenize"
] | stackoverflow_0074566601_nlp_python_spacy_stringtokenizer_tokenize.txt |
Q:
Python reading and writing to tty
BACKGROUND: If you want, skip to the problem section
I am working on a front end for test equipment. The purpose of the front end is to make it easier to write long test scripts. Pretty much just make them more human readable and writable.
The equipment will be tested using a Prol... | Python reading and writing to tty | BACKGROUND: If you want, skip to the problem section
I am working on a front end for test equipment. The purpose of the front end is to make it easier to write long test scripts. Pretty much just make them more human readable and writable.
The equipment will be tested using a Prologix GPIB-USB Controller (see prologix.... | [
"Well, I asked too soon. I hope someone benefits from this self answer.\nSo this works to read and write from both the emulator and the actual device. I am not exactly sure why, and would appreciate an explanation, but this does work in all of my tests\nimport serial\n\nclass VISA:\n def __init__(self, tty_name)... | [
7,
3,
0
] | [] | [] | [
"bash",
"linux",
"pty",
"python",
"tty"
] | stackoverflow_0020894969_bash_linux_pty_python_tty.txt |
Q:
SQLMODEL background error with date object
I'm trying to compare date objects using sqlmodel,fastapi,sqlalchemy. My ORM class looks like that:
class Evergreen(SQLModel,table=True):
id_seq: Optional[int] = Field(default=None,primary_key=True)
phase_end: Optional[date] = None
phase_start: Optional[date] ... | SQLMODEL background error with date object | I'm trying to compare date objects using sqlmodel,fastapi,sqlalchemy. My ORM class looks like that:
class Evergreen(SQLModel,table=True):
id_seq: Optional[int] = Field(default=None,primary_key=True)
phase_end: Optional[date] = None
phase_start: Optional[date] = None
phase_type: Optional[str] = None
... | [
"It seems like your query typing is wrong.\nTry this,\n if days_ago:\n margin = date.today() - timedelta(days_ago)\n query = query.where(Evergreen.phase_end =< date.today() + margin)\n\n"
] | [
2
] | [] | [] | [
"fastapi",
"python",
"sqlmodel"
] | stackoverflow_0074569607_fastapi_python_sqlmodel.txt |
Q:
Combining corresponding elements from n different lists in Python
I have three lists with the same number of elements of string type. And all I want to do is to join them together in one list.
list_1 = ['inline', '', '', '', '', '', '']
list_2 = ['static', 'static', 'static', '', 'static', 'static', 'static']
list... | Combining corresponding elements from n different lists in Python | I have three lists with the same number of elements of string type. And all I want to do is to join them together in one list.
list_1 = ['inline', '', '', '', '', '', '']
list_2 = ['static', 'static', 'static', '', 'static', 'static', 'static']
list_3 = ['boolean', 'uint8', 'uint8', 'void', 'boolean', 'void', 'void']
... | [
"If you are sure that all lists have the same number of elements, something simple as this will work :\noutput = []\nfor i in range(len(list_1)):\n output.append(f'{list_1[index]} {list_2[index]} {list_3[index]}')\n\nIf you do not know what the f before the string means, it will replace everything in curly brack... | [
3
] | [] | [] | [
"list",
"python",
"string"
] | stackoverflow_0074570092_list_python_string.txt |
Q:
Is there a way to loop through an xml file and change specific tags according to how many times that tag comes up?
In my XML file [studentinfo.xml] is there a way to loop through the xml file and change specific tags (and specific child tags) [there will be multiple ones that need to change] and add a number on th... | Is there a way to loop through an xml file and change specific tags according to how many times that tag comes up? | In my XML file [studentinfo.xml] is there a way to loop through the xml file and change specific tags (and specific child tags) [there will be multiple ones that need to change] and add a number on the end?
**The file is significantly larger
<?xml version="1.0" encoding="UTF-8"?>
<stu:StudentBreakdown>
<stu:Studentdata... | [
"In bs4, you can assign a new name to Tag simply with Tag.name = 'NEW_NAME', so you just have to enumerate and loop through.\n(I pasted your first xml snippet to xmlStr.)\nxSoup = BeautifulSoup(xmlStr, 'lxml') ## do NOT use 'xml' parser here unless you want to lose namespaces\n\nenumTags = ['st:name', 'stu:students... | [
1,
0
] | [] | [] | [
"beautifulsoup",
"dataframe",
"python",
"xml"
] | stackoverflow_0074567311_beautifulsoup_dataframe_python_xml.txt |
Q:
Python "ValueError: I/O operation on closed file" for a text file. But opened
I needed to a library specific output and, so I tired it like this way. But I got "ValueError: I/O operation on closed file." Error.
Here the code example that I tried...
import sys
def print_test():
print("Printing testing print...... | Python "ValueError: I/O operation on closed file" for a text file. But opened | I needed to a library specific output and, so I tired it like this way. But I got "ValueError: I/O operation on closed file." Error.
Here the code example that I tried...
import sys
def print_test():
print("Printing testing print...!")
print("line 01")
print("line 02")
print("line 03")
print("Before ... | [
"I did not know this, but after doing sys.stdout.close() it seems you cannot open other files.\nHowever there is a better way to print in a file using print anyway, as the print function accept a file parameter. You can then do something like :\ndef print_test(f):\n print(\"Printing testing print...!\", file=f)\... | [
1,
0
] | [] | [] | [
"capture",
"command_line_interface",
"python",
"python_3.x",
"sys"
] | stackoverflow_0074569990_capture_command_line_interface_python_python_3.x_sys.txt |
Q:
How to combine two dataframes into one pivot table?
I'm trying to create a combination of concentrations of two chemicals for an experiment. Since I want to see which combination of both is the best I want to create an overview how much I need to add of each at a given concentration. So far I managed to create two... | How to combine two dataframes into one pivot table? | I'm trying to create a combination of concentrations of two chemicals for an experiment. Since I want to see which combination of both is the best I want to create an overview how much I need to add of each at a given concentration. So far I managed to create two pivot_tables/dataframes of each but Im somehow don't get... | [
"Use numpy.broadcast_to for new 2d arrays and divide them, then pass to DataFrame constructor:\narray_CinA = np.array([0,125,250,500,1000])\narray_Aceto = np.array([0,100,200,400,800])\nvol_cina = [0, 5, 10, 20, 40]\nvol_as = [0, 2, 4,8,16]\n\nshape = (len(array_Aceto), len(array_CinA))\n\narr = np.core.defchararra... | [
0,
0
] | [] | [] | [
"dataframe",
"numpy",
"pandas",
"python"
] | stackoverflow_0074569229_dataframe_numpy_pandas_python.txt |
Q:
How to extract the top N rows from a dataframe with most frequent occurences of a word in a list?
I have a Python dataframe with multiple rows and columns, a sample of which I have shared below -
DocName
Content
Doc1
Hi how you are doing ? Hope you are well. I hear the food is great!
Doc2
The food is great. Jam... | How to extract the top N rows from a dataframe with most frequent occurences of a word in a list? | I have a Python dataframe with multiple rows and columns, a sample of which I have shared below -
DocName
Content
Doc1
Hi how you are doing ? Hope you are well. I hear the food is great!
Doc2
The food is great. James loves his food. You not so much right ?
Doc3.
Yeah he is alright.
I also have a list of... | [
"Second attempt (initially I misunderstood your requirements): With df your dataframe you could try something like:\nwords = [\"food\", \"you\"]\nn = 2 # Number of top docs\nres = (\n df\n .assign(Content=df[\"Content\"].str.casefold().str.findall(r\"\\w+\"))\n .explode(\"Content\")\n .loc[lambda df: d... | [
1,
0
] | [] | [] | [
"count",
"dataframe",
"pandas",
"python",
"text"
] | stackoverflow_0074567833_count_dataframe_pandas_python_text.txt |
Q:
Why does my code not give the same result as other users?
I was trying to solve a tiny challenge to write code that would print all numbers until 100 that are divisible by 7, so I ended with this code:
print("Numbers until 100 that can be divided by 7 are: ")
print("-" * 100)
for i in range(101):
if i % 7 == ... | Why does my code not give the same result as other users? | I was trying to solve a tiny challenge to write code that would print all numbers until 100 that are divisible by 7, so I ended with this code:
print("Numbers until 100 that can be divided by 7 are: ")
print("-" * 100)
for i in range(101):
if i % 7 == 0:
print(i)
Numbers until 100 that can be divided by 7... | [
"i // 10 == 7 is the first mistake.\n// gives you the quotient but there may be a remainder\n71 // 10 gives you 7 but it remains 1 !!! (so it's not divisible by 7)\nAnd i % 10 == 7 is the second mistake :\nBecause % gives you the remainder.\nSo 37 % 10 gives you 7 (because 37/10 = 3.7).. So it's not divisible by 7... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074570151_python.txt |
Q:
Regular Expression to split text based on different patterns (within a single expression)
I have some patterns which detect questions and splits on top of that. there are some assumptions which I'm using like:
Every pattern starts with a \n
Every pattern ends with \s+
And how I define a pattern is like:
<NUM>.
Q... | Regular Expression to split text based on different patterns (within a single expression) | I have some patterns which detect questions and splits on top of that. there are some assumptions which I'm using like:
Every pattern starts with a \n
Every pattern ends with \s+
And how I define a pattern is like:
<NUM>.
Q <NUM>.
Q <NUM>
<Q.NUM.>
<NUM>
Question <NUM>
<Example>
Problem <NUM>
Problem:
<Alphabet><Numbe... | [
"You can use\n(?m)^(?!$)(?:((?i:Question|Problem:?|Example)|[A-Z])[. ]?)?(\\d+[. ]?)?(?=\\s)\n\nSee the regex demo.\nDetails:\n\n(?m)^ - start of a line (m allows ^ to match any line start position)\n(?!$) - no end of line allowed at the same location (i.e. no empty line match allowed)\n(?:((?i:Question|Problem:?|E... | [
1,
0
] | [] | [] | [
"python",
"python_re",
"regex",
"regex_group"
] | stackoverflow_0074541585_python_python_re_regex_regex_group.txt |
Q:
How to wait for the worker processes in Python multiprocessing.pool.Pool without closing it?
I'm benchmarking this script on a 6-core CPU with Ubuntu 22.04.1 and Python 3.10.6. It is supposed to show usage of all available CPU cores with par function vs. a single core with ser function.
import numpy as np
from mul... | How to wait for the worker processes in Python multiprocessing.pool.Pool without closing it? | I'm benchmarking this script on a 6-core CPU with Ubuntu 22.04.1 and Python 3.10.6. It is supposed to show usage of all available CPU cores with par function vs. a single core with ser function.
import numpy as np
from multiprocessing import Pool
import timeit as ti
def foo(n):
return -np.sort(-np.arange(n))[-1]
... | [
"you need to get the result from apply_async to wait for it.\ndef par(reps, bigNum, pool):\n jobs = []\n for i in range(bigNum, bigNum+reps):\n jobs.append(pool.apply_async(foo, args=(i,)))\n for job in jobs:\n job.get()\n\nfor long loops you should be using map or imap or imap_unordered instead of apply_a... | [
1
] | [] | [] | [
"multiprocessing",
"python"
] | stackoverflow_0074570165_multiprocessing_python.txt |
Q:
Why does `np.sum([-np.Inf, +np.Inf])` warn about "invalid value encountered in reduce"
python -c "import numpy as np; print(np.sum([-np.Inf, +np.Inf]))"
gives
numpy\core\fromnumeric.py:86: RuntimeWarning: invalid value encountered in reduce
return ufunc.reduce(obj, axis, dtype, out, **passkwargs)
nan
I wonder... | Why does `np.sum([-np.Inf, +np.Inf])` warn about "invalid value encountered in reduce" | python -c "import numpy as np; print(np.sum([-np.Inf, +np.Inf]))"
gives
numpy\core\fromnumeric.py:86: RuntimeWarning: invalid value encountered in reduce
return ufunc.reduce(obj, axis, dtype, out, **passkwargs)
nan
I wonder why that is:
There is no warning in
python -c "import numpy as np; print(np.sum([-np.Inf, ... | [
"The warning is fine, because Inf - Inf is mathematically undefined. What result would you expect?\nIf you want to avoid the warning, use a filter as follows:\nimport warnings\n\nwith warnings.catch_warnings():\n warnings.simplefilter(\"ignore\", category=RuntimeWarning)\n res = np.sum([-np.Inf, np.Inf])\n\n"... | [
2,
1
] | [] | [] | [
"infinity",
"nan",
"numpy",
"python"
] | stackoverflow_0074552683_infinity_nan_numpy_python.txt |
Q:
How to display values on TKINTER GUI after receiving a message from a client(using sockets) (Python)
I am working with sockets and Tkinter in python, the idea is simple, I have a client and I am sending a message, and that message has to be displayed on the server's side GUI(without pulsing any button), I coded bo... | How to display values on TKINTER GUI after receiving a message from a client(using sockets) (Python) | I am working with sockets and Tkinter in python, the idea is simple, I have a client and I am sending a message, and that message has to be displayed on the server's side GUI(without pulsing any button), I coded both sides, but on the server when I am trying to display the message I am having some problems, until now I... | [
"You should create the server GUI only once in main thread (not in child thread) and run the socket server in child thread instead.\nBelow is the modified code on server side:\nimport socket\nimport threading\nimport tkinter\nfrom tkinter.scrolledtext import ScrolledText\n\n# client handler\ndef handler(client):\n ... | [
0
] | [] | [] | [
"multiprocessing",
"multithreading",
"python",
"sockets",
"tkinter"
] | stackoverflow_0074568341_multiprocessing_multithreading_python_sockets_tkinter.txt |
Q:
Can't supply list of links to "concurrent.futures" instead of one link at a time
I've created a script using "concurrent.futures" to scrape some datapoints from a website. The script is working flawlessly in the way I'm currently using it. However, I wish to supply the links as a list to the "future_to_url" block ... | Can't supply list of links to "concurrent.futures" instead of one link at a time | I've created a script using "concurrent.futures" to scrape some datapoints from a website. The script is working flawlessly in the way I'm currently using it. However, I wish to supply the links as a list to the "future_to_url" block instead of one link at a time.
This is currently how I'm trying.
links = [
'first ... | [
"I think what you need is executor.map where you can pass an iterable.\nI've simplified your code since you're not providing the links, but that should give you the general idea.\nHere's how:\nimport concurrent.futures\nfrom itertools import chain\n\nimport requests\nfrom bs4 import BeautifulSoup\n\nlinks = [\n ... | [
1
] | [] | [] | [
"concurrent.futures",
"python",
"python_3.x",
"web_scraping"
] | stackoverflow_0074569080_concurrent.futures_python_python_3.x_web_scraping.txt |
Q:
How to configure celery schedule crontab in python to execute the task from 2pm to 9am, every hour?
I tried it like this:
crontab(hour="14-9")
but it doesn't work. It executes it continuously; as soon as the task ends, it repeats immediately.
A:
According to official celery docs you have to add minute=0 attribu... | How to configure celery schedule crontab in python to execute the task from 2pm to 9am, every hour? | I tried it like this:
crontab(hour="14-9")
but it doesn't work. It executes it continuously; as soon as the task ends, it repeats immediately.
| [
"According to official celery docs you have to add minute=0 attribute to your crontab call.\nYour code has to be like:\ncrontab(hour=\"14-9\", minute=0)\n\n"
] | [
1
] | [] | [] | [
"celery",
"cron",
"python"
] | stackoverflow_0074570259_celery_cron_python.txt |
Q:
Allow positional arguments for BaseModel pydantic
I have a class with all the necessary parameters. But, for init function, it asks for keyword arguments, and does not accept positional arguments. So, my question is: is there something I can change in config of pydantic.BaseModel to allow positional arguments?
Her... | Allow positional arguments for BaseModel pydantic | I have a class with all the necessary parameters. But, for init function, it asks for keyword arguments, and does not accept positional arguments. So, my question is: is there something I can change in config of pydantic.BaseModel to allow positional arguments?
Here is an example of my class:
class Foo(BaseModel):
... | [
"Pydantic objects can't be init with positional arguments.\nimport json\nfrom pydantic import BaseModel\nfrom typing import Optional\n\nclass Foo(BaseModel):\n a: int\n b: Optional[str]\n c: Optional[float]\n\nYou have to give Pydantic every key you want to init your model with (what you did):\nFoo(a=1,b=\... | [
2,
1
] | [] | [] | [
"pydantic",
"python"
] | stackoverflow_0073156982_pydantic_python.txt |
Q:
Find a Collection of Indexes Provided that the Value
So, I have data like this
Index c1
sls1 6
sls2 4
sls3 7
sls4 5
sls5 5
I want to find a collection of indexes provided that the value of column c2 on some indexes amounts to less than equal to 10 with looping. Then I save the ind... | Find a Collection of Indexes Provided that the Value | So, I have data like this
Index c1
sls1 6
sls2 4
sls3 7
sls4 5
sls5 5
I want to find a collection of indexes provided that the value of column c2 on some indexes amounts to less than equal to 10 with looping. Then I save the index set as a list on a new data frame, which is output.
out... | [
"There is no vectorized way to compute a cumulated sum with restart on a threshold, you'll have to use a loop.\nThen combine this with groupby.agg:\ndef group(s, thresh=10):\n out = []\n g = 0\n curr_sum = 0\n for v in s:\n curr_sum += v\n if curr_sum > thresh:\n g += 1\n ... | [
0
] | [] | [] | [
"dataframe",
"python"
] | stackoverflow_0074570384_dataframe_python.txt |
Q:
VS Code - broken auto check of links for Django/Python
This is not a good question, but I used to have in Django/Python files in VS Code automatic check by yellow colour, that model, variable, view, function etc. are correctly somewhere defined and I can use them. But something broke and everything is now white.
D... | VS Code - broken auto check of links for Django/Python | This is not a good question, but I used to have in Django/Python files in VS Code automatic check by yellow colour, that model, variable, view, function etc. are correctly somewhere defined and I can use them. But something broke and everything is now white.
Does anybody know, where to switch on again this check for Py... | [
"This was related to some extensions you installed which were conflict with each other.\nI think the easiest way is to reinstall vscode.\n"
] | [
1
] | [] | [] | [
"django",
"python",
"visual_studio_code"
] | stackoverflow_0074561221_django_python_visual_studio_code.txt |
Q:
How to count and get same items from list of tuples
I'm writing a program that reads an excel file and creates a new one putting all the values in the right order and format, using openpyxl library.
I need to get some dates from the original file, where they are written in the same line, and create a new line for ... | How to count and get same items from list of tuples | I'm writing a program that reads an excel file and creates a new one putting all the values in the right order and format, using openpyxl library.
I need to get some dates from the original file, where they are written in the same line, and create a new line for each one in the new file.
I already have a function to do... | [
"One way to aggregate is using collections.defaultdict(list) and then print out the values from the defaultdict -\nfrom collections import defaultdict\nd = defaultdict(list)\nl = [(\"ID1\", 20160101), (\"ID2\", 20180101), (\"ID3\", 20160101)]\n\nfor idx, dt in l:\n d[dt].append(idx)\n\nfor key, val in d.items():... | [
0
] | [] | [] | [
"list",
"python",
"tuples"
] | stackoverflow_0074569680_list_python_tuples.txt |
Q:
Snowflake connector to python
I have python 3.11.0 version and I want to connect to snowflake as well.
I have installed the package, but my VS Code doesn't recognize it.
I saw in Snowflake Documentation that Snowflake Connector works with Python versions up to 3.9
https://docs.snowflake.com/en/user-guide/python-in... | Snowflake connector to python | I have python 3.11.0 version and I want to connect to snowflake as well.
I have installed the package, but my VS Code doesn't recognize it.
I saw in Snowflake Documentation that Snowflake Connector works with Python versions up to 3.9
https://docs.snowflake.com/en/user-guide/python-install.html
Not sure if I can make i... | [
"As mentioned in the documentation, the Snowflake Python connector requires a Python version up to 3.9 - therefore yes, you would have to have installed one of the supported versions.\nThis ensures that the connector was tested and works with these versions of Python as well as ensures that your Python installation... | [
0
] | [] | [] | [
"python",
"snowflake_cloud_data_platform"
] | stackoverflow_0074564091_python_snowflake_cloud_data_platform.txt |
Q:
How to iterate through two nested lists (28 and 3 elements) and check if subset based on the length of 28, not 28*3?
I would like to check if values from the list1 are part of a subset of list2 ([cor[1] for cor in list2]) based on the length of list1.
The result should be a list of 28 elements len(list1) and look ... | How to iterate through two nested lists (28 and 3 elements) and check if subset based on the length of 28, not 28*3? | I would like to check if values from the list1 are part of a subset of list2 ([cor[1] for cor in list2]) based on the length of list1.
The result should be a list of 28 elements len(list1) and look like this:
[['1'], [43, 44, 45, 46, 47, 48], [43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, ... | [
"If this is a small example it is fine to write with two nested loop, however for correct complexity you could put your list2 in a dictionary (since all integers are sequential pretty easily to hash them as a range) and only do with one loop.\nBut back to your implementation:\nyou do two time loop and in each scena... | [
0
] | [] | [] | [
"iteration",
"loops",
"nested_lists",
"python"
] | stackoverflow_0074569659_iteration_loops_nested_lists_python.txt |
Q:
Wagtail Convert StreamField to Dict
I'm trying to convert a streamfield in models.py to a dict on save so then I can get the data and do something with it.
from django.http import JsonResponse
import json
class ProductBlogPage(BlogDetailPage):
product_details = StreamField([
('product_name_and_url', b... | Wagtail Convert StreamField to Dict | I'm trying to convert a streamfield in models.py to a dict on save so then I can get the data and do something with it.
from django.http import JsonResponse
import json
class ProductBlogPage(BlogDetailPage):
product_details = StreamField([
('product_name_and_url', blocks.ProductNameAndUrlBlock()),
],
... | [
"product_details.raw_data is an array of dictionaries (one element per block), the only HTML should be for formatted rich text. This is the value stored in the db.\nYou can loop through the array and access all your key/value pairs from there. e.g.\n<ul> \n {% for product in self.product_details.raw_data %}\n... | [
1
] | [] | [] | [
"python",
"wagtail",
"wagtail_streamfield"
] | stackoverflow_0074570071_python_wagtail_wagtail_streamfield.txt |
Q:
how to programmatically determine available GPU memory with tensorflow?
For a vector quantization (k-means) program I like to know the amount of available memory on the present GPU (if there is one). This is needed to choose an optimal batch size in order to have as few batches as possible to run over the complete... | how to programmatically determine available GPU memory with tensorflow? | For a vector quantization (k-means) program I like to know the amount of available memory on the present GPU (if there is one). This is needed to choose an optimal batch size in order to have as few batches as possible to run over the complete data set.
I have written the following test program:
import tensorflow as tf... | [
"I actually found an answer in this old question of mine\n. To bring some additional benefit to readers I tested the mentioned program\nimport nvidia_smi\n\nnvidia_smi.nvmlInit()\n\nhandle = nvidia_smi.nvmlDeviceGetHandleByIndex(0)\n# card id 0 hardcoded here, there is also a call to get all available card ids, so ... | [
28,
25,
4,
0
] | [] | [] | [
"gpu",
"python",
"tensorflow"
] | stackoverflow_0059567226_gpu_python_tensorflow.txt |
Q:
scramble (random permutation) of image pixels within a boolean mask in Python (PIL)
I want to scramble, i.e., randomly permute the pixels of an area delimited by a boolean mask, in this case only the area of the face (omitting the background).
The code to do random permutation on the whole image works, but when I ... | scramble (random permutation) of image pixels within a boolean mask in Python (PIL) | I want to scramble, i.e., randomly permute the pixels of an area delimited by a boolean mask, in this case only the area of the face (omitting the background).
The code to do random permutation on the whole image works, but when I apply it to the masked array, it also changes the color... How to perform the shuffling a... | [
"I haven't researched if there are any shuffle methods that allow axes to be set or excluded from shuffling, but one fast way might be to convert each RGB888 pixel into a single uint32 prior to shuffling, then split back into RGB888 afterwards. As the 3 bytes will then be packed together into a single entity they w... | [
0
] | [] | [] | [
"numpy",
"python",
"python_imaging_library",
"shuffle"
] | stackoverflow_0074541109_numpy_python_python_imaging_library_shuffle.txt |
Q:
How to print number is duplicate but not contiguous in array
How to print number is duplicate but not contiguous in array?
example input : [5,2,2,3,3,5]
output : 5
I don't know what to do, I've tried but I can't check the list.
A:
I would use itertools.groupby and a set to keep track of the seen values:
l = [5,2... | How to print number is duplicate but not contiguous in array | How to print number is duplicate but not contiguous in array?
example input : [5,2,2,3,3,5]
output : 5
I don't know what to do, I've tried but I can't check the list.
| [
"I would use itertools.groupby and a set to keep track of the seen values:\nl = [5,2,2,3,3,5]\n\nfrom itertools import groupby\n\nseen = set()\nduplicates = set()\nfor k, _ in groupby(l):\n if k in seen:\n print(f'{k} is duplicated')\n duplicates.add(k)\n seen.add(k)\n\nOutput:\n5 is duplicated\... | [
0
] | [] | [] | [
"arraylist",
"python"
] | stackoverflow_0074570586_arraylist_python.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.