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%, which is correct: I can see the same manually after I join Labels and Predictions; Metrics shows higher, around 86%). What is the matter? Any comment on the code is also appreciated def sensitivity(y_true, y_pred): true_positives = K.sum(K.round(K.clip(y_true, 0, 1)) * K.round(K.clip(y_pred, 0, 1))) possible_positives = K.sum(y_true) return true_positives / (possible_positives + K.epsilon()) .... def calculate_rates(model, data, label): num_positive_prediction = np.sum(label) prediction = np.round(np.clip(model.predict(data, batch_size = 1024)[:,1], 0, 1)) true_positive = np.sum(np.multiply(prediction, label)) / num_positive_prediction return(true_positive) .... class TestCallback(keras.callbacks.Callback): def __init__(self, is_train, data, labels): self.data = data self.labels = labels[:,1] self.is_train = is_train def on_epoch_end(self, epoch, logs={}): true_positive = calculate_rates(model, self.data, self.labels) if (epoch + 1) % 10 == 0 or epoch == 0: if self.is_train: print("Epoch: %d" % epoch + 1) print("Training Set:") else: print("Testing Set:") print("True Positive Rate: %4g" % true_positive) .... model = keras.Sequential() my_init = keras.initializers.RandomNormal(stddev=0.1) model.add(keras.layers.Dense(units=200, activation='relu', input_dim=num_variables)) model.add(keras.layers.Dropout(dropout_rate)) model.add(keras.layers.Dense(units = 200, activation = 'relu', kernel_initializer=my_init, bias_initializer=my_init)) model.add(keras.layers.Dropout(dropout_rate)) model.add(keras.layers.Dense(units=num_outputs, activation='softmax', kernel_initializer=my_init, bias_initializer=my_init)) model.compile(loss='binary_crossentropy', optimizer=keras.optimizers.Adam(lr=0.0001, beta_1=0.9, beta_2=0.999, epsilon=1e-8), metrics=[sensitivity] ) history = model.fit(train_data, train_labels, epochs=num_epochs, batch_size=1024, class_weight={0: 1, 1: weight}, callbacks=[TestCallback(1, train_data, train_labels), TestCallback(0, test_data, test_labels)], verbose=1) A: The simplest way, you can use true positive, true negative, false positive, and false negative as metrics, then calculate True Positive Rate manually. Here modification to your code... model.compile(loss='binary_crossentropy', optimizer=keras.optimizers.Adam(lr=0.0001, beta_1=0.9, beta_2=0.999, epsilon=1e-8), metrics=[tf.keras.metrics.TruePositives(), tf.keras.metrics.TrueNegatives(), tf.keras.metrics.FalsePositives(), tf.keras.metrics.FalseNegatives() ] ) _, tp,tn,fp,fn = model.evaluate(data, target) # calculate True Positive Rate (tpr) tpr = tp/(tp+fn)
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 higher, around 86%). What is the matter? Any comment on the code is also appreciated def sensitivity(y_true, y_pred): true_positives = K.sum(K.round(K.clip(y_true, 0, 1)) * K.round(K.clip(y_pred, 0, 1))) possible_positives = K.sum(y_true) return true_positives / (possible_positives + K.epsilon()) .... def calculate_rates(model, data, label): num_positive_prediction = np.sum(label) prediction = np.round(np.clip(model.predict(data, batch_size = 1024)[:,1], 0, 1)) true_positive = np.sum(np.multiply(prediction, label)) / num_positive_prediction return(true_positive) .... class TestCallback(keras.callbacks.Callback): def __init__(self, is_train, data, labels): self.data = data self.labels = labels[:,1] self.is_train = is_train def on_epoch_end(self, epoch, logs={}): true_positive = calculate_rates(model, self.data, self.labels) if (epoch + 1) % 10 == 0 or epoch == 0: if self.is_train: print("Epoch: %d" % epoch + 1) print("Training Set:") else: print("Testing Set:") print("True Positive Rate: %4g" % true_positive) .... model = keras.Sequential() my_init = keras.initializers.RandomNormal(stddev=0.1) model.add(keras.layers.Dense(units=200, activation='relu', input_dim=num_variables)) model.add(keras.layers.Dropout(dropout_rate)) model.add(keras.layers.Dense(units = 200, activation = 'relu', kernel_initializer=my_init, bias_initializer=my_init)) model.add(keras.layers.Dropout(dropout_rate)) model.add(keras.layers.Dense(units=num_outputs, activation='softmax', kernel_initializer=my_init, bias_initializer=my_init)) model.compile(loss='binary_crossentropy', optimizer=keras.optimizers.Adam(lr=0.0001, beta_1=0.9, beta_2=0.999, epsilon=1e-8), metrics=[sensitivity] ) history = model.fit(train_data, train_labels, epochs=num_epochs, batch_size=1024, class_weight={0: 1, 1: weight}, callbacks=[TestCallback(1, train_data, train_labels), TestCallback(0, test_data, test_labels)], verbose=1)
[ "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, epsilon=1e-8),\n metrics=[tf.keras.metrics.TruePositives(), tf.keras.metrics.TrueNegatives(), \n tf.keras.metrics.FalsePositives(), tf.keras.metrics.FalseNegatives()\n ]\n )\n\n_, tp,tn,fp,fn = model.evaluate(data, target)\n\n# calculate True Positive Rate (tpr)\ntpr = tp/(tp+fn)\n\n" ]
[ 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 100% sure. Any suggestion is appreciated. A: You can also try df["Price"] = '$' + df["Price"].astype(str) A: We could use str.replace here: df["Price"] = df["Price"].astype(str).str.replace(r'^', '$', regex=True)
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 8 expr2 = -4*x + x**2 + a 9 z = solve(expr2) TypeError: unsupported operand type(s) for /: 'list' and 'int' I solved an equation, the answer is an array. I am trying to use the answer for a new equation. I wrote a sample code to explain my problem! A: I see you want to "use the answer for a new equation". The previous equation solution is a, a list with 1 element [1] then you can use a[0] in your next equation expr2 = -4*x + x**2 + a[0] z = solve(expr2) print(z) and p=a/2 is totally useless, you didn't use p after that.
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 type(s) for /: 'list' and 'int' I solved an equation, the answer is an array. I am trying to use the answer for a new equation. I wrote a sample code to explain my problem!
[ "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 issue i met it these days on teaching my students. chromedriver version : 107.0.5304.62 chrome version : 107.0.5304.107 selenium version : 4.6 python version : 3.10 It can work fine on an other PC1. I can't find the difference between them. I try to collect the selenium log . from selenium import webdriver driver = webdriver.Chrome(service_args=['--verbose'],service_log_path='selenium.log') driver.get('https://www.baidu.com') I get the log on PC1 too. I found the difference , but i can't sure it is the source of this issue , also i can't solve it. Here is the doubtful point: [1669339280.964][INFO]: [9a850cc416a680214e963aab4064f86b] COMMAND QuitAll { } [1669339281.111][INFO]: [9a850cc416a680214e963aab4064f86b] RESPONSE QuitAll That's all , please give me some advices. Thank u. A: You have to use Options: from selenium.webdriver.chrome.service import Service from selenium.webdriver.chrome.options import Options options = Options() options.add_experimental_option("detach", True) driver = webdriver.Chrome(service=Service(<chromedriver.exe path>), options=options)
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. chromedriver version : 107.0.5304.62 chrome version : 107.0.5304.107 selenium version : 4.6 python version : 3.10 It can work fine on an other PC1. I can't find the difference between them. I try to collect the selenium log . from selenium import webdriver driver = webdriver.Chrome(service_args=['--verbose'],service_log_path='selenium.log') driver.get('https://www.baidu.com') I get the log on PC1 too. I found the difference , but i can't sure it is the source of this issue , also i can't solve it. Here is the doubtful point: [1669339280.964][INFO]: [9a850cc416a680214e963aab4064f86b] COMMAND QuitAll { } [1669339281.111][INFO]: [9a850cc416a680214e963aab4064f86b] RESPONSE QuitAll That's all , please give me some advices. Thank u.
[ "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 code given to me or with my program itself. heres my code so far A: since you already set comparisons as global variable, you don't need to return comparisons in your function actually. instead, just after your global comparisons, put comparisons += 1 will be enough. and in the end of your program, print(comparisons)
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. heres my code so far
[ "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 I jump back and forth between frames, since the constructor method only runs once when the program begins, and which is where I produce most of the widgets on the screen. Below is an example of what I would like to accomplish: import tkinter as tk class App(tk.Tk): def __init__(self): tk.Tk.__init__(self) container = tk.Frame(self) container.pack(side = "top", fill = "both", expand = True) container.grid_rowconfigure(0, weight = 1) container.grid_columnconfigure(0, weight = 1) self.frames = {} for F in (Homescreen, Menuscreen): frame = F(container, self) self.frames[F] = frame frame.grid(row = 0, column = 0, sticky = "nsew") self.show_frame(Homescreen) def show_frame(self, container): frame = self.frames[container] frame.tkraise() class Homescreen(tk.Frame): def __init__(self, parent, controller): tk.Frame.__init__(self, parent) with open("test.txt", "r") as f: text = f.readline() tk.Label(self, text = text).pack() tk.Button(self, text = "next page", command = lambda: controller.show_frame(Menuscreen)).pack() class Menuscreen(tk.Frame): def __init__(self, parent, controller): tk.Frame.__init__(self, parent) self.controller = controller self.entry = tk.StringVar() tk.Entry(self, textvariable = self.entry).pack() tk.Button(self, text = "back to page", command = self.writeToFile).pack() def writeToFile(self): with open("test.txt", "w") as f: f.writelines(self.entry.get()) self.controller.show_frame(Homescreen) app = App() app.geometry("500x400") app.mainloop() If I have a textfile with just a simple word, in Homescreen i print it out on the screen. Then I move to the second frame, Menuscreen, where I allow the user to enter another word, and then I store the word in the same textfile. Then the program takes us back to the Homescreen, but the problem is that the printed out word, will still be the first word and not the updated word in the textfile. I tried to use the methods .update() and .destroy(), one line before i execute frame.tkraise(), but the .update() method doesn't do anything and when I use the .destroy() method, I get an error saying _tkinter.TclError: bad window path name A: 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. import tkinter as tk class App(tk.Tk): def __init__(self): tk.Tk.__init__(self) container = tk.Frame(self) container.pack(side="top", fill="both", expand=True) container.grid_rowconfigure(0, weight=1) container.grid_columnconfigure(0, weight=1) self.frames = {} for F in (Homescreen, Menuscreen): frame = F(container, self) self.frames[F] = frame frame.grid(row = 0, column = 0, sticky = "nsew") self.show_frame(Homescreen) def show_frame(self, container): frame = self.frames[container] #update the label if container is Homescreen: frame.update_label() frame.tkraise() class Homescreen(tk.Frame): def __init__(self, parent, controller): tk.Frame.__init__(self, parent) #keep a reference to the label so it can be modified self.label = tk.Label(self) self.label.pack() tk.Button(self, text = "next page", command = lambda: controller.show_frame(Menuscreen)).pack() self.update_label() #update the label def update_label(self): with open('test.txt', 'r') as f: self.label['text'] = f.read() class Menuscreen(tk.Frame): def __init__(self, parent, controller): tk.Frame.__init__(self, parent) self.controller = controller self.entry = tk.StringVar() tk.Entry(self, textvariable = self.entry).pack() tk.Button(self, text = "back to page", command = self.writeToFile).pack() def writeToFile(self): with open('test.txt', 'w') as f: f.write(self.entry.get()) #go back to homescreen self.controller.show_frame(Homescreen) app = App() app.geometry("500x400") app.mainloop() If you'd like to make your script a little easier to work with, I refactored it below, and left comments. import tkinter as tk class App(tk.Tk): def __init__(self): tk.Tk.__init__(self) #you do not need `container` #using root as the master makes it a more natural controller #you were using it more like a proxy self.rowconfigure(0, weight=1) self.columnconfigure(0, weight=1) #you created a convention with your class names of using "screen" #use some kind of "screen" for everything that contains or directly relates to them self.screens = {} #don't "juggle" #create a var, and use it for screen in (Menuscreen, Homescreen): self.screens[screen] = screen(self) self.screens[screen].grid(row=0, column=0, sticky="nsew") #renamed to reflect that it relates to your screens def show_screen(self, screen): target = self.screens[screen] if screen is Homescreen: target.update_label() target.tkraise() class Homescreen(tk.Frame): #whatever you put in master becomes the `self.master` of this widget #ie.. we are keeping the names the same def __init__(self, master, **kwargs): tk.Frame.__init__(self, master, **kwargs) self.label = tk.Label(self) self.label.pack() #this line illustrates how the root is the controller tk.Button(self, text="next page", command=lambda: master.show_screen(Menuscreen)).pack() #init the label text self.update_label() def update_label(self): with open('test.txt', 'r') as f: self.label['text'] = f.read() class Menuscreen(tk.Frame): def __init__(self, master, **kwargs): tk.Frame.__init__(self, master, **kwargs) self.entry = tk.StringVar() tk.Entry(self, textvariable=self.entry).pack() tk.Button(self, text="back to page", command=self.writeToFile).pack() def writeToFile(self): with open('test.txt', 'w') as f: f.write(self.entry.get()) #illustrates again how the root is the controller self.master.show_screen(Homescreen) #this is good practice if __name__ == "__main__": app = App() app.geometry("500x400") app.mainloop()
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 the constructor method only runs once when the program begins, and which is where I produce most of the widgets on the screen. Below is an example of what I would like to accomplish: import tkinter as tk class App(tk.Tk): def __init__(self): tk.Tk.__init__(self) container = tk.Frame(self) container.pack(side = "top", fill = "both", expand = True) container.grid_rowconfigure(0, weight = 1) container.grid_columnconfigure(0, weight = 1) self.frames = {} for F in (Homescreen, Menuscreen): frame = F(container, self) self.frames[F] = frame frame.grid(row = 0, column = 0, sticky = "nsew") self.show_frame(Homescreen) def show_frame(self, container): frame = self.frames[container] frame.tkraise() class Homescreen(tk.Frame): def __init__(self, parent, controller): tk.Frame.__init__(self, parent) with open("test.txt", "r") as f: text = f.readline() tk.Label(self, text = text).pack() tk.Button(self, text = "next page", command = lambda: controller.show_frame(Menuscreen)).pack() class Menuscreen(tk.Frame): def __init__(self, parent, controller): tk.Frame.__init__(self, parent) self.controller = controller self.entry = tk.StringVar() tk.Entry(self, textvariable = self.entry).pack() tk.Button(self, text = "back to page", command = self.writeToFile).pack() def writeToFile(self): with open("test.txt", "w") as f: f.writelines(self.entry.get()) self.controller.show_frame(Homescreen) app = App() app.geometry("500x400") app.mainloop() If I have a textfile with just a simple word, in Homescreen i print it out on the screen. Then I move to the second frame, Menuscreen, where I allow the user to enter another word, and then I store the word in the same textfile. Then the program takes us back to the Homescreen, but the problem is that the printed out word, will still be the first word and not the updated word in the textfile. I tried to use the methods .update() and .destroy(), one line before i execute frame.tkraise(), but the .update() method doesn't do anything and when I use the .destroy() method, I get an error saying _tkinter.TclError: bad window path name
[ "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.__init__(self)\n\n container = tk.Frame(self)\n container.pack(side=\"top\", fill=\"both\", expand=True)\n container.grid_rowconfigure(0, weight=1)\n container.grid_columnconfigure(0, weight=1)\n\n self.frames = {}\n\n for F in (Homescreen, Menuscreen):\n\n frame = F(container, self)\n self.frames[F] = frame\n frame.grid(row = 0, column = 0, sticky = \"nsew\")\n\n self.show_frame(Homescreen)\n\n def show_frame(self, container):\n frame = self.frames[container]\n\n #update the label\n if container is Homescreen: frame.update_label()\n\n frame.tkraise()\n\n\nclass Homescreen(tk.Frame):\n def __init__(self, parent, controller):\n tk.Frame.__init__(self, parent)\n \n #keep a reference to the label so it can be modified\n self.label = tk.Label(self)\n self.label.pack()\n \n tk.Button(self, text = \"next page\", command = lambda: controller.show_frame(Menuscreen)).pack()\n \n self.update_label()\n \n #update the label\n def update_label(self):\n with open('test.txt', 'r') as f:\n self.label['text'] = f.read()\n \n \nclass Menuscreen(tk.Frame):\n def __init__(self, parent, controller):\n tk.Frame.__init__(self, parent)\n self.controller = controller\n \n self.entry = tk.StringVar()\n\n tk.Entry(self, textvariable = self.entry).pack()\n tk.Button(self, text = \"back to page\", command = self.writeToFile).pack()\n \n def writeToFile(self):\n with open('test.txt', 'w') as f:\n f.write(self.entry.get())\n \n #go back to homescreen \n self.controller.show_frame(Homescreen)\n\n\napp = App()\napp.geometry(\"500x400\")\napp.mainloop()\n\nIf you'd like to make your script a little easier to work with, I refactored it below, and left comments.\n\nimport tkinter as tk\n\nclass App(tk.Tk):\n def __init__(self):\n tk.Tk.__init__(self)\n \n #you do not need `container`\n #using root as the master makes it a more natural controller\n #you were using it more like a proxy \n\n self.rowconfigure(0, weight=1)\n self.columnconfigure(0, weight=1)\n\n #you created a convention with your class names of using \"screen\"\n #use some kind of \"screen\" for everything that contains or directly relates to them\n self.screens = {}\n\n #don't \"juggle\"\n #create a var, and use it\n for screen in (Menuscreen, Homescreen):\n self.screens[screen] = screen(self)\n self.screens[screen].grid(row=0, column=0, sticky=\"nsew\")\n\n #renamed to reflect that it relates to your screens\n def show_screen(self, screen):\n target = self.screens[screen]\n \n if screen is Homescreen: target.update_label()\n \n target.tkraise()\n\n\nclass Homescreen(tk.Frame):\n #whatever you put in master becomes the `self.master` of this widget\n #ie.. we are keeping the names the same\n def __init__(self, master, **kwargs):\n tk.Frame.__init__(self, master, **kwargs)\n \n self.label = tk.Label(self)\n self.label.pack()\n \n #this line illustrates how the root is the controller\n tk.Button(self, text=\"next page\", command=lambda: master.show_screen(Menuscreen)).pack()\n \n #init the label text\n self.update_label()\n \n def update_label(self):\n with open('test.txt', 'r') as f:\n self.label['text'] = f.read()\n \n \nclass Menuscreen(tk.Frame):\n def __init__(self, master, **kwargs):\n tk.Frame.__init__(self, master, **kwargs)\n \n self.entry = tk.StringVar()\n\n tk.Entry(self, textvariable=self.entry).pack()\n tk.Button(self, text=\"back to page\", command=self.writeToFile).pack()\n \n def writeToFile(self):\n with open('test.txt', 'w') as f:\n f.write(self.entry.get())\n \n #illustrates again how the root is the controller \n self.master.show_screen(Homescreen)\n\n\n#this is good practice\nif __name__ == \"__main__\":\n app = App()\n app.geometry(\"500x400\")\n app.mainloop()\n\n" ]
[ 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 times each. I get the data with pandas and i split the data like this x = dataset_df.drop(columns="target", axis=1) x_train, x_test, y_train, y_test = train_test_split(x,dataset_df.target, test_size=testset_size) and the training part looks like this x_train = StandardScaler().fit(x_train).transform(x_train) dt_cls = DecisionTreeClassifier() dt_cls.fit(x_train.values, y_train) acc = accuracy_score(dt_cls.predict(x_test.values), y_test) prec = precision_score(dt_cls.predict(x_test.values), y_test, pos_label = 1) recall = recall_score(dt_cls.predict(x_test.values), y_test, pos_label = 1, zero_division=1) return acc, prec, recall I tried not to sandarize the data set or putting the dataset into numpy array, also not dropping target columns before splitting the set. obviously none of them work or changed anything. I also tried to print acc right after calculating it, but it didn't print. Also used x_train and x_test without .values but it was the same A: In think, you are loading a model fitted using previous versions of sklearn. With the latest version of sklearn, I don't get any error/warning with the following snippet. X, y = datasets.make_classification(random_state=21) x_df = pd.DataFrame(X) x_train, x_test, y_train, y_test = model_selection.train_test_split(x_df, y) x_train = preprocessing.StandardScaler().fit_transform(x_train) dt_cls = tree.DecisionTreeClassifier() # dt_cls.fit(x_train.values, y_train) dt_cls.fit(x_train, y_train)
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="target", axis=1) x_train, x_test, y_train, y_test = train_test_split(x,dataset_df.target, test_size=testset_size) and the training part looks like this x_train = StandardScaler().fit(x_train).transform(x_train) dt_cls = DecisionTreeClassifier() dt_cls.fit(x_train.values, y_train) acc = accuracy_score(dt_cls.predict(x_test.values), y_test) prec = precision_score(dt_cls.predict(x_test.values), y_test, pos_label = 1) recall = recall_score(dt_cls.predict(x_test.values), y_test, pos_label = 1, zero_division=1) return acc, prec, recall I tried not to sandarize the data set or putting the dataset into numpy array, also not dropping target columns before splitting the set. obviously none of them work or changed anything. I also tried to print acc right after calculating it, but it didn't print. Also used x_train and x_test without .values but it was the same
[ "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_split(x_df, y)\nx_train = preprocessing.StandardScaler().fit_transform(x_train)\ndt_cls = tree.DecisionTreeClassifier()\n# dt_cls.fit(x_train.values, y_train)\ndt_cls.fit(x_train, y_train)\n\n" ]
[ 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 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 module from flask import Flask, render_template, request,url_for app = Flask(__name__) @app.route("/") def home(): return render_template('home.html') @app.route("/teams") def teams(): return render_template('teams.html') @app.route("/form", methods = ['GET','POST']) def form(): #get the method of the post and the method of the get if request.method == "POST" and request.form.get('submit'): string = request.form.get('name') feedback = "Hello" + string + "\n Thank you for submiting!" return render_template('display.html').format(feedback = feedback) else: return render_template('form.html').format(feedback="") #run the program if __name__ == "__main__": app.run() Home html A: In addition to the other comments, you likely wanted this line: if request.method == "POST" and request.form.get('submit'): to be if request.method == "POST" and request.form.get('user'): to check for the user parameter in the form. This would redirect you to display.html, but following this you would likely want to incorporate the changes others suggested as well. A: You're not passing or using the variable correctly. You'll need double braces: {{feedback}}. And while render_template returns a string, you should pass the variable to render_template directly: render_template("form.html", feedback=feedback). Additionally, the input for the second name isn't closed in form.html (should probably be comments as well, and your image path in teams.html should use the full path from server root (and forward slashes, not backslashes).
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 module from flask import Flask, render_template, request,url_for app = Flask(__name__) @app.route("/") def home(): return render_template('home.html') @app.route("/teams") def teams(): return render_template('teams.html') @app.route("/form", methods = ['GET','POST']) def form(): #get the method of the post and the method of the get if request.method == "POST" and request.form.get('submit'): string = request.form.get('name') feedback = "Hello" + string + "\n Thank you for submiting!" return render_template('display.html').format(feedback = feedback) else: return render_template('form.html').format(feedback="") #run the program if __name__ == "__main__": app.run() Home html
[ "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 would likely want to incorporate the changes others suggested as well.\n", "You're not passing or using the variable correctly. You'll need double braces: {{feedback}}. And while render_template returns a string, you should pass the variable to render_template directly: render_template(\"form.html\", feedback=feedback).\nAdditionally, the input for the second name isn't closed in form.html (should probably be comments as well, and your image path in teams.html should use the full path from server root (and forward slashes, not backslashes).\n" ]
[ 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 keep getting error so i go back using manual derivate, Any clue how to derivative the function f with help of other library, Here's the code def Newton(x0): x = x0 f = lambda x : 2 * np.sin (x) - ((x)**2/10) f_x0 = f(x0) #First Derivative f1 = lambda x : 2 * np.cos (x) - ((x)/5) f_x1 = f1(x0) #Second Derivative f2 = lambda x : -2 * np.sin (x) - (1/5) f_x2 = f2(x0) x1 = x0 - (f_x1/f_x2) x0 = x1 return x,f_x0,f_x1,f_x2,x0 finding first and second derivative without the manual way. A: In your case, the derivates can be calculated using the scipy library as follows: from scipy.misc import derivative def f(x): return 2 * sin(x) - ((x)**2/10) print("First derivative:" , derivative(f, 2.5, dx=1e-9)) print("Second derivative", derivative(f, 2.5, n=2, dx=0.02)) Here the first and second derivative is calculated for your function at x=2.5. The same can be done with the sympy library and some may find this easier than the above method. from sympy import * x = Symbol('x') y = 2 * sin(x) - ((x)**2/10) #function yprime = y.diff(x) #first derivative function ydoubleprime = y.diff(x,2) #second derivative function f_first_derivative = lambdify(x, yprime) f_second_derivative = lambdify(x, ydoubleprime) print("First derivative:" , f_first_derivative(2.5)) print("Second derivative",f_second_derivative(2.5))
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 derivative the function f with help of other library, Here's the code def Newton(x0): x = x0 f = lambda x : 2 * np.sin (x) - ((x)**2/10) f_x0 = f(x0) #First Derivative f1 = lambda x : 2 * np.cos (x) - ((x)/5) f_x1 = f1(x0) #Second Derivative f2 = lambda x : -2 * np.sin (x) - (1/5) f_x2 = f2(x0) x1 = x0 - (f_x1/f_x2) x0 = x1 return x,f_x0,f_x1,f_x2,x0 finding first and second derivative without the manual way.
[ "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 second derivative is calculated for your function at x=2.5.\nThe same can be done with the sympy library and some may find this easier than the above method.\nfrom sympy import *\n\nx = Symbol('x')\ny = 2 * sin(x) - ((x)**2/10) #function\nyprime = y.diff(x) #first derivative function\nydoubleprime = y.diff(x,2) #second derivative function\n\nf_first_derivative = lambdify(x, yprime)\nf_second_derivative = lambdify(x, ydoubleprime)\n\nprint(\"First derivative:\" , f_first_derivative(2.5))\nprint(\"Second derivative\",f_second_derivative(2.5))\n\n" ]
[ 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 number in a list in linear time Is it possible to modify this code to find the second smallest number? So for example print second_smallest([1, 2, 3, 4]) 2 A: a = [6,5,4,4,2,1,10,1,2,48] s = set(a) # used to convert any of the list/tuple to the distinct element and sorted sequence of elements # Note: above statement will convert list into sets print sorted(s)[1] A: The function can indeed be modified to find the second smallest: def second_smallest(numbers): m1 = m2 = float('inf') for x in numbers: if x <= m1: m1, m2 = x, m1 elif x < m2: m2 = x return m2 The old version relied on a Python 2 implementation detail that None is always sorted before anything else (so it tests as 'smaller'); I replaced that with using float('inf') as the sentinel, as infinity always tests as larger than any other number. Ideally the original function should have used float('-inf') instead of None there, to not be tied to an implementation detail other Python implementations may not share. Demo: >>> def second_smallest(numbers): ... m1 = m2 = float('inf') ... for x in numbers: ... if x <= m1: ... m1, m2 = x, m1 ... elif x < m2: ... m2 = x ... return m2 ... >>> print(second_smallest([1, 2, 3, 4])) 2 Outside of the function you found, it's almost just as efficient to use the heapq.nsmallest() function to return the two smallest values from an iterable, and from those two pick the second (or last) value. I've included a variant of the unique_everseen() recipe to filter out duplicate numbers: from heapq import nsmallest from itertools import filterfalse def second_smallest(numbers): s = set() sa = s.add un = (sa(n) or n for n in filterfalse(s.__contains__, numbers)) return nsmallest(2, un)[-1] Like the above implementation, this is a O(N) solution; keeping the heap variant each step takes logK time, but K is a constant here (2)! Whatever you do, do not use sorting; that takes O(NlogN) time. A: Or just use heapq: import heapq def second_smallest(numbers): return heapq.nsmallest(2, numbers)[-1] second_smallest([1, 2, 3, 4]) # Output: 2 A: As per the Python in-built function sorted sorted(my_list)[0] gives back the smallest number, and sorted(my_list)[1] does accordingly for the second smallest, and so on and so forth. A: My favourite way of finding the second smallest number is by eliminating the smallest number from the list and then printing the minimum from the list would return me the second smallest element of the list. The code for the task is as below: mylist=[1,2,3,4] mylist=[x for x in mylist if x!=min(mylist)] #deletes the min element from the list print(min(mylist)) A: Yes, except that code relies on a small quirk (that raises an exception in Python 3): the fact that None compares as smaller than a number. Another value that works is float("-inf"), which is a number that is smaller than any other number. If you use that instead of None, and just change -inf to +inf and > to <, there's no reason it wouldn't work. Edit: another possibility would be to simply write -x in all the comparisons on x, e.g. do if -x <= m1: et cetera. A: Solution that returns second unique number in list with no sort: def sec_smallest(numbers): smallest = float('+inf') small = float('+inf') for i in numbers: if i < smallest: small = smallest smallest = i elif i < small and i != smallest: small = i return small print('Sec_smallest:', sec_smallest([1, 2, -8, -8, -2, 0])) A: mi= min(input_list) second_min = float('inf') for i in input_list: if i != mi: if i<second_min: second_min=i if second_min == float('inf'): print('not present') else: print(second_min) ##input_list = [6,6,6,6,6] #input_list = [3, 1, 4, 4, 5, 5, 5, 0, 2, 2] #input_list = [7, 2, 0, 9, -1, 8] # Even if there is same number in the list then Python will not get confused. A: I'd like to add another, more general approach: Here's a recursive way of finding the i-th minimums of a given list of numbers def find_i_minimums(numbers,i): minimum = float('inf') if i==0: return [] less_than_i_minimums = find_i_minimums(numbers,i-1) for element in numbers: if element not in less_than_i_minimums and element < minimum: minimum = element return less_than_i_minimums + [minimum] For example, >>> find_i_minimums([0,7,4,5,21,2,6,1],3) # finding 3 minimial values for the given list [0, 1, 2] ( And if you want only the i-th minimum number you'd extract the final value of the list ) The time-complexity of the above algorithm is bad though, it is O(N*i^2) ( Since the recursion depth is i , and at each recursive call we go over all values in 'numbers' list whose length is N and we check if the minimum element we're searching for isn't in a list of length i-1, thus the total complexity can be described by a geometric sum that will give the above mentioned complexity ). Here's a similar but alternative-implementation whose time-complexity is O(N*i) on average. It uses python's built-in 'set' data-structure: def find_i_minimums(numbers,i): minimum = float('inf') if i==0: return set() less_than_i_minimums = find_i_minimums(numbers,i-1) for element in numbers: if element not in less_than_i_minimums and element < minimum: minimum = element return less_than_i_minimums.union(set({minimum})) If your 'i' is small, you can use the implementations above and then extract how many minimums you want ( or if you want the second minimum, then in your case run the code for i=2 and just extract the last element from the output data-structure ). But if 'i' is for example greater than log(N) , I'd recommend sorting the list of numbers itself ( for example, using mergesort whose complexity is O(N*log(N)) at worst case ) and then taking the i-th element. Why so? because as stated, the run-time of the algorithm above is not great for larger values of 'i'. A: You might find this code easy and understandable def secsmall(numbers): small = max(numbers) for i in range(len(numbers)): if numbers[i]>min(numbers): if numbers[i]<small: small = numbers[i] return small I am assuming "numbers" is a list name.
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 to modify this code to find the second smallest number? So for example print second_smallest([1, 2, 3, 4]) 2
[ "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):\n m1 = m2 = float('inf')\n for x in numbers:\n if x <= m1:\n m1, m2 = x, m1\n elif x < m2:\n m2 = x\n return m2\n\nThe old version relied on a Python 2 implementation detail that None is always sorted before anything else (so it tests as 'smaller'); I replaced that with using float('inf') as the sentinel, as infinity always tests as larger than any other number. Ideally the original function should have used float('-inf') instead of None there, to not be tied to an implementation detail other Python implementations may not share.\nDemo:\n>>> def second_smallest(numbers):\n... m1 = m2 = float('inf')\n... for x in numbers:\n... if x <= m1:\n... m1, m2 = x, m1\n... elif x < m2:\n... m2 = x\n... return m2\n... \n>>> print(second_smallest([1, 2, 3, 4]))\n2\n\nOutside of the function you found, it's almost just as efficient to use the heapq.nsmallest() function to return the two smallest values from an iterable, and from those two pick the second (or last) value. I've included a variant of the unique_everseen() recipe to filter out duplicate numbers:\nfrom heapq import nsmallest\nfrom itertools import filterfalse\n\ndef second_smallest(numbers):\n s = set()\n sa = s.add\n un = (sa(n) or n for n in filterfalse(s.__contains__, numbers))\n return nsmallest(2, un)[-1]\n\nLike the above implementation, this is a O(N) solution; keeping the heap variant each step takes logK time, but K is a constant here (2)!\nWhatever you do, do not use sorting; that takes O(NlogN) time.\n", "Or just use heapq:\nimport heapq\ndef second_smallest(numbers):\n return heapq.nsmallest(2, numbers)[-1]\n\nsecond_smallest([1, 2, 3, 4])\n# Output: 2\n\n", "As per the Python in-built function sorted\nsorted(my_list)[0]\n\ngives back the smallest number, and sorted(my_list)[1] does accordingly for the second smallest, and so on and so forth.\n", "My favourite way of finding the second smallest number is by eliminating the smallest number from the list and then printing the minimum from the list would return me the second smallest element of the list. The code for the task is as below:\nmylist=[1,2,3,4]\nmylist=[x for x in mylist if x!=min(mylist)] #deletes the min element from the list\nprint(min(mylist))\n\n", "Yes, except that code relies on a small quirk (that raises an exception in Python 3): the fact that None compares as smaller than a number.\nAnother value that works is float(\"-inf\"), which is a number that is smaller than any other number.\nIf you use that instead of None, and just change -inf to +inf and > to <, there's no reason it wouldn't work.\nEdit: another possibility would be to simply write -x in all the comparisons on x, e.g. do if -x <= m1: et cetera.\n", "Solution that returns second unique number in list with no sort:\ndef sec_smallest(numbers):\n smallest = float('+inf')\n small = float('+inf')\n for i in numbers:\n if i < smallest:\n small = smallest\n smallest = i\n elif i < small and i != smallest:\n small = i\n return small\n\nprint('Sec_smallest:', sec_smallest([1, 2, -8, -8, -2, 0]))\n\n", " mi= min(input_list)\n second_min = float('inf')\n for i in input_list:\n if i != mi:\n if i<second_min:\n second_min=i\n if second_min == float('inf'):\n print('not present')\n else:\n print(second_min)\n \n\n##input_list = [6,6,6,6,6]\n#input_list = [3, 1, 4, 4, 5, 5, 5, 0, 2, 2]\n#input_list = [7, 2, 0, 9, -1, 8]\n# Even if there is same number in the list then Python will not get confused.\n\n", "I'd like to add another, more general approach:\nHere's a recursive way of finding the i-th minimums of a given list of numbers\ndef find_i_minimums(numbers,i):\n minimum = float('inf')\n if i==0:\n return []\n less_than_i_minimums = find_i_minimums(numbers,i-1)\n for element in numbers:\n if element not in less_than_i_minimums and element < minimum:\n minimum = element\n return less_than_i_minimums + [minimum]\n\nFor example,\n>>> find_i_minimums([0,7,4,5,21,2,6,1],3) # finding 3 minimial values for the given list\n[0, 1, 2]\n\n( And if you want only the i-th minimum number you'd extract the final value of the list )\nThe time-complexity of the above algorithm is bad though, it is O(N*i^2) ( Since the recursion depth is i , and at each recursive call we go over all values in 'numbers' list whose length is N and we check if the minimum element we're searching for isn't in a list of length i-1, thus the total complexity can be described by a geometric sum that will give the above mentioned complexity ).\nHere's a similar but alternative-implementation whose time-complexity is O(N*i) on average. It uses python's built-in 'set' data-structure:\ndef find_i_minimums(numbers,i):\n minimum = float('inf')\n if i==0:\n return set()\n less_than_i_minimums = find_i_minimums(numbers,i-1)\n for element in numbers:\n if element not in less_than_i_minimums and element < minimum:\n minimum = element\n return less_than_i_minimums.union(set({minimum}))\n\nIf your 'i' is small, you can use the implementations above and then extract how many minimums you want ( or if you want the second minimum, then in your case run the code for i=2 and just extract the last element from the output data-structure ).\nBut if 'i' is for example greater than log(N) , I'd recommend sorting the list of numbers itself ( for example, using mergesort whose complexity is O(N*log(N)) at worst case ) and then taking the i-th element. Why so? because as stated, the run-time of the algorithm above is not great for larger values of 'i'.\n", "You might find this code easy and understandable\ndef secsmall(numbers):\nsmall = max(numbers)\nfor i in range(len(numbers)):\n if numbers[i]>min(numbers):\n if numbers[i]<small:\n small = numbers[i]\nreturn small\n\nI am assuming \"numbers\" is a list name.\n" ]
[ 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 magic numbers), next we iterate on all the remaining numbers, maintaining our invariant.\ndef second_smaller(numbers):\n # if len(numbers)<2: return None or otherwise raise an exception\n\n m1, m2 = numbers[:2]\n if m2<m1: m1, m2 = m2, m1\n\n for x in numbers[2:]:\n if x <= m1:\n m1, m2 = x, m1\n elif x < m2:\n m2 = x\n return m2\n\nAddendum\nBTW, the same reasoning should be applied to the second_largest function mentioned by the OP\n", "l = [41,9000,123,1337]\n\n# second smallest\nsorted(l)[1]\n123\n\n\n# second biggest\nsorted(l)[-2]\n1337\n\n", "I am writing the code which is using recursion to find the second smallest element in a list.\ndef small(l):\n small.counter+=1;\n min=l[0];\n\n emp=[]\n\n for i in range(len(l)):\n if l[i]<min:\n min=l[i]\n\n for i in range(len(l)):\n if min==l[i]:\n emp.append(i)\n\n if small.counter==2:\n print \"The Second smallest element is:\"+str(min)\n else:\n for j in range(0,len(emp)):\n\n l.remove(min)\n\n small(l)\nsmall.counter = 0\n\nlist=[-1-1-1-1-1-1-1-1-1,1,1,1,1,1]\nsmall(list)\n\nYou can test it with various input integers.\n", "There is a easy way to do . First sort the list and get the second item from the list.\ndef solution(a_list):\n\n a_list.sort()\n print a_list[1]\n\nsolution([1, 2, -8, -2, -10])\n\n", "You can use in built function 'sorted'\ndef second_smallest(numbers):\n\ncount = 0\nl = []\nfor i in numbers:\n if(i not in l):\n l.append(i)\n count+=1\n if(count==2):\n break\n\nreturn max(l)\n\n", "To find second smallest in the list, use can use following approach which will work if two or more elements are repeated.\ndef second_smallest(numbers):\n s = sorted(set(numbers))\n return s[1]\n\n", "Here is:\ndef find_second_smallest(a: list) -> int:\n first, second = float('inf')\n for i in range(len(a)):\n if a[i] < first:\n first, second = a[i], first\n elif a[i] < second and a[i] != first:\n second = a[i]\n return second\n\ninput: [1, 1, 1, 2]\noutput: 2\n", "This code is also works fine, To find the second smallest number in list.\nFor this code first we have to sort the values in list. after that we have to initialize the variable as second index.\nl1 = [12,32,4,34,64,3,43]\nfor i in range(0,len(l1)):\n for j in range(0,i+1):\n if l1[i]<l1[j]:\n l1[i],l1[j]=l1[j],l1[i]\nmin_val = l1[1]\nfor k in l1:\n if min_val>k:\n break\nprint(min_val)\n\n", "def SecondSmallest(x):\n lowest=min(x[0],x[1])\n lowest2 = max(x[0],x[1])\n for item in x:\n if item < lowest:\n lowest2 = lowest\n lowest = item\n elif lowest2 > item and item > lowest:\n lowest2 = item\n return lowest2\n\nSecondSmallest([10,1,-1,2,3,4,5])\n\n" ]
[ -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 defs? import pygame from pygame.locals import ( K_UP, K_DOWN, K_LEFT, K_RIGHT, K_ESCAPE, KEYDOWN, QUIT, ) pygame.init() SCREEN_WIDTH = 800 SCREEN_HEIGHT = 600 screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT)) #Define a player object by extending pygame.sprite.Sprite # The surface drawn on the screen is now an attribute of Player class Player(pygame.sprite.Sprite): def __init__(self): super(Player,self).__init__() self.surf = pygame.Surface((75,25)) self.surf.fill((255,255,255)) self.rect = self.surf.get_rect() def update(self, pressed_keys): if pressed_keys[K_UP]: self.rect.move_ip(0,-5) if pressed_keys[K_DOWN]: self.rect.move_ip(0,5) if pressed_keys[K_LEFT]: self.rect.move_ip(-5,0) if pressed_keys[K_RIGHT]: self.rect.move_ip(5,0) #Instantiate player pygame.init() player = Player() #keeps main loop running running = True #main loop while running: for event in pygame.event.get(): #Did user hit a key? if event.type == KEYDOWN: # Was it the escape key? if so, exit loop if event.key == K_ESCAPE: running = False elif event.type == QUIT: running = False pressed_keys = pygame.key.get_pressed() player.update(pressed_keys) screen.fill((0,0,0)) screen.blit(player.surf,(SCREEN_WIDTH/2,SCREEN_HEIGHT/2)) pygame.display.flip() I tried to make the block move by clicking the arrow keys. A: You always draw the player in the center of the screen: screen.blit(player.surf,(SCREEN_WIDTH/2,SCREEN_HEIGHT/2)) You have to draw the player at player.rect: screen.blit(player.surf, player.rect) However, since you use pygame.sprite.Sprite you should also use pygame.sprite.Group and you should limit the frames per second with pygame.time.Clock.tick: clock = pygame.time.Clock() player = Player() spriteGroup = pygame.sprite.Group() spriteGroup.add(player) running = True while running: clock.tick(60) for event in pygame.event.get(): if event.type == KEYDOWN: if event.key == K_ESCAPE: running = False elif event.type == QUIT: running = False pressed_keys = pygame.key.get_pressed() player.update(pressed_keys) screen.fill((0,0,0)) spriteGroup.draw(screen) pygame.display.flip()
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, K_LEFT, K_RIGHT, K_ESCAPE, KEYDOWN, QUIT, ) pygame.init() SCREEN_WIDTH = 800 SCREEN_HEIGHT = 600 screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT)) #Define a player object by extending pygame.sprite.Sprite # The surface drawn on the screen is now an attribute of Player class Player(pygame.sprite.Sprite): def __init__(self): super(Player,self).__init__() self.surf = pygame.Surface((75,25)) self.surf.fill((255,255,255)) self.rect = self.surf.get_rect() def update(self, pressed_keys): if pressed_keys[K_UP]: self.rect.move_ip(0,-5) if pressed_keys[K_DOWN]: self.rect.move_ip(0,5) if pressed_keys[K_LEFT]: self.rect.move_ip(-5,0) if pressed_keys[K_RIGHT]: self.rect.move_ip(5,0) #Instantiate player pygame.init() player = Player() #keeps main loop running running = True #main loop while running: for event in pygame.event.get(): #Did user hit a key? if event.type == KEYDOWN: # Was it the escape key? if so, exit loop if event.key == K_ESCAPE: running = False elif event.type == QUIT: running = False pressed_keys = pygame.key.get_pressed() player.update(pressed_keys) screen.fill((0,0,0)) screen.blit(player.surf,(SCREEN_WIDTH/2,SCREEN_HEIGHT/2)) pygame.display.flip() I tried to make the block move by clicking the arrow keys.
[ "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 the frames per second with pygame.time.Clock.tick:\nclock = pygame.time.Clock()\nplayer = Player()\nspriteGroup = pygame.sprite.Group()\nspriteGroup.add(player)\n\nrunning = True\nwhile running:\n clock.tick(60)\n for event in pygame.event.get():\n if event.type == KEYDOWN:\n if event.key == K_ESCAPE:\n running = False\n elif event.type == QUIT:\n running = False\n\n pressed_keys = pygame.key.get_pressed()\n player.update(pressed_keys)\n\n screen.fill((0,0,0))\n spriteGroup.draw(screen)\n pygame.display.flip()\n\n" ]
[ 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). How can I solve this? import networkx as nx import matplotlib.pyplot as plt import itertools net = nx.complete_graph(20) fig = plt.figure(figsize=(12,12)) #nx.draw(net) d = nx.coloring.greedy_color(net) print(d) OUTPUT: { 0: 0, 1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7: 7, 8: 8, 9: 9, 10: 10, 11: 11, 12: 12, 13: 13, 14: 14, 15: 15, 16: 16, 17: 17, 18: 18, 19: 19 } I tried passing the graph created as a parameter inside greedy_color() But the output should give me a dictionary with value elements being repetitive and as least as possible for the given number of keys. (Key denotes nodes and value denotes color) A: Your code is correct, however complete graph means every node is next to each other, so each node will have a unique colour. For example, modifying the graph to a different one gives the following: from networkx import greedy_color from networkx import karate_club_graph G = karate_club_graph() print(greedy_color(G)) # {33: 0, 0: 0, 32: 1, 2: 2, 1: 1, 3: 3, 31: 2, 8: 3, 13: 4, 23: 2, 5: 1, 6: 2, 7: 4, 27: 1, 29: 3, 30: 2, 4: 1, 10: 2, 19: 2, 24: 0, 25: 1, 28: 1, 9: 1, 12: 1, 14: 2, 15: 2, 16: 0, 17: 2, 18: 2, 20: 2, 21: 2, 22: 2, 26: 1, 11: 1}
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 as nx import matplotlib.pyplot as plt import itertools net = nx.complete_graph(20) fig = plt.figure(figsize=(12,12)) #nx.draw(net) d = nx.coloring.greedy_color(net) print(d) OUTPUT: { 0: 0, 1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7: 7, 8: 8, 9: 9, 10: 10, 11: 11, 12: 12, 13: 13, 14: 14, 15: 15, 16: 16, 17: 17, 18: 18, 19: 19 } I tried passing the graph created as a parameter inside greedy_color() But the output should give me a dictionary with value elements being repetitive and as least as possible for the given number of keys. (Key denotes nodes and value denotes color)
[ "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_color(G))\n# {33: 0, 0: 0, 32: 1, 2: 2, 1: 1, 3: 3, 31: 2, 8: 3, 13: 4, 23: 2, 5: 1, 6: 2, 7: 4, 27: 1, 29: 3, 30: 2, 4: 1, 10: 2, 19: 2, 24: 0, 25: 1, 28: 1, 9: 1, 12: 1, 14: 2, 15: 2, 16: 0, 17: 2, 18: 2, 20: 2, 21: 2, 22: 2, 26: 1, 11: 1}\n\n" ]
[ 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): ") if record == 'n': continue_record = False else: distance, name, passenger_type = input_passenger() total_fare = compute(distance) get_receipt = receipt(name,passenger_type, distance, total_fare) file.write(get_receipt) file.write("\n") file.close() This is my input_passenger function: def input_passenger(): global distance global passenger_name global passenger_type passenger_name = input("Enter your name: ") distance = float(input("Enter distance: ")) passenger_type = input("Enter type of passenger: ") return passenger_name, distance, passenger_type #I tried returning them but it gives me this error Error: line 14, in <module> total_fare = compute(distance) line 29, in compute if distance > 0: TypeError: '>' not supported between instances of 'str' and 'int' This is my code in compute function def compute(distance): global fare fare = 0 if distance > 0: fare += 3 * 50 fare += (distance - 3) * 4.5 else: fare = round(distance * 50, 2) return fare I tried converting it, but it still the error A: You are returning the elements in a different order of unpacking them. return passenger_name, distance, passenger_type You unpack as the following (note that distance is actually the passenger_name). distance, name, passenger_type = input_passenger() You want name, distance, passenger_type = input_passenger() But yes like what others have said you likely want to avoid globals whenever you can.
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: distance, name, passenger_type = input_passenger() total_fare = compute(distance) get_receipt = receipt(name,passenger_type, distance, total_fare) file.write(get_receipt) file.write("\n") file.close() This is my input_passenger function: def input_passenger(): global distance global passenger_name global passenger_type passenger_name = input("Enter your name: ") distance = float(input("Enter distance: ")) passenger_type = input("Enter type of passenger: ") return passenger_name, distance, passenger_type #I tried returning them but it gives me this error Error: line 14, in <module> total_fare = compute(distance) line 29, in compute if distance > 0: TypeError: '>' not supported between instances of 'str' and 'int' This is my code in compute function def compute(distance): global fare fare = 0 if distance > 0: fare += 3 * 50 fare += (distance - 3) * 4.5 else: fare = round(distance * 50, 2) return fare I tried converting it, but it still the error
[ "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_passenger()\n\nBut yes like what others have said you likely want to avoid globals whenever you can.\n" ]
[ 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] because only [5,8,9] contain elements which are not found in any other list. I have created a program which seems to work, but I was wondering if there is a more reliable way to get unique values. viablepath=[[1,2,3,4],[1,3,6,7],[5,8,9]] unique=[] flattenedpath=[] for element in viablepath: if element[0] not in flattenedpath: unique.append(element) if element[0] in flattenedpath: for list in unique: if element[0] in list: unique.remove(list) for item in element: flattenedpath.append(item) print(flattenedpath) print(unique) enter code here This code works by basically flattening the input list of lists and appending to unique any value that is not found in list of lists to unique. i have no idea if that is a reliable strategy if im working with larger data sets which includes around 50 lists within a single list. A: Using collections.Counter and itertools.chain.from_iterable: from collections import Counter from itertools import chain lists = [[1, 2, 3, 4], [1, 3, 6, 7], [5, 8, 9]] counts = Counter(chain.from_iterable(lists)) unique = [ element for element in lists if all(counts[e] == 1 for e in element) ] print(unique) # [[5, 8, 9]] A: Using a python dictionary to count the frequency of each number and then check every list to see if it is unique. Using list methods like .remove or checking if the element is in a list takes O(n) while a hashmap(python dictionary) on average takes O(1) which is much faster. def is_unique(list_of_numbers,numbers_frequency): for number in list_of_numbers: if numbers_frequency[number] > 1 : return False return True def find_unique_lists(list_of_lists): numbers_frequency = {} for list_of_numbers in list_of_lists: for number in list_of_numbers: if number not in numbers_frequency: numbers_frequency[number] = 0 numbers_frequency[number] += 1 result = [] for list_of_numbers in list_of_lists: if is_unique(list_of_numbers,numbers_frequency): result.append(list_of_numbers) return result input_1 = [ [1,2,3,4], [1,3,6,7], [5,8,9] ] expected_output1 = [[5,8,9]] input_2 = [[1,2,3,4], [5,6,7,8], [9,10,11,12]] expected_output2 = [[1,2,3,4], [5,6,7,8], [9,10,11,12]] input_3 = [[10,13,14], [10,11,12], [8,9,10]] expected_output3 = [] input_4 = [[1,2,3,i] for i in range(100)] input_4.append([100,200,300]) input_4.append([101,110,111]) expected_output4 = [[100,200,300], [101,110,111]] print(find_unique_lists(input_1) == expected_output1 ) print(find_unique_lists(input_2) == expected_output2 ) print(find_unique_lists(input_3) == expected_output3 ) print(find_unique_lists(input_4) == expected_output4 ) #output #True #True #True #True
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 a program which seems to work, but I was wondering if there is a more reliable way to get unique values. viablepath=[[1,2,3,4],[1,3,6,7],[5,8,9]] unique=[] flattenedpath=[] for element in viablepath: if element[0] not in flattenedpath: unique.append(element) if element[0] in flattenedpath: for list in unique: if element[0] in list: unique.remove(list) for item in element: flattenedpath.append(item) print(flattenedpath) print(unique) enter code here This code works by basically flattening the input list of lists and appending to unique any value that is not found in list of lists to unique. i have no idea if that is a reliable strategy if im working with larger data sets which includes around 50 lists within a single list.
[ "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 element)\n]\n\nprint(unique)\n# [[5, 8, 9]]\n\n", "Using a python dictionary to count the frequency of each number and then check every list to see if it is unique. Using list methods like .remove or checking if the element is in a list takes O(n) while a hashmap(python dictionary) on average takes O(1) which is much faster.\ndef is_unique(list_of_numbers,numbers_frequency):\n for number in list_of_numbers:\n if numbers_frequency[number] > 1 :\n return False\n return True\n\ndef find_unique_lists(list_of_lists):\n numbers_frequency = {}\n\n for list_of_numbers in list_of_lists:\n for number in list_of_numbers:\n if number not in numbers_frequency:\n numbers_frequency[number] = 0\n\n numbers_frequency[number] += 1\n\n result = []\n for list_of_numbers in list_of_lists:\n if is_unique(list_of_numbers,numbers_frequency):\n result.append(list_of_numbers)\n\n return result\n\ninput_1 = [ [1,2,3,4],\n [1,3,6,7],\n [5,8,9] ]\nexpected_output1 = [[5,8,9]]\n\ninput_2 = [[1,2,3,4],\n [5,6,7,8],\n [9,10,11,12]]\n\nexpected_output2 = [[1,2,3,4],\n [5,6,7,8],\n [9,10,11,12]]\n\ninput_3 = [[10,13,14],\n [10,11,12],\n [8,9,10]]\n\nexpected_output3 = []\n\ninput_4 = [[1,2,3,i] for i in range(100)]\ninput_4.append([100,200,300])\ninput_4.append([101,110,111])\n\nexpected_output4 = [[100,200,300],\n [101,110,111]]\n\nprint(find_unique_lists(input_1) == expected_output1 )\nprint(find_unique_lists(input_2) == expected_output2 )\nprint(find_unique_lists(input_3) == expected_output3 )\nprint(find_unique_lists(input_4) == expected_output4 )\n\n#output\n#True\n#True\n#True\n#True\n\n" ]
[ 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 my request ... so ... how should I disable it? A: 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 called in order to persist data to the database. During this time, other transactions in progress elsewhere will not see this data. However, due to the isolated nature of transactions, there's an extra twist. Those other transactions in progress will not only not see your transaction's data until it is committed, they also can't see it in some cases until they are committed or rolled back also (which is the same effect your close() is having here). A transaction with an average degree of isolation will hold onto the state that it has loaded thus far, and keep giving you that same state local to the transaction even though the real data has changed - this is called repeatable reads in transaction isolation parlance. http://en.wikipedia.org/wiki/Isolation_%28database_systems%29 A: This issue has been really frustrating for me, but I have finally figured it out. I have a Flask/SQLAlchemy Application running alongside an older PHP site. The PHP site would write to the database and SQLAlchemy would not be aware of any changes. I tried the sessionmaker setting autoflush=True unsuccessfully I tried db_session.flush(), db_session.expire_all(), and db_session.commit() before querying and NONE worked. Still showed stale data. Finally I came across this section of the SQLAlchemy docs: http://docs.sqlalchemy.org/en/latest/dialects/postgresql.html#transaction-isolation-level Setting the isolation_level worked great. Now my Flask app is "talking" to the PHP app. Here's the code: engine = create_engine( "postgresql+pg8000://scott:tiger@localhost/test", isolation_level="READ UNCOMMITTED" ) When the SQLAlchemy engine is started with the "READ UNCOMMITED" isolation_level it will perform "dirty reads" which means it will read uncommited changes directly from the database. Hope this helps Here is a possible solution courtesy of AaronD in the comments from flask.ext.sqlalchemy import SQLAlchemy class UnlockedAlchemy(SQLAlchemy): def apply_driver_hacks(self, app, info, options): if "isolation_level" not in options: options["isolation_level"] = "READ COMMITTED" return super(UnlockedAlchemy, self).apply_driver_hacks(app, info, options) A: Additionally to zzzeek excellent answer, I had a similar issue. I solved the problem by using short living sessions. with closing(new_session()) as sess: # do your stuff I used a fresh session per task, task group or request (in case of web app). That solved the "caching" problem for me. This material was very useful for me: When do I construct a Session, when do I commit it, and when do I close it A: This was happening in my Flask application, and my solution was to expire all objects in the session after every request. from flask.signals import request_finished def expire_session(sender, response, **extra): app.db.session.expire_all() request_finished.connect(expire_session, flask_app) Worked like a charm. A: I have tried session.commit(), session.flush() none worked for me. After going through sqlalchemy source code, I found the solution to disable caching. Setting query_cache_size=0 in create_engine worked. create_engine(connection_string, convert_unicode=True, echo=True, query_cache_size=0)
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 disable it?
[ "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 called in order to persist data to the database. During this time, other transactions in progress elsewhere will not see this data.\nHowever, due to the isolated nature of transactions, there's an extra twist. Those other transactions in progress will not only not see your transaction's data until it is committed, they also can't see it in some cases until they are committed or rolled back also (which is the same effect your close() is having here). A transaction with an average degree of isolation will hold onto the state that it has loaded thus far, and keep giving you that same state local to the transaction even though the real data has changed - this is called repeatable reads in transaction isolation parlance.\nhttp://en.wikipedia.org/wiki/Isolation_%28database_systems%29\n", "This issue has been really frustrating for me, but I have finally figured it out. \nI have a Flask/SQLAlchemy Application running alongside an older PHP site. The PHP site would write to the database and SQLAlchemy would not be aware of any changes.\nI tried the sessionmaker setting autoflush=True unsuccessfully\nI tried db_session.flush(), db_session.expire_all(), and db_session.commit() before querying and NONE worked. Still showed stale data. \nFinally I came across this section of the SQLAlchemy docs: http://docs.sqlalchemy.org/en/latest/dialects/postgresql.html#transaction-isolation-level\nSetting the isolation_level worked great. Now my Flask app is \"talking\" to the PHP app. Here's the code:\nengine = create_engine(\n \"postgresql+pg8000://scott:tiger@localhost/test\",\n isolation_level=\"READ UNCOMMITTED\"\n)\n\nWhen the SQLAlchemy engine is started with the \"READ UNCOMMITED\" isolation_level it will perform \"dirty reads\" which means it will read uncommited changes directly from the database.\nHope this helps\n\nHere is a possible solution courtesy of AaronD in the comments\nfrom flask.ext.sqlalchemy import SQLAlchemy\n\nclass UnlockedAlchemy(SQLAlchemy):\n def apply_driver_hacks(self, app, info, options):\n if \"isolation_level\" not in options:\n options[\"isolation_level\"] = \"READ COMMITTED\"\n return super(UnlockedAlchemy, self).apply_driver_hacks(app, info, options)\n\n", "Additionally to zzzeek excellent answer,\nI had a similar issue. I solved the problem by using short living sessions.\nwith closing(new_session()) as sess:\n # do your stuff\n\nI used a fresh session per task, task group or request (in case of web app). That solved the \"caching\" problem for me.\nThis material was very useful for me:\nWhen do I construct a Session, when do I commit it, and when do I close it\n", "This was happening in my Flask application, and my solution was to expire all objects in the session after every request. \nfrom flask.signals import request_finished\ndef expire_session(sender, response, **extra):\n app.db.session.expire_all()\nrequest_finished.connect(expire_session, flask_app)\n\nWorked like a charm.\n", "I have tried session.commit(), session.flush() none worked for me.\nAfter going through sqlalchemy source code, I found the solution to disable caching.\nSetting query_cache_size=0 in create_engine worked.\ncreate_engine(connection_string, convert_unicode=True, echo=True, query_cache_size=0)\n\n" ]
[ 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 print \"username:\", row['username']\nconnection.close()\n(2) use Engine ...\n(3) use MegaData...\n\nplease folowing the step in : http://docs.sqlalchemy.org/en/latest/core/connections.html\nAnother possible reason is your MySQL DB is not updated permanently. Restart MySQL service and have a check.\n", "As i know SQLAlchemy does not store caches, so you need to looking at logging output.\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,Pune 2016 - 2020 Bachelor of Engineering Computer Science CGPA: 8.78 Vidya Bharati Chinmaya Vidyalaya,Jamshedpur 2014 - 2016 Intermediate-PCM,Economics CBSE Percentage: 88.8 Vidya Bharati Chinmaya Vidyalaya,Jamshedpur 2003 - 2014 Matriculation,CBSE CGPA: 8.6 EXPERIENCE I want the ouput: [{ "Institute": "NBN Sinhgad School Of Engineering", "Degree": "Bachelor of Engineering Computer Science", "Grades": "8.78", "Year of Passing": "2020" }, { "Institute": "Vidya Bharati Chinmaya Vidyalaya", "Degree": "Intermediate-PCM,Economics", "Grades": "88.8", "Year of Passing": "2016" }, { "Institute": "Vidya Bharati Chinmaya Vidyalaya", "Degree": "Matriculation,CBSE", "Grades": "8.6", "Year of Passing": "2014" }] Can it be done without training any custom NER model? Is there any pre-trained NER available to do this? A: yes it is possible to parse the data without training any custom NER model. you have to build the custom rules to parse the data. In 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 by keywords like school, institute,college ans so on... either way it depends on your case. import re txt = '''NBN Sinhgad School Of Engineering,Pune 2016 - 2020 Bachelor of Engineering Computer Science CGPA: 8.78 Vidya Bharati Chinmaya Vidyalaya,Jamshedpur 2014 - 2016 Intermediate-PCM,Economics CBSE Percentage: 88.8 Vidya Bharati Chinmaya Vidyalaya,Jamshedpur 2003 - 2014 Matriculation,CBSE CGPA: 8.6 EXPERIENCE''' # extract grades grade_regex = r'(?:\d{1,2}\.\d{1,2})' grades = re.findall(grade_regex, txt) # extract years year_regex = r'(?:\d{4}\s?-\s?\d{4})' years = re.findall(year_regex, txt) # function to replace a value in string def replacer(string, noise_list): for v in noise_list: string = string.replace(v, ":") return string # extract college data = replacer(txt, years) cleaned_text = re.sub("(?:\w+\s?\:)", "**", data).split('\n') college = [] degree = [] for i in cleaned_text: split_data = i.split("**") college.append(split_data[0].replace(',', '').strip()) degree.append(split_data[1].strip()) parsed_output = [] for i in range(len(grades)): parsed_data = { "Institute": college[i], "Degree": degree[i], "Grades": grades[i], "Year of Passing": years[i].split('-')[1] } parsed_output.append(parsed_data) print(parsed_output) >>>> [{'Institute': 'NBN Sinhgad School Of Engineering', 'Degree': 'Bachelor of Engineering Computer Science', 'Grades': '8.78', 'Year of Passing': ' 2020'}, {'Institute': 'Vidya Bharati Chinmaya Vidyalaya', 'Degree': 'Intermediate-PCM,Economics CBSE', 'Grades': '88.8', 'Year of Passing': ' 2016'}, {'Institute': 'Vidya Bharati Chinmaya Vidyalaya', 'Degree': 'Matriculation,CBSE', 'Grades': '8.6', 'Year of Passing': ' 2014'}]
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,Jamshedpur 2014 - 2016 Intermediate-PCM,Economics CBSE Percentage: 88.8 Vidya Bharati Chinmaya Vidyalaya,Jamshedpur 2003 - 2014 Matriculation,CBSE CGPA: 8.6 EXPERIENCE I want the ouput: [{ "Institute": "NBN Sinhgad School Of Engineering", "Degree": "Bachelor of Engineering Computer Science", "Grades": "8.78", "Year of Passing": "2020" }, { "Institute": "Vidya Bharati Chinmaya Vidyalaya", "Degree": "Intermediate-PCM,Economics", "Grades": "88.8", "Year of Passing": "2016" }, { "Institute": "Vidya Bharati Chinmaya Vidyalaya", "Degree": "Matriculation,CBSE", "Grades": "8.6", "Year of Passing": "2014" }] Can it be done without training any custom NER model? Is there any pre-trained NER available to do this?
[ "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 by keywords like school, institute,college ans so on... either way it depends on your case.\nimport re\n\ntxt = '''NBN Sinhgad School Of Engineering,Pune 2016 - 2020 Bachelor of Engineering Computer Science CGPA: 8.78 \nVidya Bharati Chinmaya Vidyalaya,Jamshedpur 2014 - 2016 Intermediate-PCM,Economics CBSE Percentage: 88.8\nVidya Bharati Chinmaya Vidyalaya,Jamshedpur 2003 - 2014 Matriculation,CBSE CGPA: 8.6 EXPERIENCE'''\n\n# extract grades\ngrade_regex = r'(?:\\d{1,2}\\.\\d{1,2})'\ngrades = re.findall(grade_regex, txt)\n\n# extract years\nyear_regex = r'(?:\\d{4}\\s?-\\s?\\d{4})'\nyears = re.findall(year_regex, txt)\n\n\n# function to replace a value in string\ndef replacer(string, noise_list):\n for v in noise_list:\n string = string.replace(v, \":\")\n return string\n\n\n# extract college\ndata = replacer(txt, years)\ncleaned_text = re.sub(\"(?:\\w+\\s?\\:)\", \"**\", data).split('\\n')\ncollege = []\ndegree = []\nfor i in cleaned_text:\n split_data = i.split(\"**\")\n college.append(split_data[0].replace(',', '').strip())\n degree.append(split_data[1].strip())\nparsed_output = []\nfor i in range(len(grades)):\n parsed_data = {\n \"Institute\": college[i],\n \"Degree\": degree[i],\n \"Grades\": grades[i],\n \"Year of Passing\": years[i].split('-')[1]\n }\n parsed_output.append(parsed_data)\nprint(parsed_output)\n\n>>>> [{'Institute': 'NBN Sinhgad School Of Engineering', 'Degree': 'Bachelor of Engineering Computer Science', 'Grades': '8.78', 'Year of Passing': ' 2020'}, {'Institute': 'Vidya Bharati Chinmaya Vidyalaya', 'Degree': 'Intermediate-PCM,Economics CBSE', 'Grades': '88.8', 'Year of Passing': ' 2016'}, {'Institute': 'Vidya Bharati Chinmaya Vidyalaya', 'Degree': 'Matriculation,CBSE', 'Grades': '8.6', 'Year of Passing': ' 2014'}]\n\n" ]
[ 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 WOOD.</SixteenCharacterName> <Address> <com:PostalAddress> <add:A_5LineAddress> <add:Line>Abbey Wood station</add:Line> <add:Line>Wilton Road</add:Line> <add:Line>Abbey Wood</add:Line> <add:Line>Greater London</add:Line> <add:PostCode>SE2 9RH</add:PostCode> </add:A_5LineAddress> </com:PostalAddress> </Address> ''', "lxml") tags = soup.find("AlternativeIdentifiers").name print(tags) for example, it will print AlternativeIdentifiers but I want the inside tag name too which is NationalLocationCode. I tried using the for loop but got the error. Just for more clarification I have tried find_all and then use the for loop to traverse to get the tag name but it will print the entire tag not the tag.name A: Just invoke the find_all method, then you will get the desired ResultSet. from bs4 import BeautifulSoup soup = BeautifulSoup(''' <AlternativeIdentifiers> <NationalLocationCode>513100</NationalLocationCode> </AlternativeIdentifiers> <Name>Abbey Wood</Name> <SixteenCharacterName>ABBEY WOOD.</SixteenCharacterName> <Address> <com:PostalAddress> <add:A_5LineAddress> <add:Line>Abbey Wood station</add:Line> <add:Line>Wilton Road</add:Line> <add:Line>Abbey Wood</add:Line> <add:Line>Greater London</add:Line> <add:PostCode>SE2 9RH</add:PostCode> </add:A_5LineAddress> </com:PostalAddress> </Address> ''', "xml") for tag in tags: print(tag.name) print(tag.find('NationalLocationCode').name) Output: AlternativeIdentifiers NationalLocationCode
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:PostalAddress> <add:A_5LineAddress> <add:Line>Abbey Wood station</add:Line> <add:Line>Wilton Road</add:Line> <add:Line>Abbey Wood</add:Line> <add:Line>Greater London</add:Line> <add:PostCode>SE2 9RH</add:PostCode> </add:A_5LineAddress> </com:PostalAddress> </Address> ''', "lxml") tags = soup.find("AlternativeIdentifiers").name print(tags) for example, it will print AlternativeIdentifiers but I want the inside tag name too which is NationalLocationCode. I tried using the for loop but got the error. Just for more clarification I have tried find_all and then use the for loop to traverse to get the tag name but it will print the entire tag not the tag.name
[ "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.</SixteenCharacterName>\n<Address>\n <com:PostalAddress>\n <add:A_5LineAddress>\n <add:Line>Abbey Wood station</add:Line>\n <add:Line>Wilton Road</add:Line>\n <add:Line>Abbey Wood</add:Line>\n <add:Line>Greater London</add:Line>\n <add:PostCode>SE2 9RH</add:PostCode>\n </add:A_5LineAddress>\n </com:PostalAddress>\n</Address>\n ''', \"xml\")\n\nfor tag in tags:\n print(tag.name)\n print(tag.find('NationalLocationCode').name)\n\nOutput:\nAlternativeIdentifiers\nNationalLocationCode\n\n" ]
[ 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 just a few clock cycles? It there a way to confirm how many clock cycles per instructions like adding and subing it takes in python? if so how? A: 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. For python there is a package called hwcounter that can be used as follows: # pip install hwcounter from hwcounter import Timer, count, count_end from time import sleep # Method-1 start = count() # Do something here: sleep(1) elapsed = count_end() - start print(f'Elapsed cycles: {elapsed:,}') # Method-2 with Timer() as t: # Do something here: sleep(1) print(f'Elapsed cycles: {t.cycles:,}') NOTE: It seem that the hwcounter implementation is currently broken for Windows python builds. A working alternative is to build the pip package using the mingw compiler, instead of MS VS. Caveats Using this method, always depend on how your computer is scheduling tasks and threads among its processors. Ideally you'd need to: bind the test code to one unused processor (aka. processor affinity) Run the tests over 1k - 1M times to get a good average. Need a good understanding of not only compilers, but also how python optimize its code internally. Many things are not at all obvious, especially if you come from C/C++/C# background. Rabbit Hole: http://en.wikipedia.org/wiki/Time_Stamp_Counter https://github.com/MicrosoftDocs/cpp-docs/blob/main/docs/intrinsics/rdtsc.md How to get the CPU cycle count in x86_64 from C++? __asm __rdtsc __cpuid, __cpuidex Defining __asm Blocks as C Macros
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 many clock cycles per instructions like adding and subing it takes in python? if so 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 Timer, count, count_end\nfrom time import sleep\n\n# Method-1\nstart = count()\n# Do something here:\nsleep(1)\nelapsed = count_end() - start\nprint(f'Elapsed cycles: {elapsed:,}')\n\n# Method-2\nwith Timer() as t:\n # Do something here:\n sleep(1)\nprint(f'Elapsed cycles: {t.cycles:,}')\n\n\n\nNOTE:\nIt seem that the hwcounter implementation is currently broken for Windows python builds. A working alternative is to build the pip package using the mingw compiler, instead of MS VS.\n\n\nCaveats\nUsing this method, always depend on how your computer is scheduling tasks and threads among its processors. Ideally you'd need to:\n\nbind the test code to one unused processor (aka. processor affinity)\nRun the tests over 1k - 1M times to get a good average.\nNeed a good understanding of not only compilers, but also how python optimize its code internally. Many things are not at all obvious, especially if you come from C/C++/C# background.\n\nRabbit Hole:\n\nhttp://en.wikipedia.org/wiki/Time_Stamp_Counter\nhttps://github.com/MicrosoftDocs/cpp-docs/blob/main/docs/intrinsics/rdtsc.md\nHow to get the CPU cycle count in x86_64 from C++?\n__asm\n__rdtsc\n__cpuid, __cpuidex\nDefining __asm Blocks as C Macros\n\n" ]
[ 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.ForeignKey(RealTimeLocation, on_delete=models.CASCADE, related_name='cablog_locations') Then i thought, no need for an FK field, so i changed the fk field to a Point field. class RealTimeLocation(models.Model): name = models.CharField(max_length=80) latlng = models.PointField(default=None) class CabLog(models.Model): location = models.PointField()// 'python manage.py makemigrations ' no issues, but on migrate i'm getting error. .django.db.utils.ProgrammingError: column "location_id" of relation "myapp_cablog" does not exist. I tried adding a null=True option to pointfield, deleting the migrate-scripts and redo it many times, no avail. SO before i completely fake-migrate the entire project and startover, do anybody have any solutions for this. I already got some data in DB, so i really don't want to do that. Thanks. A: You got this error because you run only makemigrations and migrate. You must run sqlmigrate also. Try these three commands: python manage.py makemigrations appname python manage.py sqlmigrate appname 0001 #You didn't run this command after makemigrations that's why you got that error python manage.py migrate Note: 0001 this value will generate after makemigrations. It can be either 0001, 0002 and so on.
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.CASCADE, related_name='cablog_locations') Then i thought, no need for an FK field, so i changed the fk field to a Point field. class RealTimeLocation(models.Model): name = models.CharField(max_length=80) latlng = models.PointField(default=None) class CabLog(models.Model): location = models.PointField()// 'python manage.py makemigrations ' no issues, but on migrate i'm getting error. .django.db.utils.ProgrammingError: column "location_id" of relation "myapp_cablog" does not exist. I tried adding a null=True option to pointfield, deleting the migrate-scripts and redo it many times, no avail. SO before i completely fake-migrate the entire project and startover, do anybody have any solutions for this. I already got some data in DB, so i really don't want to do that. Thanks.
[ "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 migrate\n\nNote: 0001 this value will generate after makemigrations. It can be either 0001, 0002 and so on.\n" ]
[ 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 the length of the line is greater than 0? A: I think it is a logical error: Even 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" so the length of no input i.e empty input is 0 but the terminal condition didn't meet
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 K L M N I'm getting the following results when I concatenate the two data frames: Column1 Column2 Column3 Column4 Column5 Column6 A B C D E F G H I J K L M N However, I want the intended result to be as :- Column1 Column2 Column3 Column4 Column5 Column6 A B C D E F A B G H I J A B K L M N A: What you need is ffill . Assuming final concated DataFrame as df df['Column1'] = df['Column1'].replace('', np.nan).ffill() df['Column2'] = df['Column2'].replace('', np.nan).ffill() Should Gives # Column1 Column2 Column3 Column4 Column5 Column6 A B C D E F A B G H I J A B K L M N If you want to do at once then import numpy as np df = df.replace('', np.nan) df=df.fillna(method='ffill')
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'm getting the following results when I concatenate the two data frames: Column1 Column2 Column3 Column4 Column5 Column6 A B C D E F G H I J K L M N However, I want the intended result to be as :- Column1 Column2 Column3 Column4 Column5 Column6 A B C D E F A B G H I J A B K L M N
[ "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 G H I J\n A B K L M N\n\nIf you want to do at once then\nimport numpy as np\n\ndf = df.replace('', np.nan)\ndf=df.fillna(method='ffill')\n\n" ]
[ 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 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): Name = N age = a gender = g Username = Uname Password = Pwd Address = Addr CCinfo = CC UserCart = os.getcwd() + self.Username + "_UC.csv" OrderHistory = os.getcwd() + self.Username +"_OH.csv" UserCart and OrderHistory are supposed to be strings that when a user is created, grab the current directory, + the Username of the USR instance, + "_UC.csv" or "_OH.csv" respectively. in my testing function. i am doing the following: print("testing USR init") Usr = UserClass.USR("Andrew", 69,"Other","idk",1234,"some house",1234567891012131) print(Usr.UserCart) print(Usr.OrderHistory) when the code is run in the command line (OS = win10) i get the following error line 12, in __init__, UserCart = os.getcwd() + self.Username + "_UC.csv" AttributeError: 'USR' object has no attribute 'Username' I'm assuming this is because of the fact that the Username attribute is set in the same function? i don't really know what to do about this. Any tips or solutions are welcome, thank you! I've tried setting them to use self.Name aswell, i still get the same attribute error. I'm not sure what else to try to solve the issue at hand. A: def __init__(self,N,a,g,Uname,Pwd,Addr,CC): Name = N age = a gender = g Username = Uname Password = Pwd Address = Addr CCinfo = CC You need to put self. in front of these variable names. self.Name = N, etc.
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): Name = N age = a gender = g Username = Uname Password = Pwd Address = Addr CCinfo = CC UserCart = os.getcwd() + self.Username + "_UC.csv" OrderHistory = os.getcwd() + self.Username +"_OH.csv" UserCart and OrderHistory are supposed to be strings that when a user is created, grab the current directory, + the Username of the USR instance, + "_UC.csv" or "_OH.csv" respectively. in my testing function. i am doing the following: print("testing USR init") Usr = UserClass.USR("Andrew", 69,"Other","idk",1234,"some house",1234567891012131) print(Usr.UserCart) print(Usr.OrderHistory) when the code is run in the command line (OS = win10) i get the following error line 12, in __init__, UserCart = os.getcwd() + self.Username + "_UC.csv" AttributeError: 'USR' object has no attribute 'Username' I'm assuming this is because of the fact that the Username attribute is set in the same function? i don't really know what to do about this. Any tips or solutions are welcome, thank you! I've tried setting them to use self.Name aswell, i still get the same attribute error. I'm not sure what else to try to solve the issue at hand.
[ "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 doing wrong? I'm pretty sure there's something wrong with my 'print queue' (maybe getting corrupted) or with the Windows processing timeout... The script is: import os import os.path import subprocess from subprocess import * import sys import time from watchdog.observers import Observer from watchdog.events import FileSystemEventHandler class Watcher: DIRECTORY_TO_WATCH = r"C:\Users\50544342\Desktop\Newfolder3\Files" def __init__(self): self.observer = Observer() def run(self): event_handler = Handler() self.observer.schedule(event_handler, self.DIRECTORY_TO_WATCH, recursive=True) self.observer.start() try: while True: time.sleep(5) except: self.observer.stop() print("Error") self.observer.join() class Handler(FileSystemEventHandler): @staticmethod def on_any_event(event): if event.is_directory: # LPR print from batch on any event. p = subprocess.Popen(['LPR.bat', event.src_path], stdout=PIPE, stderr=PIPE) output, errors = p.communicate() p.wait() # wait for process to terminate elif event.event_type == 'created': # LPR print from batch when a file is first created. p = subprocess.Popen(['LPR.bat', event.src_path], stdout=PIPE, stderr=PIPE) output, errors = p.communicate() p.wait() # wait for process to terminate if __name__ == '__main__': w = Watcher() w.run() The LPR.bat reads: lpr.exe -S 127.0.0.1 -P Queue %1 Thanks in advance for any help or tips you may provide. A: You should try changing the buffer size of watchdog. Look at this. try to use a bigger buffer size: Value to change
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 my 'print queue' (maybe getting corrupted) or with the Windows processing timeout... The script is: import os import os.path import subprocess from subprocess import * import sys import time from watchdog.observers import Observer from watchdog.events import FileSystemEventHandler class Watcher: DIRECTORY_TO_WATCH = r"C:\Users\50544342\Desktop\Newfolder3\Files" def __init__(self): self.observer = Observer() def run(self): event_handler = Handler() self.observer.schedule(event_handler, self.DIRECTORY_TO_WATCH, recursive=True) self.observer.start() try: while True: time.sleep(5) except: self.observer.stop() print("Error") self.observer.join() class Handler(FileSystemEventHandler): @staticmethod def on_any_event(event): if event.is_directory: # LPR print from batch on any event. p = subprocess.Popen(['LPR.bat', event.src_path], stdout=PIPE, stderr=PIPE) output, errors = p.communicate() p.wait() # wait for process to terminate elif event.event_type == 'created': # LPR print from batch when a file is first created. p = subprocess.Popen(['LPR.bat', event.src_path], stdout=PIPE, stderr=PIPE) output, errors = p.communicate() p.wait() # wait for process to terminate if __name__ == '__main__': w = Watcher() w.run() The LPR.bat reads: lpr.exe -S 127.0.0.1 -P Queue %1 Thanks in advance for any help or tips you may provide.
[ "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() win32clipboard.EmptyClipboard() win32clipboard.SetClipboardData(clip_type, data) win32clipboard.CloseClipboard() clip_type = win32clipboard.CF_BITMAP filepath = 'c:\\temp\\image.jpg' im = Image.open(filepath) data = im.tobitmap() # fails with valueerror: not a bitmap # data = im.tostring() runs, but receiving programs can't read the results send_to_clipboard(clip_type, data) I could install PythonMagick, etc., but would prefer not installing yet another library for a one-off program A: from cStringIO import StringIO import win32clipboard from PIL import Image def send_to_clipboard(clip_type, data): win32clipboard.OpenClipboard() win32clipboard.EmptyClipboard() win32clipboard.SetClipboardData(clip_type, data) win32clipboard.CloseClipboard() filepath = 'image.jpg' image = Image.open(filepath) output = StringIO() image.convert("RGB").save(output, "BMP") data = output.getvalue()[14:] output.close() send_to_clipboard(win32clipboard.CF_DIB, data) A: The file header off-set of BMP is 14 bytes. Well, BMP is also known as the device independent bitmap (DIB) file format, so you don't need to worried about the magic number 14. FYI, it does need a windows clipboard API. Hence you can use BMP but can't use image.convert("RGB").save(output, "PNG") data = output.getvalue()[8:] even you know the offset is 8 for PNG. A: This worked for me in Python 3.8 (solution found here) It's the same answer as the cgohike's but: output = StringIO() changed into: output = io.BytesIO() Full code: import io import win32clipboard from PIL import Image def send_to_clipboard(clip_type, data): win32clipboard.OpenClipboard() win32clipboard.EmptyClipboard() win32clipboard.SetClipboardData(clip_type, data) win32clipboard.CloseClipboard() image = Image.open('image.jpg') output = io.BytesIO() image.convert("RGB").save(output, "BMP") data = output.getvalue()[14:] output.close() send_to_clipboard(win32clipboard.CF_DIB, data) A: Addendum to the other answers, it's also possible to copy PNG (and probably other formats) to the clipboard. I've used the following: buffer = io.BytesIO() img_out.save(fp=buffer, format='PNG') clipboard_format = win32clipboard.RegisterClipboardFormat('PNG') win32clipboard.OpenClipboard() win32clipboard.EmptyClipboard() win32clipboard.SetClipboardData(clipboard_format, buffer.getvalue()) win32clipboard.CloseClipboard() buffer.close() This answer to a related question details support by some programs for the non-standard clipboard format "PNG", which I used in my answer. If the program you want to copy to accepts a custom clipboard format, this is an alternative. You can also of course define many standard and/or non-standard clipboard formats together.
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) win32clipboard.CloseClipboard() clip_type = win32clipboard.CF_BITMAP filepath = 'c:\\temp\\image.jpg' im = Image.open(filepath) data = im.tobitmap() # fails with valueerror: not a bitmap # data = im.tostring() runs, but receiving programs can't read the results send_to_clipboard(clip_type, data) I could install PythonMagick, etc., but would prefer not installing yet another library for a one-off program
[ "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'\nimage = Image.open(filepath)\n\noutput = StringIO()\nimage.convert(\"RGB\").save(output, \"BMP\")\ndata = output.getvalue()[14:]\noutput.close()\n\nsend_to_clipboard(win32clipboard.CF_DIB, data)\n\n", "The file header off-set of BMP is 14 bytes. Well, BMP is also known as the device independent bitmap (DIB) file format, so you don't need to worried about the magic number 14. \nFYI, it does need a windows clipboard API. Hence you can use BMP but can't use \nimage.convert(\"RGB\").save(output, \"PNG\")\ndata = output.getvalue()[8:]\n\neven you know the offset is 8 for PNG.\n", "This worked for me in Python 3.8 (solution found here)\nIt's the same answer as the cgohike's but:\noutput = StringIO()\n\nchanged into:\noutput = io.BytesIO()\n\nFull code:\nimport io\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\nimage = Image.open('image.jpg')\n\noutput = io.BytesIO()\nimage.convert(\"RGB\").save(output, \"BMP\")\ndata = output.getvalue()[14:]\noutput.close()\n\nsend_to_clipboard(win32clipboard.CF_DIB, data)\n\n", "Addendum to the other answers, it's also possible to copy PNG (and probably other formats) to the clipboard. I've used the following:\nbuffer = io.BytesIO()\nimg_out.save(fp=buffer, format='PNG')\n\nclipboard_format = win32clipboard.RegisterClipboardFormat('PNG')\nwin32clipboard.OpenClipboard()\nwin32clipboard.EmptyClipboard()\nwin32clipboard.SetClipboardData(clipboard_format, buffer.getvalue())\nwin32clipboard.CloseClipboard()\n\nbuffer.close()\n\nThis answer to a related question details support by some programs for the non-standard clipboard format \"PNG\", which I used in my answer. If the program you want to copy to accepts a custom clipboard format, this is an alternative. You can also of course define many standard and/or non-standard clipboard formats together.\n" ]
[ 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'): can't open/read file: check file path/integrity" I've tried uninstalling opencv but nothing tried declaring a variable with the path to the image then call that through imread() but still nothing. I'm losing my marbles here man import cv2 import pytesseract as tess tess.pytesseract.tesseract_cmd = r'C:\Users\blkcap\AppData\Local\Programs\Tesseract-OCR\tesseract' import PIL as Image img = cv2.imread('hello.png') text = tess.image_to_string(img) cv2.resize(img, (800,500)) cv2.imshow('results', img) cv2.waitKey(0) I have my image in vscode in same working folder so that's why it's being called as shown above A: 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 A: i faced the same issue : "Pictures\screen1.jpg" [ WARN:0@447.011] global D:\a\opencv-python\opencv-pythonA\opencv\modules\imgcodecs\src\loadsave.cpp (239) cv::findDecoder imread_('Pictures\screen1.jpg'): can't open/read file: check file path/integrity in my case it got solved by changing the format to "Pictures\screen1.jpeg"
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 file path/integrity" I've tried uninstalling opencv but nothing tried declaring a variable with the path to the image then call that through imread() but still nothing. I'm losing my marbles here man import cv2 import pytesseract as tess tess.pytesseract.tesseract_cmd = r'C:\Users\blkcap\AppData\Local\Programs\Tesseract-OCR\tesseract' import PIL as Image img = cv2.imread('hello.png') text = tess.image_to_string(img) cv2.resize(img, (800,500)) cv2.imshow('results', img) cv2.waitKey(0) I have my image in vscode in same working folder so that's why it's being called as shown above
[ "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\\modules\\imgcodecs\\src\\loadsave.cpp (239) cv::findDecoder imread_('Pictures\\screen1.jpg'): can't open/read file: check file path/integrity\n\nin my case it got solved by changing the format to \"Pictures\\screen1.jpeg\"\n" ]
[ 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 functionally with Github's atom editor? A: The script package does exactly what you're looking for: https://atom.io/packages/script The package's documentation also contains the key mappings, which you can easily customize. A: Download and Install package here: https://atom.io/packages/script To execute the python command in atom use the below shortcuts: For Windows/Linux, it's SHIFT + Ctrl + B OR Ctrl + SHIFT + B If you're on Mac, press ⌘ + I A: To run the python file on mac. Open the preferences in atom ide. To open the preferences press 'command + . ' ( ⌘ + , ) Click on the install in the preferences to install packages. Search for package "script" and click on install Now open the python file(with .py extension ) you want to run and press 'control + r ' (^ + r) A: Yes, you can do it by: -- Install Atom -- Install Python on your system. Atom requires the latest version of Python (currently 3.8.5). Note that Anaconda sometimes may not have this version, and depending on how you installed it, it may not have been added to the PATH. Install Python via https://www.python.org/ and make sure to check the option of "Add to PATH" -- Install "scripts" on Atom via "Install packages" -- Install any other autocomplete package like Kite on Atom if you want that feature. -- Run it I tried the normal way (I had Python installed via Anaconda) but Atom did not detect it & gave me an error when I tried to run Python. This is the way around it. A: Follow the steps: Install Python Install Atom Install and configure Atom package for Python Install and configure Python Linter Install Script Package in Atom Download and install Syntax Highlighter for Python Install Version control package Run Python file More details for each step Click Here A: There is a package called "platformio-ide-terminal" that allows you to run Atom code with Ctrl + Shift + B". That's the only package you need (Windows). A: Use below command to install the script package in Atom. apm install script
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 editor?
[ "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 shortcuts:\nFor Windows/Linux, it's SHIFT + Ctrl + B OR Ctrl + SHIFT + B\nIf you're on Mac, press ⌘ + I\n", "To run the python file on mac.\n\nOpen the preferences in atom ide. To open the preferences press 'command + . '\n( ⌘ + , )\nClick on the install in the preferences to install packages.\nSearch for package \"script\" and click on install\nNow open the python file(with .py extension ) you want to run and press 'control + r ' (^ + r)\n\n", "Yes, you can do it by:\n-- Install Atom\n-- Install Python on your system. Atom requires the latest version of Python (currently 3.8.5). Note that Anaconda sometimes may not have this version, and depending on how you installed it, it may not have been added to the PATH. Install Python via https://www.python.org/ and make sure to check the option of \"Add to PATH\"\n-- Install \"scripts\" on Atom via \"Install packages\"\n-- Install any other autocomplete package like Kite on Atom if you want that feature.\n-- Run it\nI tried the normal way (I had Python installed via Anaconda) but Atom did not detect it & gave me an error when I tried to run Python. This is the way around it.\n", "Follow the steps:\n\nInstall Python\nInstall Atom\nInstall and configure Atom package for Python\nInstall and configure Python Linter\nInstall Script Package in Atom\nDownload and install Syntax Highlighter for Python\nInstall Version control package Run Python file\n\nMore details for each step Click Here\n", "There is a package called \"platformio-ide-terminal\" that allows you to run Atom code with Ctrl + Shift + B\". That's the only package you need (Windows).\n", "Use below command to install the script package in Atom.\napm install script\n\n" ]
[ 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/135ec7cefbaffd516b77362ad2b2ad1025af462e/Objects/setobject.c
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 generating passwords. After I upload user lists and save them in database, I want to send a reset password email to each user. In allauth to reset password you first need to go to reset page account/password/reset/ and type your email. then an email is send which directs you to change your password account/password/reset/key/(?P<uidb36>[0-9A-Za-z]+)-(?P<key>.+)/ Is it possible to send the email directly within the app? The url contains a key that I don't know how to generate!! Or is there any better way to do that? A: 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: from allauth.account.views import PasswordResetView from django.conf import settings from django.dispatch import receiver from django.http import HttpRequest from django.middleware.csrf import get_token @receiver(models.signals.post_save, sender=settings.AUTH_USER_MODEL) def send_reset_password_email(sender, instance, created, **kwargs): if created: # First create a post request to pass to the view request = HttpRequest() request.method = 'POST' # add the absolute url to be be included in email if settings.DEBUG: request.META['HTTP_HOST'] = '127.0.0.1:8000' else: request.META['HTTP_HOST'] = 'www.mysite.com' # pass the post form data request.POST = { 'email': instance.email, 'csrfmiddlewaretoken': get_token(HttpRequest()) } PasswordResetView.as_view()(request) # email will be sent! A: You can try to get URL for specific user using something like this: from allauth.account.forms import EmailAwarePasswordResetTokenGenerator from allauth.account.utils import user_pk_to_url_str token_generator = EmailAwarePasswordResetTokenGenerator() user = User.objects.get(email='example@example.com') temp_key = token_generator.make_token(user) path = reverse("account_reset_password_from_key", kwargs=dict(uidb36=user_pk_to_url_str(user), key=temp_key)) A: Following from @davecaputo's answer, you can also directly submit the form instead of creating and calling the view: from allauth.account.forms import ResetPasswordForm from django.conf import settings from django.http import HttpRequest def send_password_reset(user: settings.AUTH_USER_MODEL): request = HttpRequest() request.user = user request.META["HTTP_HOST"] = "www.mysite.com" form = ResetPasswordForm({"email": user.email}) if form.is_valid(): form.save(request)
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 database, I want to send a reset password email to each user. In allauth to reset password you first need to go to reset page account/password/reset/ and type your email. then an email is send which directs you to change your password account/password/reset/key/(?P<uidb36>[0-9A-Za-z]+)-(?P<key>.+)/ Is it possible to send the email directly within the app? The url contains a key that I don't know how to generate!! Or is there any better way to do that?
[ "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.views import PasswordResetView\n\nfrom django.conf import settings\nfrom django.dispatch import receiver\nfrom django.http import HttpRequest\nfrom django.middleware.csrf import get_token\n\n\n@receiver(models.signals.post_save, sender=settings.AUTH_USER_MODEL)\ndef send_reset_password_email(sender, instance, created, **kwargs):\n\n if created:\n\n # First create a post request to pass to the view\n request = HttpRequest()\n request.method = 'POST'\n\n # add the absolute url to be be included in email\n if settings.DEBUG:\n request.META['HTTP_HOST'] = '127.0.0.1:8000'\n else:\n request.META['HTTP_HOST'] = 'www.mysite.com'\n\n # pass the post form data\n request.POST = {\n 'email': instance.email,\n 'csrfmiddlewaretoken': get_token(HttpRequest())\n }\n PasswordResetView.as_view()(request) # email will be sent!\n\n", "You can try to get URL for specific user using something like this:\nfrom allauth.account.forms import EmailAwarePasswordResetTokenGenerator\nfrom allauth.account.utils import user_pk_to_url_str\n\ntoken_generator = EmailAwarePasswordResetTokenGenerator()\nuser = User.objects.get(email='example@example.com')\ntemp_key = token_generator.make_token(user)\npath = reverse(\"account_reset_password_from_key\", \n kwargs=dict(uidb36=user_pk_to_url_str(user), key=temp_key))\n\n", "Following from @davecaputo's answer, you can also directly submit the form instead of creating and calling the view:\nfrom allauth.account.forms import ResetPasswordForm\nfrom django.conf import settings\nfrom django.http import HttpRequest\n\n\ndef send_password_reset(user: settings.AUTH_USER_MODEL):\n request = HttpRequest()\n request.user = user\n request.META[\"HTTP_HOST\"] = \"www.mysite.com\"\n\n form = ResetPasswordForm({\"email\": user.email})\n if form.is_valid():\n form.save(request)\n\n" ]
[ 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 contend with a different order. I've tried reading documentation on dataframe.subtract() and don't understand how to apply it to my specific problem. data frame 1: CUSIP (x$1000) PRN AMT TICKER 594918104 2765345852 2114080582 MSFT 037833100 1891440177 3058252946 AAPL 02079K305 1721936077 132543866 GOOGL 023135106 1341784239 2573051329 AMZN data frame 2: CUSIP (x$1000) PRN AMT TICKER 594918104 3034828140 1612323669 MSFT 037833100 2463247977 2628732382 AAPL 02079K305 2096049986 93429916 GOOGL 023135106 1581124222 118724459 AMZN Wanted output: CUSIP (x$1000) PRN AMT TICKER 594918104 -269482288 501756913 MSFT 037833100 -571807800 429520564 AAPL 02079K305 -374113909 39113950 GOOGL 023135106 -239339983 2454326870 AMZN Here is the code to recreate the dataframes: import pandas as pd dataset_1 = {'CUSIP': ['594918104', '037833100', '02079K305', '023135106'], '(x$1000)': [ 2765345852, 1891440177, 1721936077, 1341784239], 'PRN AMT': [2114080582, 3058252946, 132543866, 2573051329], 'TICKER': ['MSFT', 'AAPL', 'GOOGL', 'AMZN']} dataset_2 = {'CUSIP': ['594918104', '037833100', '02079K305', '023135106'], '(x$1000)': [ 3034828140, 2463247977, 2096049986, 1581124222], 'PRN AMT': [1612323669, 2628732382, 93429916, 118724459], 'TICKER': ['MSFT', 'AAPL', 'GOOGL', 'AMZN']} df_1 = pd.DataFrame(data=dataset_1) df_2 = pd.DataFrame(data=dataset_2) print(f'{df_1} and {df_2}') A: Create MultiIndex by CUSIP,TICKER and subtract by DataFrame.sub, last DataFrame.reset_index and change order of columns by DataFrame.reindex: df = (df_1.set_index(['CUSIP','TICKER']) .sub(df_2.set_index(['CUSIP','TICKER'])) .reset_index() .reindex(df_1.columns, axis=1)) print (df) CUSIP (x$1000) PRN AMT TICKER 0 594918104 -269482288 501756913 MSFT 1 037833100 -571807800 429520564 AAPL 2 02079K305 -374113909 39113950 GOOGL 3 023135106 -239339983 2454326870 AMZN
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.subtract() and don't understand how to apply it to my specific problem. data frame 1: CUSIP (x$1000) PRN AMT TICKER 594918104 2765345852 2114080582 MSFT 037833100 1891440177 3058252946 AAPL 02079K305 1721936077 132543866 GOOGL 023135106 1341784239 2573051329 AMZN data frame 2: CUSIP (x$1000) PRN AMT TICKER 594918104 3034828140 1612323669 MSFT 037833100 2463247977 2628732382 AAPL 02079K305 2096049986 93429916 GOOGL 023135106 1581124222 118724459 AMZN Wanted output: CUSIP (x$1000) PRN AMT TICKER 594918104 -269482288 501756913 MSFT 037833100 -571807800 429520564 AAPL 02079K305 -374113909 39113950 GOOGL 023135106 -239339983 2454326870 AMZN Here is the code to recreate the dataframes: import pandas as pd dataset_1 = {'CUSIP': ['594918104', '037833100', '02079K305', '023135106'], '(x$1000)': [ 2765345852, 1891440177, 1721936077, 1341784239], 'PRN AMT': [2114080582, 3058252946, 132543866, 2573051329], 'TICKER': ['MSFT', 'AAPL', 'GOOGL', 'AMZN']} dataset_2 = {'CUSIP': ['594918104', '037833100', '02079K305', '023135106'], '(x$1000)': [ 3034828140, 2463247977, 2096049986, 1581124222], 'PRN AMT': [1612323669, 2628732382, 93429916, 118724459], 'TICKER': ['MSFT', 'AAPL', 'GOOGL', 'AMZN']} df_1 = pd.DataFrame(data=dataset_1) df_2 = pd.DataFrame(data=dataset_2) print(f'{df_1} and {df_2}')
[ "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)\n\n CUSIP (x$1000) PRN AMT TICKER\n0 594918104 -269482288 501756913 MSFT\n1 037833100 -571807800 429520564 AAPL\n2 02079K305 -374113909 39113950 GOOGL\n3 023135106 -239339983 2454326870 AMZN\n\n" ]
[ 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 frame rather than multiple small ones from bs4 import BeautifulSoup import requests import pandas as pd hdr = {'user-agent': 'Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (HTML, like Gecko) Chrome/92.0.4515.107 Mobile Safari/537.36'} for x in range(1,61,20): url = 'https://finviz.com/screener.ashx?v=111&r=' r = requests.get(url+str(x), headers=hdr) soup = BeautifulSoup(r.text, 'lxml') table = soup.find('table', {'class':'table-light'}) headers = [] for i in table.find_all('td')[:11]: title = i.text headers.append(title) df = pd.DataFrame(columns= headers) for row in table.find_all('tr')[1:]: data = row.find_all('td') row_data = [td.text.strip() for td in data] length = len(df) df.loc[length] = row_data df.to_csv('all.csv', index=False, encoding='utf-8') print(df) A: Here is how you can achieve your goal: import requests from bs4 import BeautifulSoup as bs import pandas as pd from tqdm import tqdm ## if using Jupyter: from tqdm.notebook import tqdm pd.set_option('display.max_columns', None) pd.set_option('display.max_colwidth', None) headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/105.0.0.0 Safari/537.36' } s = requests.Session() s.headers.update(headers) big_df = pd.DataFrame() for x in tqdm(range(1, 61, 20)): r = s.get(f'https://finviz.com/screener.ashx?v=111&r={x}') soup = bs(r.text, 'html.parser') df = pd.read_html(str(soup.select_one('table[id="screener-views-table"] table[class="table-light"]')), header=0)[0] big_df = pd.concat([big_df, df], axis=0, ignore_index=True) print(big_df) big_df.to_csv('some_fin_data.csv') Result in terminal: 100% 3/3 [00:01<00:00, 2.04it/s] No. Ticker Company Sector Industry Country Market Cap P/E Price Change Volume 0 1 A Agilent Technologies, Inc. Healthcare Diagnostics & Research USA 45.44B 35.44 155.35 -0.96% 1443781 1 2 AA Alcoa Corporation Basic Materials Aluminum USA 8.59B - 48.51 -1.72% 3213397 2 3 AAAU Goldman Sachs Physical Gold ETF Financial Exchange Traded Fund USA - - 17.38 0.64% 2781472 3 4 AAC Ares Acquisition Corporation Financial Shell Companies USA 1.25B 46.51 10.00 -0.05% 2537 4 5 AACG ATA Creativity Global Consumer Defensive Education & Training Services China 50.93M - 1.72 2.38% 2302 5 6 AACI Armada Acquisition Corp. I Financial Shell Companies USA 206.69M - 9.98 -0.05% 91802 6 7 AACIW Armada Acquisition Corp. I Financial Shell Companies USA - - 0.03 0.00% 0 7 8 AADI Aadi Bioscience, Inc. Healthcare Biotechnology USA 315.29M - 13.17 -1.86% 45328 8 9 AADR AdvisorShares Dorsey Wright ADR ETF Financial Exchange Traded Fund USA - - 49.17 0.53% 2232 9 10 AAIC Arlington Asset Investment Corp. Real Estate REIT - Mortgage USA 88.94M 46.97 3.10 2.99% 122458 10 11 AAL American Airlines Group Inc. Industrials Airlines USA 9.30B - 14.42 3.15% 23630403 11 12 AAME Atlantic American Corporation Financial Insurance - Life USA 61.09M 23.65 2.98 4.56% 383 12 13 AAN The Aaron's Company, Inc. Industrials Rental & Leasing Services USA 346.97M 23.51 11.85 1.37% 507153 13 14 AAOI Applied Optoelectronics, Inc. Technology Semiconductors USA 63.96M - 2.18 -4.39% 159890 14 15 AAON AAON, Inc. Industrials Building Products & Equipment USA 4.22B 62.62 78.65 -1.13% 141623 15 16 AAP Advance Auto Parts, Inc. Consumer Cyclical Specialty Retail USA 9.10B 19.37 150.55 0.67% 1841506 16 17 AAPD Direxion Daily AAPL Bear 1X Shares Financial Exchange Traded Fund USA - - 26.28 -0.46% 59190 17 18 AAPL Apple Inc. Technology Consumer Electronics USA 2394.19B 24.76 151.07 0.59% 58192555 18 19 AAPU Direxion Daily AAPL Bull 1.5X Shares Financial Exchange Traded Fund USA - - 21.22 0.66% 13827 19 20 AAQC Accelerate Acquisition Corp. Financial Shell Companies USA 400.80M - 10.02 -0.05% 68967 20 21 AAT American Assets Trust, Inc. Real Estate REIT - Diversified USA 1.64B 39.89 27.92 -1.38% 233450 21 22 AATC Autoscope Technologies Corporation Technology Scientific & Technical Instruments USA 25.59M 53.47 5.03 0.53% 16509 22 23 AAU Almaden Minerals Ltd. Basic Materials Gold Canada 33.64M - 0.24 3.56% 141687 23 24 AAWW Atlas Air Worldwide Holdings, Inc. Industrials Airports & Air Services USA 2.84B 8.15 100.92 0.13% 168608 24 25 AAXJ iShares MSCI All Country Asia ex Japan ETF Financial Exchange Traded Fund USA - - 63.44 0.87% 431419 25 26 AB AllianceBernstein Holding L.P. Financial Asset Management USA 4.15B 12.08 40.93 -0.58% 336015 26 27 ABB ABB Ltd Industrials Specialty Industrial Machinery Switzerland 61.86B 15.27 31.44 0.93% 1030745 27 28 ABBV AbbVie Inc. Healthcare Drug Manufacturers - General USA 276.75B 21.23 159.39 -0.25% 3218694 28 29 ABC AmerisourceBergen Corporation Healthcare Medical Distribution USA 32.87B 20.59 165.53 0.50% 916086 29 30 ABCB Ameris Bancorp Financial Banks - Regional USA 3.60B 10.57 52.67 -0.53% 175672 30 31 ABCL AbCellera Biologics Inc. Healthcare Biotechnology Canada 3.98B 17.52 14.00 0.14% 1040716 31 32 ABCM Abcam plc Healthcare Biotechnology United Kingdom 3.74B 459.43 16.08 2.10% 177164 32 33 ABEO Abeona Therapeutics Inc. Healthcare Biotechnology USA 66.51M - 3.94 -4.14% 195905 33 34 ABEQ Absolute Select Value ETF Financial Exchange Traded Fund USA - - 28.27 0.42% 11336 34 35 ABEV Ambev S.A. Consumer Defensive Beverages - Brewers Brazil 45.51B 19.21 2.92 1.74% 19875513 35 36 ABG Asbury Automotive Group, Inc. Consumer Cyclical Auto & Truck Dealerships USA 4.05B 5.18 181.90 1.16% 74043 36 37 ABGI ABG Acquisition Corp. I Financial Shell Companies USA 193.49M - 10.01 0.00% 130565 37 38 ABIO ARCA biopharma, Inc. Healthcare Biotechnology USA 29.90M - 2.10 0.96% 8556 38 39 ABM ABM Industries Incorporated Industrials Specialty Business Services USA 2.97B 14.24 45.30 -0.90% 155214 39 40 ABMD Abiomed, Inc. Healthcare Medical Devices USA 17.02B 64.93 377.78 -0.06% 801762 40 41 ABNB Airbnb, Inc. Consumer Cyclical Travel Services USA 62.14B 40.31 96.63 1.42% 4328409 41 42 ABOS Acumen Pharmaceuticals, Inc. Healthcare Biotechnology USA 278.70M - 6.36 0.79% 103296 42 43 ABR Arbor Realty Trust, Inc. Real Estate REIT - Mortgage USA 2.42B 8.77 14.44 -1.37% 1212811 43 44 ABSI Absci Corporation Healthcare Biotechnology USA 221.28M - 2.20 0.00% 136066 44 45 ABST Absolute Software Corporation Technology Software - Application Canada 701.66M - 10.20 4.83% 119574 45 46 ABT Abbott Laboratories Healthcare Medical Devices USA 182.52B 23.81 106.02 1.10% 4617364 46 47 ABUS Arbutus Biopharma Corporation Healthcare Biotechnology USA 416.56M - 2.70 1.50% 635974 47 48 ABVC ABVC BioPharma, Inc. Healthcare Biotechnology USA 24.70M - 0.73 -3.31% 6456 48 49 AC Associated Capital Group, Inc. Financial Capital Markets USA 881.43M - 40.60 -0.85% 591 49 50 ACA Arcosa, Inc. Industrials Infrastructure Operations USA 2.83B 28.62 58.87 -1.31% 160255 50 51 ACAD ACADIA Pharmaceuticals Inc. Healthcare Biotechnology USA 2.40B - 15.00 -0.27% 788928 51 52 ACAQ Athena Consumer Acquisition Corp. Financial Shell Companies USA 328.16M - 10.22 0.20% 1200 52 53 ACB Aurora Cannabis Inc. Healthcare Drug Manufacturers - Specialty & Generic Canada 616.72M - 1.33 1.53% 7895713 53 54 ACCD Accolade, Inc. Healthcare Health Information Services USA 621.64M - 8.61 5.13% 363498 54 55 ACCO ACCO Brands Corporation Industrials Business Equipment & Supplies USA 517.53M 27.54 5.48 0.74% 466342 55 56 ACDC ProFrac Holding Corp. Energy Oil & Gas Equipment & Services USA 3.90B 61.26 24.81 -3.54% 329691 56 57 ACEL Accel Entertainment, Inc. Consumer Cyclical Gambling USA 757.39M 11.83 8.65 -1.37% 132148 57 58 ACER Acer Therapeutics Inc. Healthcare Biotechnology USA 18.35M - 1.17 3.54% 45443 58 59 ACES ALPS Clean Energy ETF Financial Exchange Traded Fund USA - - 55.29 1.52% 14477 59 60 ACET Adicet Bio, Inc. Healthcare Biotechnology USA 713.11M - 17.20 -2.88% 441691 Relevant documentation for packages used: tqdm pandas BeautifulSoup Requests
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 hdr = {'user-agent': 'Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (HTML, like Gecko) Chrome/92.0.4515.107 Mobile Safari/537.36'} for x in range(1,61,20): url = 'https://finviz.com/screener.ashx?v=111&r=' r = requests.get(url+str(x), headers=hdr) soup = BeautifulSoup(r.text, 'lxml') table = soup.find('table', {'class':'table-light'}) headers = [] for i in table.find_all('td')[:11]: title = i.text headers.append(title) df = pd.DataFrame(columns= headers) for row in table.find_all('tr')[1:]: data = row.find_all('td') row_data = [td.text.strip() for td in data] length = len(df) df.loc[length] = row_data df.to_csv('all.csv', index=False, encoding='utf-8') print(df)
[ "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': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/105.0.0.0 Safari/537.36'\n}\n\ns = requests.Session()\ns.headers.update(headers)\n\nbig_df = pd.DataFrame()\n\nfor x in tqdm(range(1, 61, 20)):\n r = s.get(f'https://finviz.com/screener.ashx?v=111&r={x}')\n soup = bs(r.text, 'html.parser')\n df = pd.read_html(str(soup.select_one('table[id=\"screener-views-table\"] table[class=\"table-light\"]')), header=0)[0]\n big_df = pd.concat([big_df, df], axis=0, ignore_index=True)\nprint(big_df)\nbig_df.to_csv('some_fin_data.csv')\n\nResult in terminal:\n100%\n3/3 [00:01<00:00, 2.04it/s]\nNo. Ticker Company Sector Industry Country Market Cap P/E Price Change Volume\n0 1 A Agilent Technologies, Inc. Healthcare Diagnostics & Research USA 45.44B 35.44 155.35 -0.96% 1443781\n1 2 AA Alcoa Corporation Basic Materials Aluminum USA 8.59B - 48.51 -1.72% 3213397\n2 3 AAAU Goldman Sachs Physical Gold ETF Financial Exchange Traded Fund USA - - 17.38 0.64% 2781472\n3 4 AAC Ares Acquisition Corporation Financial Shell Companies USA 1.25B 46.51 10.00 -0.05% 2537\n4 5 AACG ATA Creativity Global Consumer Defensive Education & Training Services China 50.93M - 1.72 2.38% 2302\n5 6 AACI Armada Acquisition Corp. I Financial Shell Companies USA 206.69M - 9.98 -0.05% 91802\n6 7 AACIW Armada Acquisition Corp. I Financial Shell Companies USA - - 0.03 0.00% 0\n7 8 AADI Aadi Bioscience, Inc. Healthcare Biotechnology USA 315.29M - 13.17 -1.86% 45328\n8 9 AADR AdvisorShares Dorsey Wright ADR ETF Financial Exchange Traded Fund USA - - 49.17 0.53% 2232\n9 10 AAIC Arlington Asset Investment Corp. Real Estate REIT - Mortgage USA 88.94M 46.97 3.10 2.99% 122458\n10 11 AAL American Airlines Group Inc. Industrials Airlines USA 9.30B - 14.42 3.15% 23630403\n11 12 AAME Atlantic American Corporation Financial Insurance - Life USA 61.09M 23.65 2.98 4.56% 383\n12 13 AAN The Aaron's Company, Inc. Industrials Rental & Leasing Services USA 346.97M 23.51 11.85 1.37% 507153\n13 14 AAOI Applied Optoelectronics, Inc. Technology Semiconductors USA 63.96M - 2.18 -4.39% 159890\n14 15 AAON AAON, Inc. Industrials Building Products & Equipment USA 4.22B 62.62 78.65 -1.13% 141623\n15 16 AAP Advance Auto Parts, Inc. Consumer Cyclical Specialty Retail USA 9.10B 19.37 150.55 0.67% 1841506\n16 17 AAPD Direxion Daily AAPL Bear 1X Shares Financial Exchange Traded Fund USA - - 26.28 -0.46% 59190\n17 18 AAPL Apple Inc. Technology Consumer Electronics USA 2394.19B 24.76 151.07 0.59% 58192555\n18 19 AAPU Direxion Daily AAPL Bull 1.5X Shares Financial Exchange Traded Fund USA - - 21.22 0.66% 13827\n19 20 AAQC Accelerate Acquisition Corp. Financial Shell Companies USA 400.80M - 10.02 -0.05% 68967\n20 21 AAT American Assets Trust, Inc. Real Estate REIT - Diversified USA 1.64B 39.89 27.92 -1.38% 233450\n21 22 AATC Autoscope Technologies Corporation Technology Scientific & Technical Instruments USA 25.59M 53.47 5.03 0.53% 16509\n22 23 AAU Almaden Minerals Ltd. Basic Materials Gold Canada 33.64M - 0.24 3.56% 141687\n23 24 AAWW Atlas Air Worldwide Holdings, Inc. Industrials Airports & Air Services USA 2.84B 8.15 100.92 0.13% 168608\n24 25 AAXJ iShares MSCI All Country Asia ex Japan ETF Financial Exchange Traded Fund USA - - 63.44 0.87% 431419\n25 26 AB AllianceBernstein Holding L.P. Financial Asset Management USA 4.15B 12.08 40.93 -0.58% 336015\n26 27 ABB ABB Ltd Industrials Specialty Industrial Machinery Switzerland 61.86B 15.27 31.44 0.93% 1030745\n27 28 ABBV AbbVie Inc. Healthcare Drug Manufacturers - General USA 276.75B 21.23 159.39 -0.25% 3218694\n28 29 ABC AmerisourceBergen Corporation Healthcare Medical Distribution USA 32.87B 20.59 165.53 0.50% 916086\n29 30 ABCB Ameris Bancorp Financial Banks - Regional USA 3.60B 10.57 52.67 -0.53% 175672\n30 31 ABCL AbCellera Biologics Inc. Healthcare Biotechnology Canada 3.98B 17.52 14.00 0.14% 1040716\n31 32 ABCM Abcam plc Healthcare Biotechnology United Kingdom 3.74B 459.43 16.08 2.10% 177164\n32 33 ABEO Abeona Therapeutics Inc. Healthcare Biotechnology USA 66.51M - 3.94 -4.14% 195905\n33 34 ABEQ Absolute Select Value ETF Financial Exchange Traded Fund USA - - 28.27 0.42% 11336\n34 35 ABEV Ambev S.A. Consumer Defensive Beverages - Brewers Brazil 45.51B 19.21 2.92 1.74% 19875513\n35 36 ABG Asbury Automotive Group, Inc. Consumer Cyclical Auto & Truck Dealerships USA 4.05B 5.18 181.90 1.16% 74043\n36 37 ABGI ABG Acquisition Corp. I Financial Shell Companies USA 193.49M - 10.01 0.00% 130565\n37 38 ABIO ARCA biopharma, Inc. Healthcare Biotechnology USA 29.90M - 2.10 0.96% 8556\n38 39 ABM ABM Industries Incorporated Industrials Specialty Business Services USA 2.97B 14.24 45.30 -0.90% 155214\n39 40 ABMD Abiomed, Inc. Healthcare Medical Devices USA 17.02B 64.93 377.78 -0.06% 801762\n40 41 ABNB Airbnb, Inc. Consumer Cyclical Travel Services USA 62.14B 40.31 96.63 1.42% 4328409\n41 42 ABOS Acumen Pharmaceuticals, Inc. Healthcare Biotechnology USA 278.70M - 6.36 0.79% 103296\n42 43 ABR Arbor Realty Trust, Inc. Real Estate REIT - Mortgage USA 2.42B 8.77 14.44 -1.37% 1212811\n43 44 ABSI Absci Corporation Healthcare Biotechnology USA 221.28M - 2.20 0.00% 136066\n44 45 ABST Absolute Software Corporation Technology Software - Application Canada 701.66M - 10.20 4.83% 119574\n45 46 ABT Abbott Laboratories Healthcare Medical Devices USA 182.52B 23.81 106.02 1.10% 4617364\n46 47 ABUS Arbutus Biopharma Corporation Healthcare Biotechnology USA 416.56M - 2.70 1.50% 635974\n47 48 ABVC ABVC BioPharma, Inc. Healthcare Biotechnology USA 24.70M - 0.73 -3.31% 6456\n48 49 AC Associated Capital Group, Inc. Financial Capital Markets USA 881.43M - 40.60 -0.85% 591\n49 50 ACA Arcosa, Inc. Industrials Infrastructure Operations USA 2.83B 28.62 58.87 -1.31% 160255\n50 51 ACAD ACADIA Pharmaceuticals Inc. Healthcare Biotechnology USA 2.40B - 15.00 -0.27% 788928\n51 52 ACAQ Athena Consumer Acquisition Corp. Financial Shell Companies USA 328.16M - 10.22 0.20% 1200\n52 53 ACB Aurora Cannabis Inc. Healthcare Drug Manufacturers - Specialty & Generic Canada 616.72M - 1.33 1.53% 7895713\n53 54 ACCD Accolade, Inc. Healthcare Health Information Services USA 621.64M - 8.61 5.13% 363498\n54 55 ACCO ACCO Brands Corporation Industrials Business Equipment & Supplies USA 517.53M 27.54 5.48 0.74% 466342\n55 56 ACDC ProFrac Holding Corp. Energy Oil & Gas Equipment & Services USA 3.90B 61.26 24.81 -3.54% 329691\n56 57 ACEL Accel Entertainment, Inc. Consumer Cyclical Gambling USA 757.39M 11.83 8.65 -1.37% 132148\n57 58 ACER Acer Therapeutics Inc. Healthcare Biotechnology USA 18.35M - 1.17 3.54% 45443\n58 59 ACES ALPS Clean Energy ETF Financial Exchange Traded Fund USA - - 55.29 1.52% 14477\n59 60 ACET Adicet Bio, Inc. Healthcare Biotechnology USA 713.11M - 17.20 -2.88% 441691\n\nRelevant documentation for packages used:\n\ntqdm\npandas\nBeautifulSoup\nRequests\n\n" ]
[ 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 lol I got the lib and started to mess around with the code a bit and I got it to measure the time for an operation: import timeit start = timeit.timeit() print("") end = timeit.timeit() print(end - start) A: You can use the datetime module for this. from datetime import datetime clocked_in = "21/11/22 3:10:52" clocked_out = "21/11/22 10:30:33" #changing to datetime t1 = datetime.strptime(clocked_in, "%d/%m/%y %H:%M:%S") t2 = datetime.strptime(clocked_out, "%d/%m/%y %H:%M:%S") #calculating the time difference time_difference = t2 - t1 print('Time between clocked in and out is:', time_difference) #output: Time between clocked in and out is: 7:19:41
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 I got it to measure the time for an operation: import timeit start = timeit.timeit() print("") end = timeit.timeit() print(end - start)
[ "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 difference\ntime_difference = t2 - t1\nprint('Time between clocked in and out is:', time_difference)\n\n#output: Time between clocked in and out is: 7:19:41\n\n" ]
[ 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 85030 333 20209 58014 79999 85360= 202211061800 AAXX 06184 65528 11458 61404 10237 20214 39640 40108 69902 70296 83970 333 10326 58015 83815 81920 86360= SYNOPS from 65536, Korhogo (Cote d'Ivoire) 202211070600 AAXX 07064 65536 42960 23402 10204 20204 39708 40122 80002 333 20203 58002 79999 82076= 202211061800 AAXX 06184 65536 11458 70402 10268 20204 39688 40095 69902 70162 83932 333 10340 58008 82613 82920 87076= SYNOPS from 65545, Bondoukou (Cote d'Ivoire) 202211070600 AAXX 07064 65545 32958 ///// 10215 20206 39706 40124 80002 333 20212 59001 85076= 202211061800 AAXX 06184 65545 32958 ///// 10260 20213 39696 40107 80072 333 10325 58015 83360 88076= SYNOPS from 65548, Man (Cote d'Ivoire) 202211070600 AAXX 07064 65548 42458 70000 10215 20215 39753 40121 86530 333 20215 59001 70140 86613= 202211061800 AAXX 06184 65548 31458 60000 10285 20234 39738 40097 71799 84933 333 10313 58011 84813 81913= SYNOPS from 65555, Bouake (Cote d'Ivoire) 202211070600 AAXX 07064 65555 11440 32002 10210 20210 39698 40125 60084 71011 83502 333 20208 58003 83610= 202211061800 AAXX 06184 65555 11458 71402 10247 20237 39688 40109 60082 70196 8297/ 333 10315 58013 82813 81920 87360= SYNOPS from 65557, Gagnoa (Cote d'Ivoire) 202211070600 AAXX 07064 65557 41458 41602 10211 20208 39881 40115 70296 84500 333 20211 59004 70250 84613= 202211061800 AAXX 06184 65557 13460 62204 10276 20234 39866 40094 69902 333 10320 58007 86613 81920= SYNOPS from 65560, Daloa (Cote d'Ivoire) 202211070600 AAXX 07064 65560 32460 ///// 10220 20213 39811 40124 81572 333 20220 58002 81613 84360= 202211061800 AAXX 06184 65560 32460 ///// 10285 20219 39794 40100 83902 333 10324 58012 83815 81920 85076= SYNOPS from 65562, Dimbokro (Cote d'Ivoire) 202211070600 AAXX 07064 65562 41209 60802 10230 20229 30017 40143 74442 86500 333 20222 58003 70090 83705 84613= 202211061800 AAXX 06184 65562 32460 53102 10305 20256 30003 40126 85900 333 10340 58016 85815 81920= SYNOPS from 65563, Yamoussoukro (Cote d'Ivoire) 202211070600 AAXX 07064 65563 42956 30000 10208 20206 39882 40115 80001 333 20202 58004 70040 83076= 202211061800 AAXX 06184 65563 11458 70000 10234 20229 39868 40099 60042 79596 85903 333 10331 58014 85810 81920 87076= SYNOPS from 65578, Abidjan (Cote d'Ivoire) 202211070600 AAXX 07064 65578 41358 60404 10245 20245 30112 40120 70362 83530 333 20244 58000 70010 81707 83620 86360= 202211061800 AAXX 06184 65578 32460 62006 10285 20254 30104 40112 85932 333 10297 58011 81917 85620 85075= SYNOPS from 65585, Adiake (Cote d'Ivoire) 202211070600 AAXX 07064 65585 42458 ///// 10236 20232 30079 40117 82202 333 20232 58002 70080 82813 83076= 202211061800 AAXX 06184 65585 11460 ///// 10280 20247 30070 40108 60082 70262 85270 333 10315 58008 85813= SYNOPS from 65592, Tabou (Cote d'Ivoire) 202211070600 AAXX 07064 65592 41458 71804 10239 20236 30097 40119 76266 8527/ 333 20239 58003 70150 85813 87360= 202211061800 AAXX 06184 65592 12460 71804 10276 20242 30083 40105 60052 83902 333 10300 58004 83813 81920 87076= SYNOPS from 65594, San Pedro (Cote d'Ivoire) 202211070600 AAXX 07064 65594 42458 43604 10221 20221 30086 40120 82202 333 20220 58002 70100 82813 84080= 202211061800 AAXX 06184 65594 11458 53602 10271 20259 30071 40104 60102 70296 83202 333 10290 58002 83813 85080= SYNOPS from 65599, Sassandra (Cote d'Ivoire) 202211070600 AAXX 07064 65599 41456 53202 10228 20224 30043 40118 70196 84202 333 20224 58000 70030 84813 84076= 202211061800 AAXX 06184 65599 31460 61802 10280 20252 30031 40104 70392 85902 333 10298 58001 85815 81920 84076= A: 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: csvRows = [] for pCont in soup.find_all('pre'): csvRows += [( ('[About Query]', '\n'.join([ ql[1:].strip() for ql in pb.split('\n')[2:5] ])) if pi == 0 else tuple(pb.split(f"\n{'#'*80}\n")[:2]) ) for pi, pb in enumerate(pCont.get_text().split(f"{'#'*80}\n# "))] pandas.DataFrame(csvRows, columns=[ 'Result Header', 'Result Lines' ]).to_csv('Cotey_synopsc.csv', index=False) would result in a file that looks like this. Although, I think it would be better [visually] to split it up a bit more - something like aboutQuery, qresBlocks, bHeads = [], [], [] for pci, pCont in enumerate(soup.find_all('pre')): pBlocks = pCont.get_text().split(f"{'#'*80}\n# ") aboutQuery.append({k: v for v, k in zip([pci]+[ ql[1:].strip() for ql in pBlocks[0].split('\n')[2:5] ], ['qIndex', 'Query Time', 'Query', 'Query Inerval'])}) for pbi, pb in enumerate(pBlocks[1:]): if f"\n{'#'*80}\n" not in pb: continue # unknown format bhead, blines = pb.split(f"\n{'#'*80}\n")[:2] bhead = bhead.strip().split(' | ') bHeads.append({k: v for k, v in [ ('qIndex', pci), ('bIndex', pbi), ('from', bhead[0]), ('N', ''.join(bhead[1:2])), ('W', ''.join(bhead[2:3])), ('m', ''.join(bhead[3:4])), ('extra', ' | '.join(bhead[4:])) ] if v != ''}) for bl in blines.split('=\n')[:-1]: line1 = bl.split('\n')[0].strip() ldate = line1.split(' ')[0] line1 = line1.replace(ldate, '', 1) line2 = '\n'.join([l.strip() for l in bl.split('\n')[1:]]) if line2 == '' and line1.endswith(' NIL'): line1, line2 = line1[:-4], 'NIL' qresBlocks.append({ 'qIndex': pci, 'bIndex': pbi, 'date?': ldate, 'firstLine': line1, 'lastLine(/s)': f'{line2}=' }) listsByName = [ ('About Query', aboutQuery), ('Result Blocks - Headers', bHeads), ('Result Blocks - Lines', qresBlocks) ] You can save to separate CSVs with for name, nList in listsByName: pandas.DataFrame(nList).to_csv(f'{name}.csv', index=False) or to separate sheets of a single Excel file with with pandas.ExcelWriter('Cote_synopsc.xlsx') as w: for name, nList in listsByName: pandas.DataFrame(nList).to_excel(w, name, index=False) The outputs look like: "About Query" "Result Blocks - Headers" "Result Blocks - Lines"
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 61404 10237 20214 39640 40108 69902 70296 83970 333 10326 58015 83815 81920 86360= SYNOPS from 65536, Korhogo (Cote d'Ivoire) 202211070600 AAXX 07064 65536 42960 23402 10204 20204 39708 40122 80002 333 20203 58002 79999 82076= 202211061800 AAXX 06184 65536 11458 70402 10268 20204 39688 40095 69902 70162 83932 333 10340 58008 82613 82920 87076= SYNOPS from 65545, Bondoukou (Cote d'Ivoire) 202211070600 AAXX 07064 65545 32958 ///// 10215 20206 39706 40124 80002 333 20212 59001 85076= 202211061800 AAXX 06184 65545 32958 ///// 10260 20213 39696 40107 80072 333 10325 58015 83360 88076= SYNOPS from 65548, Man (Cote d'Ivoire) 202211070600 AAXX 07064 65548 42458 70000 10215 20215 39753 40121 86530 333 20215 59001 70140 86613= 202211061800 AAXX 06184 65548 31458 60000 10285 20234 39738 40097 71799 84933 333 10313 58011 84813 81913= SYNOPS from 65555, Bouake (Cote d'Ivoire) 202211070600 AAXX 07064 65555 11440 32002 10210 20210 39698 40125 60084 71011 83502 333 20208 58003 83610= 202211061800 AAXX 06184 65555 11458 71402 10247 20237 39688 40109 60082 70196 8297/ 333 10315 58013 82813 81920 87360= SYNOPS from 65557, Gagnoa (Cote d'Ivoire) 202211070600 AAXX 07064 65557 41458 41602 10211 20208 39881 40115 70296 84500 333 20211 59004 70250 84613= 202211061800 AAXX 06184 65557 13460 62204 10276 20234 39866 40094 69902 333 10320 58007 86613 81920= SYNOPS from 65560, Daloa (Cote d'Ivoire) 202211070600 AAXX 07064 65560 32460 ///// 10220 20213 39811 40124 81572 333 20220 58002 81613 84360= 202211061800 AAXX 06184 65560 32460 ///// 10285 20219 39794 40100 83902 333 10324 58012 83815 81920 85076= SYNOPS from 65562, Dimbokro (Cote d'Ivoire) 202211070600 AAXX 07064 65562 41209 60802 10230 20229 30017 40143 74442 86500 333 20222 58003 70090 83705 84613= 202211061800 AAXX 06184 65562 32460 53102 10305 20256 30003 40126 85900 333 10340 58016 85815 81920= SYNOPS from 65563, Yamoussoukro (Cote d'Ivoire) 202211070600 AAXX 07064 65563 42956 30000 10208 20206 39882 40115 80001 333 20202 58004 70040 83076= 202211061800 AAXX 06184 65563 11458 70000 10234 20229 39868 40099 60042 79596 85903 333 10331 58014 85810 81920 87076= SYNOPS from 65578, Abidjan (Cote d'Ivoire) 202211070600 AAXX 07064 65578 41358 60404 10245 20245 30112 40120 70362 83530 333 20244 58000 70010 81707 83620 86360= 202211061800 AAXX 06184 65578 32460 62006 10285 20254 30104 40112 85932 333 10297 58011 81917 85620 85075= SYNOPS from 65585, Adiake (Cote d'Ivoire) 202211070600 AAXX 07064 65585 42458 ///// 10236 20232 30079 40117 82202 333 20232 58002 70080 82813 83076= 202211061800 AAXX 06184 65585 11460 ///// 10280 20247 30070 40108 60082 70262 85270 333 10315 58008 85813= SYNOPS from 65592, Tabou (Cote d'Ivoire) 202211070600 AAXX 07064 65592 41458 71804 10239 20236 30097 40119 76266 8527/ 333 20239 58003 70150 85813 87360= 202211061800 AAXX 06184 65592 12460 71804 10276 20242 30083 40105 60052 83902 333 10300 58004 83813 81920 87076= SYNOPS from 65594, San Pedro (Cote d'Ivoire) 202211070600 AAXX 07064 65594 42458 43604 10221 20221 30086 40120 82202 333 20220 58002 70100 82813 84080= 202211061800 AAXX 06184 65594 11458 53602 10271 20259 30071 40104 60102 70296 83202 333 10290 58002 83813 85080= SYNOPS from 65599, Sassandra (Cote d'Ivoire) 202211070600 AAXX 07064 65599 41456 53202 10228 20224 30043 40118 70196 84202 333 20224 58000 70030 84813 84076= 202211061800 AAXX 06184 65599 31460 61802 10280 20252 30031 40104 70392 85902 333 10298 58001 85815 81920 84076=
[ "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('\\n')[2:5]\n ])) if pi == 0 else tuple(pb.split(f\"\\n{'#'*80}\\n\")[:2]) \n ) for pi, pb in enumerate(pCont.get_text().split(f\"{'#'*80}\\n# \"))]\npandas.DataFrame(csvRows, columns=[\n 'Result Header', 'Result Lines'\n]).to_csv('Cotey_synopsc.csv', index=False)\n\nwould result in a file that looks like this.\n\n\nAlthough, I think it would be better [visually] to split it up a bit more - something like\naboutQuery, qresBlocks, bHeads = [], [], []\nfor pci, pCont in enumerate(soup.find_all('pre')):\n pBlocks = pCont.get_text().split(f\"{'#'*80}\\n# \")\n\n aboutQuery.append({k: v for v, k in zip([pci]+[\n ql[1:].strip() for ql in pBlocks[0].split('\\n')[2:5]\n ], ['qIndex', 'Query Time', 'Query', 'Query Inerval'])})\n\n for pbi, pb in enumerate(pBlocks[1:]):\n if f\"\\n{'#'*80}\\n\" not in pb: continue # unknown format\n bhead, blines = pb.split(f\"\\n{'#'*80}\\n\")[:2]\n bhead = bhead.strip().split(' | ')\n bHeads.append({k: v for k, v in [\n ('qIndex', pci), ('bIndex', pbi), ('from', bhead[0]), \n ('N', ''.join(bhead[1:2])), ('W', ''.join(bhead[2:3])),\n ('m', ''.join(bhead[3:4])), ('extra', ' | '.join(bhead[4:]))\n ] if v != ''})\n for bl in blines.split('=\\n')[:-1]:\n line1 = bl.split('\\n')[0].strip()\n ldate = line1.split(' ')[0]\n line1 = line1.replace(ldate, '', 1)\n line2 = '\\n'.join([l.strip() for l in bl.split('\\n')[1:]])\n if line2 == '' and line1.endswith(' NIL'):\n line1, line2 = line1[:-4], 'NIL'\n qresBlocks.append({\n 'qIndex': pci, 'bIndex': pbi, 'date?': ldate,\n 'firstLine': line1, 'lastLine(/s)': f'{line2}='\n })\n\nlistsByName = [\n ('About Query', aboutQuery), \n ('Result Blocks - Headers', bHeads), \n ('Result Blocks - Lines', qresBlocks)\n]\n\n\nYou can save to separate CSVs with\nfor name, nList in listsByName:\n pandas.DataFrame(nList).to_csv(f'{name}.csv', index=False)\n\n\nor to separate sheets of a single Excel file with\nwith pandas.ExcelWriter('Cote_synopsc.xlsx') as w:\n for name, nList in listsByName:\n pandas.DataFrame(nList).to_excel(w, name, index=False)\n\n\nThe outputs look like: \"About Query\" \"Result Blocks - Headers\" \"Result Blocks - Lines\"\n" ]
[ 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 tried this code. import pickle as pkl import tarfile t = tarfile.open('model.tar.gz', 'r:gz') t.extractall() model = pkl.load('xgboost-model', 'rb') But it's only giving me this error XGBoostError: [13:32:18] /opt/concourse/worker/volumes/live/7a2b9f41-3287-451b-6691-43e9a6c0910f/volume/xgboost-split_1619728204606/work/src/learner.cc:922: Check failed: header == serialisation_header_: If you are loading a serialized model (like pickle in Python) generated by older XGBoost, please export the model by calling `Booster.save_model` from that version first, then load it back in current version. There's a simple script for helping the process. So I tried using the Booster.save_model function at sagemaker notebook but it doesnt work nor does pickling the trained model work. I also tried this code model = xgb.Booster() model.load_model('xgboost-model') but it's giving me this error XGBoostError: std::bad_alloc Any help would be greatly appreciated. A: 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. That said I was able to run my code below by downgrading the XGBoost library on my environment from 1.7 to 0.9 and it works like a charm. t = tarfile.open('model.tar.gz', 'r:gz') t.extractall() model = pkl.load('xgboost-model', 'rb')
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 = tarfile.open('model.tar.gz', 'r:gz') t.extractall() model = pkl.load('xgboost-model', 'rb') But it's only giving me this error XGBoostError: [13:32:18] /opt/concourse/worker/volumes/live/7a2b9f41-3287-451b-6691-43e9a6c0910f/volume/xgboost-split_1619728204606/work/src/learner.cc:922: Check failed: header == serialisation_header_: If you are loading a serialized model (like pickle in Python) generated by older XGBoost, please export the model by calling `Booster.save_model` from that version first, then load it back in current version. There's a simple script for helping the process. So I tried using the Booster.save_model function at sagemaker notebook but it doesnt work nor does pickling the trained model work. I also tried this code model = xgb.Booster() model.load_model('xgboost-model') but it's giving me this error XGBoostError: std::bad_alloc Any help would be greatly appreciated.
[ "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 my environment from 1.7 to 0.9 and it works like a charm.\nt = tarfile.open('model.tar.gz', 'r:gz')\nt.extractall()\nmodel = pkl.load('xgboost-model', 'rb')\n\n" ]
[ 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_files li = [] for filename in all_files: df=pd.read_csv(filename,index_col=None,header=None) li.append(df) However, will there be multiple headers after appending the list of dfs into one? If so, How to keep only the first header and remove the rest? A: Use pd.concat() For more info you can refer https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.concat.html A: You can simply concat in loop itself. Let's assume csv1 looks like. Ref tim 0 1 mow 1 2 pak 2 3 bow 3 4 tring Let's assume csv2 looks like. Ref tim 0 1 mow 1 2 pak 2 3 bow 3 4 tring Read files uisng glob and concat at once as follows. path =r"..." all_files=glob.glob(path) df = (pd.read_csv(each) for each in all_files) df= pd.concat(df, ignore_index=True) print(df) Gives # Ref tim 0 1 mow 1 2 pak 2 3 bow 3 4 tring 4 1 mow 5 2 pak 6 3 bow 7 4 tring
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.append(df) However, will there be multiple headers after appending the list of dfs into one? If so, How to keep only the first header and remove the rest?
[ "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 Ref tim\n0 1 mow\n1 2 pak\n2 3 bow\n3 4 tring\n\nRead files uisng glob and concat at once as follows.\npath =r\"...\"\nall_files=glob.glob(path)\ndf = (pd.read_csv(each) for each in all_files)\ndf= pd.concat(df, ignore_index=True)\nprint(df)\n\nGives #\n Ref tim\n0 1 mow\n1 2 pak\n2 3 bow\n3 4 tring\n4 1 mow\n5 2 pak\n6 3 bow\n7 4 tring\n\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(input()) number_of_guesses += 1` if guess < number: print('Your guess is too low') if guess > number: print('Your guess is too high') if guess == number: break if guess == number: print('You guessed the number in ' + str(number_of_guesses) + ' tries!') else: print('You did not guess the number, The number was ' + str(number)) Above is the normal Python Numberguessing game code. But I want to make a quiz game using variables or lists without input. Like using input import random number = random.randint(1, 10) list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] number_of_guesses = 0 print(' I am Guessing a number between 1 and 10:') while number_of_guesses < 3: number_of_guesses += 1 if list < number: print('Your guess is too low') if list > number: print('Your guess is too high') if list == number: break if list == number: print('축하합니다! 당신은 {}번의 시도만에 정답을 맞췄습니다.!'.format(number_of_guesses)) else: print('아쉽지만 정답을 맞추지 못했네요. 정답은 {} 이었습니다. 다시 도전해보세요!'.format(number)) I tried to make it using a list or variable, but I failed. Help me please.** A: See my code . Code-: import random lis=[1, 2, 3, 4, 5, 8, 9, 10] print('I am Guessing a number between 1 and 10:\n') for number in lis: number_of_guesses = 0 while number_of_guesses<3: guess_number=random.randint(1,10) if number<guess_number: number_of_guesses+=1 print('Your guess number is high '+str(guess_number)) elif number>guess_number: number_of_guesses+=1 print('Your guess number is low '+str(guess_number)) else: print("You guess Right The number is: "+str(guess_number)+"\nNumber of guess taken "+str(number_of_guesses+1)) break if number_of_guesses==3: print("Sorry your chances of guessing is over! You can not guess the number correct") Output:- I am Guessing a number between 1 and 10: Your guess number is high 5 Your guess number is high 10 Your guess number is high 9 Sorry your chances of guessing is over! You can not guess the number correct Your guess number is high 4 Your guess number is high 7 Your guess number is high 3 Sorry your chances of guessing is over! You can not guess the number correct Your guess number is high 5 Your guess number is high 5 Your guess number is high 10 Sorry your chances of guessing is over! You can not guess the number correct Your guess number is high 5 Your guess number is high 8 Your guess number is high 6 Sorry your chances of guessing is over! You can not guess the number correct Your guess number is high 7 Your guess number is low 1 You guess Right The number is: 5 Number of guess taken 3 Your guess number is low 5 Your guess number is high 9 Your guess number is low 3 Sorry your chances of guessing is over! You can not guess the number correct Your guess number is high 10 Your guess number is low 3 Your guess number is low 5 Sorry your chances of guessing is over! You can not guess the number correct Your guess number is low 6 Your guess number is low 5 Your guess number is low 7 Sorry your chances of guessing is over! You can not guess the number Please give the feedback if this helps to you..!
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 guess is too low') if guess > number: print('Your guess is too high') if guess == number: break if guess == number: print('You guessed the number in ' + str(number_of_guesses) + ' tries!') else: print('You did not guess the number, The number was ' + str(number)) Above is the normal Python Numberguessing game code. But I want to make a quiz game using variables or lists without input. Like using input import random number = random.randint(1, 10) list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] number_of_guesses = 0 print(' I am Guessing a number between 1 and 10:') while number_of_guesses < 3: number_of_guesses += 1 if list < number: print('Your guess is too low') if list > number: print('Your guess is too high') if list == number: break if list == number: print('축하합니다! 당신은 {}번의 시도만에 정답을 맞췄습니다.!'.format(number_of_guesses)) else: print('아쉽지만 정답을 맞추지 못했네요. 정답은 {} 이었습니다. 다시 도전해보세요!'.format(number)) I tried to make it using a list or variable, but I failed. Help me please.**
[ "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 print('Your guess number is high '+str(guess_number))\n elif number>guess_number:\n number_of_guesses+=1\n print('Your guess number is low '+str(guess_number))\n else:\n print(\"You guess Right The number is: \"+str(guess_number)+\"\\nNumber of guess taken \"+str(number_of_guesses+1))\n break\n if number_of_guesses==3:\n print(\"Sorry your chances of guessing is over! You can not guess the number correct\")\n\nOutput:-\nI am Guessing a number between 1 and 10:\n\nYour guess number is high 5\nYour guess number is high 10\nYour guess number is high 9\nSorry your chances of guessing is over! You can not guess the number correct\nYour guess number is high 4\nYour guess number is high 7\nYour guess number is high 3\nSorry your chances of guessing is over! You can not guess the number correct\nYour guess number is high 5\nYour guess number is high 5\nYour guess number is high 10\nSorry your chances of guessing is over! You can not guess the number correct\nYour guess number is high 5\nYour guess number is high 8\nYour guess number is high 6\nSorry your chances of guessing is over! You can not guess the number correct\nYour guess number is high 7\nYour guess number is low 1\nYou guess Right The number is: 5\nNumber of guess taken 3\nYour guess number is low 5\nYour guess number is high 9\nYour guess number is low 3\nSorry your chances of guessing is over! You can not guess the number correct\nYour guess number is high 10\nYour guess number is low 3\nYour guess number is low 5\nSorry your chances of guessing is over! You can not guess the number correct\nYour guess number is low 6\nYour guess number is low 5\nYour guess number is low 7\nSorry your chances of guessing is over! You can not guess the number\n\nPlease give the feedback if this helps to you..!\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, *args, **kwargs): # <<< post is working items = get_object_or_404(Item, id=self.kwargs.get('pk')) if items.discount_price < items.price: ncart = CartItem.objects.create(user=request.user, product=items) ncart.total = ncart.quantity * items.discount_price ncart.save() else: ncart = CartItem.objects.create(user=request.user, product=items) ncart.total = ncart.quantity * items.price ncart.save() data = json.dumps(ncart, default=str, indent=1) return Response({'msg': 'Product Added to Cart Successfully'}, status=status.HTTP_200_OK) Actually I tried post with model-view-set with function perform create but its not working, so I just changed name performcreate > post. this is working any one let me know how it is possible, model viewset allows ModelViewSet get_queryset (list retrieve create perform_create update perform_update destroy)this method right , then why? A: Everything is correct just rename your post method with create mentioned below def create(self, request, *args, **kwargs): # <<< post is working
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_object_or_404(Item, id=self.kwargs.get('pk')) if items.discount_price < items.price: ncart = CartItem.objects.create(user=request.user, product=items) ncart.total = ncart.quantity * items.discount_price ncart.save() else: ncart = CartItem.objects.create(user=request.user, product=items) ncart.total = ncart.quantity * items.price ncart.save() data = json.dumps(ncart, default=str, indent=1) return Response({'msg': 'Product Added to Cart Successfully'}, status=status.HTTP_200_OK) Actually I tried post with model-view-set with function perform create but its not working, so I just changed name performcreate > post. this is working any one let me know how it is possible, model viewset allows ModelViewSet get_queryset (list retrieve create perform_create update perform_update destroy)this method right , then why?
[ "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 sometime. I tried using multiple service provider internet that has different ip and stil facing the same issue ? I also tried to use googletrans on different laptops , still same issue ..Is googletrans package broken or something google did at their end ? >>> from googletrans import Translator >>> translator = Translator() >>> translator.translate('안녕하세요.') Traceback (most recent call last): File "<pyshell#2>", line 1, in <module> translator.translate('안녕하세요.') File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/googletrans/client.py", line 172, in translate data = self._translate(text, dest, src) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/googletrans/client.py", line 75, in _translate token = self.token_acquirer.do(text) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/googletrans/gtoken.py", line 180, in do self._update() File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/googletrans/gtoken.py", line 59, in _update code = unicode(self.RE_TKK.search(r.text).group(1)).replace('var ', '') AttributeError: 'NoneType' object has no attribute 'group' A: Update 06.12.20: A new 'official' alpha version of googletrans with a fix was released Install the alpha version like this: pip install googletrans==3.1.0a0 Translation example: translator = Translator() translation = translator.translate("Der Himmel ist blau und ich mag Bananen", dest='en') print(translation.text) #output: 'The sky is blue and I like bananas' In case it does not work, try to specify the service url like this: from googletrans import Translator translator = Translator(service_urls=['translate.googleapis.com']) translator.translate("Der Himmel ist blau und ich mag Bananen", dest='en') See the discussion here for details and updates: https://github.com/ssut/py-googletrans/pull/237 Update 10.12.20: Another fix was released As pointed out by @DesiKeki and @Ahmed Breem, there is another fix which seems to work for several people: pip install googletrans==4.0.0-rc1 Github discussion here: https://github.com/ssut/py-googletrans/issues/234#issuecomment-742460612 In case the fixes above don't work for you If the above doesn't work for you, google_trans_new seems to be a good alternative that works for some people. It's unclear why the fix above works for some and doesn't for others. See details on installation and usage here: https://github.com/lushan88a/google_trans_new #pip install google_trans_new from google_trans_new import google_translator translator = google_translator() translate_text = translator.translate('สวัสดีจีน',lang_tgt='en') print(translate_text) #output: Hello china A: Update 01/12/2020: This issue re-emerged lately, (apparently) caused once again by some changes on the Google translation API. A solution is being discussed (again) in this Github issue. Although there is not a definitive solution yet a Pull Request seem to be solving the problem: https://github.com/ssut/py-googletrans/pull/237. While we wait for it to be approved it can be installed like this: $ pip uninstall googletrans $ git clone https://github.com/alainrouillon/py-googletrans.git $ cd ./py-googletrans $ git checkout origin/feature/enhance-use-of-direct-api $ python setup.py install Original Answer: Apparently it's a recent and widespread problem on Google's side. Quoting various Github discussions, it happens when Google sends you directly the raw token. It's being discussed right now and there is already a pull request to fix it, so it should be resolved in the next few days. For reference, see: https://github.com/ssut/py-googletrans/issues/48 <-- exact same problem reported on the Github repo https://github.com/pndurette/gTTS/issues/60 <-- seemingly same problem on a text-to-speech library https://github.com/ssut/py-googletrans/pull/78 <-- pull request to fix the issue To apply this patch (without waiting for the pull request to be accepted) simply install the library from the forked repo https://github.com/BoseCorp/py-googletrans.git (uninstall the official library first): $ pip uninstall googletrans $ git clone https://github.com/BoseCorp/py-googletrans.git $ cd ./py-googletrans $ python setup.py install You can clone it anywhere on your system and install it globally or while inside a virtualenv. A: Try google_trans_new. It solved the problem for me https://github.com/lushan88a/google_trans_new pip install google_trans_new from google_trans_new import google_translator translator = google_translator() translate_text = translator.translate('Hola mundo!', lang_src='es', lang_tgt='en') print(translate_text) -> Hello world! A: Updated Answer as of 2021 Sept pip uninstall googletrans==4.0.0-rc1 pip install googletrans==3.1.0a0 The 3.1.0a0 version works with bulk translation too! A: Update 10.12.20: New Alpha Version Release (Stable Release Candidate) is released: 4.0.0-rc1 It can be installed as follows: pip install googletrans==4.0.0-rc1 Usage: translation = translator.translate('이 문장은 한글로 쓰여졌습니다.', dest='en') print(translation.text) >>This sentence is written in Korean. detected_lang = translator.detect('mein english me hindi likh raha hoon') print(detected_lang) >>Detected(lang=hi, confidence=None) detected_lang = translator.detect('이 문장은 한글로 쓰여졌습니다.') print(detected_lang) >>Detected(lang=ko, confidence=None) A: Unfortunately, I could get neither googletrans nor google_trans_new to work, despite the many proposed fixes that are around. My solution was to switch to the deep_translator package: pip install -U deep-translator Then you can use it like this: >>> from deep_translator import GoogleTranslator >>> GoogleTranslator(source='auto', target='de').translate("keep it up, you are awesome") 'weiter so, du bist toll' See documentation for more info. A: By the time of this answer, you can solve it with the following: Uninstall your installed version of pip uninstall googletrans Install the following version pip install googletrans==4.0.0rc1 I hope this will works for you as it worked for me. You can try it now: from googletrans import Translator translator = Translator() ar = translator.translate('مرحبا').text print(ar) A: Here is an unofficial fix to this problem as Darkblader24 stated in: https://github.com/ssut/py-googletrans/pull/78 Update gtoken.py like this: RE_TKK = re.compile(r'TKK=eval\(\'\(\(function\(\)\{(.+?)\}\)\(\)\)\'\);', re.DOTALL) RE_RAWTKK = re.compile(r'TKK=\'([^\']*)\';',re.DOTALL) def __init__(self, tkk='0', session=None, host='translate.google.com'): self.session = session or requests.Session() self.tkk = tkk self.host = host if 'http' in host else 'https://' + host def _update(self): """update tkk """ # we don't need to update the base TKK value when it is still valid now = math.floor(int(time.time() * 1000) / 3600000.0) if self.tkk and int(self.tkk.split('.')[0]) == now: return r = self.session.get(self.host) rawtkk = self.RE_RAWTKK.search(r.text) if rawtkk: self.tkk = rawtkk.group(1) return A: This worked for me: pip install googletrans==4.0.0-rc1 Original answer can be found here: https://github.com/ssut/py-googletrans/issues/234#issuecomment-742460612 A: pip uninstall googletrans googletrans-temp pip install googletrans-temp Worked for me in Win10 and Ubuntu 16 (Python 3.6) as of 2019.2.24 -- Refer to one of the replies in https://github.com/ssut/py-googletrans/issues/94. The old fix pip install git+https://github.com/BoseCorp/py-googletrans.git --upgrade does not work any more over here. A: Fixed is here https://pypi.org/project/py-translator/ $ pip3 install py_translator==1.8.9 from py_translator import Translator s = Translator().translate(text='Hello my friend', dest='es').text print(s) out:Hola mi amigo A: googletrans is not supported in latest python so you need to unistall it install new googletrans ( pip install googletrans==3.1.0a0) A: This is how I fixed my problem. pip3 uninstall googletrans pip3 install googletrans==3.1.0a0 First you need to uninstall the previous version and the install the 3.1.0 version. A: Use the translators package from here It works (; Supports more then google Installation: pip install translators --upgrade Usage: >>> import translators as ts Using Israel server backend. >>> ts.google('שלום' , to_language = 'es') 'Hola' A: Making the following change to gtoken made it work for me: RE_TKK = re.compile(r'tkk:\'(.+?)\'') def __init__(self, tkk='0', session=None, host='translate.google.com'): self.session = session or requests.Session() self.tkk = tkk self.host = host if 'http' in host else 'https://' + host def _update(self): """update tkk """ # we don't need to update the base TKK value when it is still valid r = self.session.get(self.host) self.tkk = self.RE_TKK.findall(r.text)[0] now = math.floor(int(time.time() * 1000) / 3600000.0) if self.tkk and int(self.tkk.split('.')[0]) == now: return # this will be the same as python code after stripping out a reserved word 'var' code = unicode(self.RE_TKK.search(r.text).group(1)).replace('var ', '') # unescape special ascii characters such like a \x3d(=) I obtained this snippet from the ticket here. Note that this is slightly different from other change suggested earlier by Kerem. For other uninitiated folks like me, gtoken.py can be found within AppData\Local\Continuum\anaconda3\site-packages\googletrans on a Windows machine using Anaconda. To find AppData, go into the address bar in file explorer, type '%AppData%', and hit Enter. A: It turns out putting the call whithin a try/except block solved the problem for me try: langs = translator.detect(update.message.text) if langs.lang == 'en': foo(translator.translate(update.message.text,dest='zh-cn').text) else: bar(translator.translate(update.message.text,dest='en').text) except Exception as e: print(e) A: Try - pip install googletrans==3.1.0a0 A: If you are using Google Colab or Jupyter Notebook, then run: !pip uninstall googletrans Restart the runtime, and then execute: !pip install googletrans==4.0.0rc1
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 facing the same issue ? I also tried to use googletrans on different laptops , still same issue ..Is googletrans package broken or something google did at their end ? >>> from googletrans import Translator >>> translator = Translator() >>> translator.translate('안녕하세요.') Traceback (most recent call last): File "<pyshell#2>", line 1, in <module> translator.translate('안녕하세요.') File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/googletrans/client.py", line 172, in translate data = self._translate(text, dest, src) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/googletrans/client.py", line 75, in _translate token = self.token_acquirer.do(text) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/googletrans/gtoken.py", line 180, in do self._update() File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/googletrans/gtoken.py", line 59, in _update code = unicode(self.RE_TKK.search(r.text).group(1)).replace('var ', '') AttributeError: 'NoneType' object has no attribute 'group'
[ "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(translation.text)\n#output: 'The sky is blue and I like bananas'\n\nIn case it does not work, try to specify the service url like this:\nfrom googletrans import Translator\ntranslator = Translator(service_urls=['translate.googleapis.com'])\ntranslator.translate(\"Der Himmel ist blau und ich mag Bananen\", dest='en')\n\nSee the discussion here for details and updates: https://github.com/ssut/py-googletrans/pull/237\nUpdate 10.12.20: Another fix was released\nAs pointed out by @DesiKeki and @Ahmed Breem, there is another fix which seems to work for several people:\npip install googletrans==4.0.0-rc1\n\nGithub discussion here: https://github.com/ssut/py-googletrans/issues/234#issuecomment-742460612\nIn case the fixes above don't work for you\nIf the above doesn't work for you, google_trans_new seems to be a good alternative that works for some people. It's unclear why the fix above works for some and doesn't for others. See details on installation and usage here: https://github.com/lushan88a/google_trans_new\n#pip install google_trans_new\n\nfrom google_trans_new import google_translator \ntranslator = google_translator() \ntranslate_text = translator.translate('สวัสดีจีน',lang_tgt='en') \nprint(translate_text)\n#output: Hello china\n\n", "Update 01/12/2020: This issue re-emerged lately, (apparently) caused once again by some changes on the Google translation API.\nA solution is being discussed (again) in this Github issue. Although there is not a definitive solution yet a Pull Request seem to be solving the problem: https://github.com/ssut/py-googletrans/pull/237.\nWhile we wait for it to be approved it can be installed like this:\n$ pip uninstall googletrans\n$ git clone https://github.com/alainrouillon/py-googletrans.git\n$ cd ./py-googletrans\n$ git checkout origin/feature/enhance-use-of-direct-api\n$ python setup.py install\n\nOriginal Answer:\nApparently it's a recent and widespread problem on Google's side.\nQuoting various Github discussions, it happens when Google sends you directly the raw token.\nIt's being discussed right now and there is already a pull request to fix it, so it should be resolved in the next few days.\nFor reference, see:\nhttps://github.com/ssut/py-googletrans/issues/48 <-- exact same problem reported on the Github repo\nhttps://github.com/pndurette/gTTS/issues/60 <-- seemingly same problem on a text-to-speech library\nhttps://github.com/ssut/py-googletrans/pull/78 <-- pull request to fix the issue\nTo apply this patch (without waiting for the pull request to be accepted) simply install the library from the forked repo https://github.com/BoseCorp/py-googletrans.git (uninstall the official library first):\n$ pip uninstall googletrans\n$ git clone https://github.com/BoseCorp/py-googletrans.git\n$ cd ./py-googletrans\n$ python setup.py install\n\nYou can clone it anywhere on your system and install it globally or while inside a virtualenv.\n", "Try google_trans_new. It solved the problem for me\nhttps://github.com/lushan88a/google_trans_new\n\npip install google_trans_new\n\nfrom google_trans_new import google_translator \n \ntranslator = google_translator() \ntranslate_text = translator.translate('Hola mundo!', lang_src='es', lang_tgt='en') \nprint(translate_text)\n-> Hello world!\n\n", "Updated Answer as of 2021 Sept\npip uninstall googletrans==4.0.0-rc1\n\npip install googletrans==3.1.0a0\n\nThe 3.1.0a0 version works with bulk translation too!\n", "Update 10.12.20: New Alpha Version Release (Stable Release Candidate) is released: 4.0.0-rc1\nIt can be installed as follows:\npip install googletrans==4.0.0-rc1\n\nUsage:\ntranslation = translator.translate('이 문장은 한글로 쓰여졌습니다.', dest='en')\nprint(translation.text)\n>>This sentence is written in Korean.\ndetected_lang = translator.detect('mein english me hindi likh raha hoon')\nprint(detected_lang)\n>>Detected(lang=hi, confidence=None)\ndetected_lang = translator.detect('이 문장은 한글로 쓰여졌습니다.')\nprint(detected_lang)\n>>Detected(lang=ko, confidence=None)\n\n", "Unfortunately, I could get neither googletrans nor google_trans_new to work, despite the many proposed fixes that are around.\nMy solution was to switch to the deep_translator package:\npip install -U deep-translator\n\nThen you can use it like this:\n>>> from deep_translator import GoogleTranslator\n>>> GoogleTranslator(source='auto', target='de').translate(\"keep it up, you are awesome\") \n'weiter so, du bist toll'\n\nSee documentation for more info.\n", "By the time of this answer, you can solve it with the following:\nUninstall your installed version of\npip uninstall googletrans\n\nInstall the following version\npip install googletrans==4.0.0rc1\n\nI hope this will works for you as it worked for me.\nYou can try it now:\nfrom googletrans import Translator\ntranslator = Translator()\nar = translator.translate('مرحبا').text\nprint(ar)\n\n", "Here is an unofficial fix to this problem as Darkblader24 stated in: https://github.com/ssut/py-googletrans/pull/78\nUpdate gtoken.py like this: \n RE_TKK = re.compile(r'TKK=eval\\(\\'\\(\\(function\\(\\)\\{(.+?)\\}\\)\\(\\)\\)\\'\\);',\n re.DOTALL)\n RE_RAWTKK = re.compile(r'TKK=\\'([^\\']*)\\';',re.DOTALL)\n\n def __init__(self, tkk='0', session=None, host='translate.google.com'):\n self.session = session or requests.Session()\n self.tkk = tkk\n self.host = host if 'http' in host else 'https://' + host\n\n def _update(self):\n \"\"\"update tkk\n \"\"\"\n # we don't need to update the base TKK value when it is still valid\n now = math.floor(int(time.time() * 1000) / 3600000.0)\n if self.tkk and int(self.tkk.split('.')[0]) == now:\n return\n\n r = self.session.get(self.host)\n\n rawtkk = self.RE_RAWTKK.search(r.text)\n if rawtkk:\n self.tkk = rawtkk.group(1)\n return\n\n", "This worked for me:\npip install googletrans==4.0.0-rc1\n\nOriginal answer can be found here:\nhttps://github.com/ssut/py-googletrans/issues/234#issuecomment-742460612\n", "pip uninstall googletrans googletrans-temp\npip install googletrans-temp\n\nWorked for me in Win10 and Ubuntu 16 (Python 3.6) as of 2019.2.24 -- Refer to one of the replies in https://github.com/ssut/py-googletrans/issues/94. The old fix pip install git+https://github.com/BoseCorp/py-googletrans.git --upgrade does not work any more over here.\n", "Fixed is here https://pypi.org/project/py-translator/\n$ pip3 install py_translator==1.8.9 \nfrom py_translator import Translator\ns = Translator().translate(text='Hello my friend', dest='es').text\nprint(s)\n\n\nout:Hola mi amigo\n\n", "googletrans is not supported in latest python so you need to unistall it\ninstall new googletrans ( pip install googletrans==3.1.0a0)\n", "This is how I fixed my problem.\npip3 uninstall googletrans\npip3 install googletrans==3.1.0a0\n\nFirst you need to uninstall the previous version and the install the 3.1.0 version.\n", "Use the translators package from here\n\nIt works (;\nSupports more then google\n\nInstallation:\npip install translators --upgrade\nUsage:\n\n >>> import translators as ts\n Using Israel server backend.\n >>> ts.google('שלום' , to_language = 'es')\n 'Hola'\n \n\n\n", "Making the following change to gtoken made it work for me:\nRE_TKK = re.compile(r'tkk:\\'(.+?)\\'') \n\ndef __init__(self, tkk='0', session=None, host='translate.google.com'):\n self.session = session or requests.Session()\n self.tkk = tkk\n self.host = host if 'http' in host else 'https://' + host\n\ndef _update(self):\n \"\"\"update tkk\n \"\"\"\n # we don't need to update the base TKK value when it is still valid\n r = self.session.get(self.host) \n\n self.tkk = self.RE_TKK.findall(r.text)[0]\n\n now = math.floor(int(time.time() * 1000) / 3600000.0)\n if self.tkk and int(self.tkk.split('.')[0]) == now:\n return\n\n # this will be the same as python code after stripping out a reserved word 'var'\n code = unicode(self.RE_TKK.search(r.text).group(1)).replace('var ', '')\n # unescape special ascii characters such like a \\x3d(=)\n\nI obtained this snippet from the ticket here. \nNote that this is slightly different from other change suggested earlier by Kerem. \nFor other uninitiated folks like me, gtoken.py can be found within AppData\\Local\\Continuum\\anaconda3\\site-packages\\googletrans on a Windows machine using Anaconda. To find AppData, go into the address bar in file explorer, type '%AppData%', and hit Enter. \n", "It turns out putting the call whithin a try/except block solved the problem for me\ntry:\n langs = translator.detect(update.message.text)\n if langs.lang == 'en':\n foo(translator.translate(update.message.text,dest='zh-cn').text)\n else:\n bar(translator.translate(update.message.text,dest='en').text)\nexcept Exception as e:\n print(e)\n\n", "Try - pip install googletrans==3.1.0a0\n", "If you are using Google Colab or Jupyter Notebook, then run:\n!pip uninstall googletrans\n\nRestart the runtime, and then execute:\n!pip install googletrans==4.0.0rc1\n\n" ]
[ 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 make the code simpler ?. The objective is to get all the Item (blue cylinder). A: 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 - for i in range(4): Dev.step(2*i+6) for a in range(3): Dev.turnLeft() Dev.step(i+2)
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 (blue cylinder).
[ "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.turnLeft()\n Dev.step(i+2)\n\n" ]
[ 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'], data= [[ 1, 'A' ], [ 1, 'B' ], [ 1, 'B' ], [ 1, np.nan ], [ 2, np.nan ], [ 3, 'C' ], [ 3, np.nan ], [ 3, 'D' ], [ 3, 'D' ]]) key value 0 1 A 1 1 B 2 1 B 3 1 NaN 4 2 NaN 5 3 C 6 3 NaN 7 3 D 8 3 D get most frequent values based on keys def mode(df, key_cols, value_col, count_col): return (df.groupby(key_cols + [value_col]).size() .to_frame(count_col).reset_index() .sort_values(count_col, ascending=False) .drop_duplicates(subset=key_cols)) freq_df = mode(test_input, ['key'], 'value', 'count') key value count 1 1 B 2 3 3 D 2 How can I fill the most frequent values on the original dataframe Desired Output key value 0 1 B 1 1 B 2 1 B 3 1 B 4 2 NaN 5 3 D 6 3 D 7 3 D 8 3 D 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)): test_input['value'] = (test_input.groupby('key')['value'] .transform(lambda x: next(iter(x.mode()), np.nan))) print (test_input) key value 0 1 B 1 1 B 2 1 B 3 1 B 4 2 NaN 5 3 D 6 3 D 7 3 D 8 3 D Solution with Series.value_counts: test_input['value'] = (test_input.groupby('key')['value'] .transform(lambda x: next(iter(x.value_counts().index), np.nan))) print (test_input) key value 0 1 B 1 1 B 2 1 B 3 1 B 4 2 NaN 5 3 D 6 3 D 7 3 D 8 3 D
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' ], [ 1, 'B' ], [ 1, 'B' ], [ 1, np.nan ], [ 2, np.nan ], [ 3, 'C' ], [ 3, np.nan ], [ 3, 'D' ], [ 3, 'D' ]]) key value 0 1 A 1 1 B 2 1 B 3 1 NaN 4 2 NaN 5 3 C 6 3 NaN 7 3 D 8 3 D get most frequent values based on keys def mode(df, key_cols, value_col, count_col): return (df.groupby(key_cols + [value_col]).size() .to_frame(count_col).reset_index() .sort_values(count_col, ascending=False) .drop_duplicates(subset=key_cols)) freq_df = mode(test_input, ['key'], 'value', 'count') key value count 1 1 B 2 3 3 D 2 How can I fill the most frequent values on the original dataframe Desired Output key value 0 1 B 1 1 B 2 1 B 3 1 B 4 2 NaN 5 3 D 6 3 D 7 3 D 8 3 D
[ "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 value\n0 1 B\n1 1 B\n2 1 B\n3 1 B\n4 2 NaN\n5 3 D\n6 3 D\n7 3 D\n8 3 D\n\nSolution with Series.value_counts:\ntest_input['value'] = (test_input.groupby('key')['value']\n .transform(lambda x: next(iter(x.value_counts().index), np.nan)))\nprint (test_input)\n key value\n0 1 B\n1 1 B\n2 1 B\n3 1 B\n4 2 NaN\n5 3 D\n6 3 D\n7 3 D\n8 3 D\n\n" ]
[ 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 e = datetime.datetime.now() print(e.strftime("%B %d,%Y @ %H:%M:%S")) number = random.randint(1, 100) print(number) name = input("\nEnter your name: ") def main(): print(f"Hi, {name}, Welcome to the Guessing Number Game ") x = eval(input("Enter a number between 1 and 100, or 0 to quit: ")) if x == 0: print("You quit? Goodbye!") else: playGuessingGame(x) def playGuessingGame(x): times = 1 while number != x: times += 1 if x < number: print("Too low, try again") x = eval(input("Enter a number between 1 and 100, or 0 to quit: ")) elif x > number: print("Too high, try again") x = eval(input("Enter a number between 1 and 100, or 0 to quit: ")) print(f"Congratulations {name}!, you guessed the right number with {times} tries!") main() After congratulations message the program should ask user again to input a number until user input zero as quit. A: since you have not added break inside while loop in playGuessingGame(). so program continuously asking to enter number even though you have entered zero def playGuessingGame(x): times = 1 while number != x: times += 1 if x < number: print("Too low, try again") x = eval(input("Enter a number between 1 and 100, or 0 to quit: ")) break #since this was missing, program doesn't break the while loop elif x > number: print("Too high, try again") x = int(input("Enter a number between 1 and 100, or 0 to quit: ")) break #since this was missing, program doesn't break the while loop
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() print(e.strftime("%B %d,%Y @ %H:%M:%S")) number = random.randint(1, 100) print(number) name = input("\nEnter your name: ") def main(): print(f"Hi, {name}, Welcome to the Guessing Number Game ") x = eval(input("Enter a number between 1 and 100, or 0 to quit: ")) if x == 0: print("You quit? Goodbye!") else: playGuessingGame(x) def playGuessingGame(x): times = 1 while number != x: times += 1 if x < number: print("Too low, try again") x = eval(input("Enter a number between 1 and 100, or 0 to quit: ")) elif x > number: print("Too high, try again") x = eval(input("Enter a number between 1 and 100, or 0 to quit: ")) print(f"Congratulations {name}!, you guessed the right number with {times} tries!") main() After congratulations message the program should ask user again to input a number until user input zero as quit.
[ "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 x = eval(input(\"Enter a number between 1 and 100, or 0 to quit: \"))\n break #since this was missing, program doesn't break the while loop\n\n elif x > number:\n print(\"Too high, try again\")\n x = int(input(\"Enter a number between 1 and 100, or 0 to quit: \"))\n break #since this was missing, program doesn't break the while loop \n\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 for such a simple thing. I was wondering if there was a more elegant way of doing this. A: If you have... items = [ ['a', 'b'], ['c', 'd'] ] ...you have a nested list that you can access this way: >>> items[0] ['a', 'b'] >>> items[0][0] To have the second element (the element with index 1) of each sublist, I would suggest a list comprehension: new_list = [sublist[1] for sublist in items] If you want the last element (the element with index -1) of each sublist, you just have to change the index: new_list = [sublist[-1] for sublist in items] For the list you shown the two lines will give the same list, but when the sublists have more than two elements the two solution will give different results. You can read more about list comprehension here and here. A: From a readability perspective, I would probably combine iterable unpacking with list comprehension for something like - new_list = [second for first, second, *rest in items] The *rest is not really required in this case where the sublists have only 2 items, but helps generalize. A: You can do new_list = [i[-1] for i in items] A: using List comprehension: items = [['a','b'],['c','d']] new_list = [item[1] for item in items] # where 1 in item[1] is the index of last element or you can use -1 print(new_list) # ['b', 'd']
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 elegant way of doing this.
[ "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 in items]\n\nIf you want the last element (the element with index -1) of each sublist, you just have to change the index:\nnew_list = [sublist[-1] for sublist in items]\n\nFor the list you shown the two lines will give the same list, but when the sublists have more than two elements the two solution will give different results.\n\nYou can read more about list comprehension here and here.\n", "From a readability perspective, I would probably combine iterable unpacking with list comprehension for something like -\nnew_list = [second for first, second, *rest in items]\n\nThe *rest is not really required in this case where the sublists have only 2 items, but helps generalize.\n", "You can do\nnew_list = [i[-1] for i in items]\n\n", "using List comprehension:\nitems = [['a','b'],['c','d']]\n\nnew_list = [item[1] for item in items] # where 1 in item[1] is the index of last element or you can use -1\n\nprint(new_list) # ['b', 'd']\n\n" ]
[ 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'\.', a) bb=re.split(r'\.', g) c=[] e=[] for i in range(len(b)): c.append(b[i]) dd=c for j in range(len(bb)): e.append(bb[j]) f=e for i in dd: if len(i) != len(f[j]): return True else: return False #call function d="66.22.33" u="66.2.33" print(aa(d,u)) the result is false and we not that this is a mistake : 22 contain 2 number 1 contain 1 number. A: You are trying to find if substrings contained between dots are the same length: d="66.22.33" u="66.2.33" compare(d, u) >>> False d="66.22.33" u="66.11.33" compare(d, u) >>> True Then you can check it this way: def compare(a, b): a = a.split('.') b = b.split('.') return all(len(i) == len(j) for i, j in zip(a,b))
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=[] for i in range(len(b)): c.append(b[i]) dd=c for j in range(len(bb)): e.append(bb[j]) f=e for i in dd: if len(i) != len(f[j]): return True else: return False #call function d="66.22.33" u="66.2.33" print(aa(d,u)) the result is false and we not that this is a mistake : 22 contain 2 number 1 contain 1 number.
[ "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(i) == len(j) for i, j in zip(a,b))\n\n" ]
[ 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(): for k1, v1 in v.items(): for k2, v2 in v1.items(): d1[(k, k2)].update({k1: v2}) df.insert(loc=2, column=' ', value=None) df.insert(loc=0, column='Mode', value='Website') df.columns = df.columns.rename("Metric", level=1) It looks like: I need help with applying the font and background color using the conditions in the following functions, to the traffic and sales row of the data frame: def sales_color(val): font_color = '' background_color = '' if val <= 10000: font_color = 'red' background_color = 'light red' elif val >= 100000: font_color = 'green' else: font_color = 'grey' return [font_color, background_color] def traffic_color(val): font_color = 'orange' if val < 300 else 'black' background_color = 'light orange' if val < 300 else '' return [font_color, background_color] I was trying an inefficient way - applying the colors individually to the cell, but that is not working: df['US']['new']['Sales'].style.apply(sales_color) df['US']['new']['Traffic'].style.apply(traffic_color) df['US']['Repeat']['Sales'].style.apply(sales_color) df['US']['Repeat']['Traffic'].style.apply(traffic_color) df['UK']['new']['Sales'].style.apply(sales_color) df['UK']['new']['Traffic'].style.apply(traffic_color) df['UK']['Repeat']['Sales'].style.apply(sales_color) df['UK']['Repeat']['Traffic'].style.apply(traffic_color) A: Use custom function with select by DataFrame.loc, then set values by conditions by numpy.where and numpy.select. For me not working light red and light orange color, I use colors hex codes instead: def color(x): idx = pd.IndexSlice t = x.loc['Traffic', idx[:, ['new','repeat']]] s = x.loc['Sales', idx[:, ['new','repeat']]] df1 = pd.DataFrame('', index=x.index, columns=x.columns) s1 = np.select([s <= 10000, s >= 100000], ['background-color: #fa8072; color: red', 'color: green'], default='color: grey') t1 = np.where(t <= 300, 'background-color: #ffcc99; color: orange', 'color: black') df1.loc['Sales', idx[:, ['new','repeat']]] = s1 df1.loc['Traffic', idx[:, ['new','repeat']]] = t1 return df1 df.style.apply(color, axis=None)
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(): d1[(k, k2)].update({k1: v2}) df.insert(loc=2, column=' ', value=None) df.insert(loc=0, column='Mode', value='Website') df.columns = df.columns.rename("Metric", level=1) It looks like: I need help with applying the font and background color using the conditions in the following functions, to the traffic and sales row of the data frame: def sales_color(val): font_color = '' background_color = '' if val <= 10000: font_color = 'red' background_color = 'light red' elif val >= 100000: font_color = 'green' else: font_color = 'grey' return [font_color, background_color] def traffic_color(val): font_color = 'orange' if val < 300 else 'black' background_color = 'light orange' if val < 300 else '' return [font_color, background_color] I was trying an inefficient way - applying the colors individually to the cell, but that is not working: df['US']['new']['Sales'].style.apply(sales_color) df['US']['new']['Traffic'].style.apply(traffic_color) df['US']['Repeat']['Sales'].style.apply(sales_color) df['US']['Repeat']['Traffic'].style.apply(traffic_color) df['UK']['new']['Sales'].style.apply(sales_color) df['UK']['new']['Traffic'].style.apply(traffic_color) df['UK']['Repeat']['Sales'].style.apply(sales_color) df['UK']['Repeat']['Traffic'].style.apply(traffic_color)
[ "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['Sales', idx[:, ['new','repeat']]]\n \n df1 = pd.DataFrame('', index=x.index, columns=x.columns)\n \n s1 = np.select([s <= 10000, s >= 100000], ['background-color: #fa8072; color: red',\n 'color: green'], \n default='color: grey')\n t1 = np.where(t <= 300, 'background-color: #ffcc99; color: orange',\n 'color: black')\n df1.loc['Sales', idx[:, ['new','repeat']]] = s1\n df1.loc['Traffic', idx[:, ['new','repeat']]] = t1\n \n return df1\n\ndf.style.apply(color, axis=None)\n\n" ]
[ 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)] print arraya Produces [1, 2, 3, 1, 2, 3, 1] A: You can use zip combined with cycle for this: if arrayb: arraysum = [sum(x) for x in zip(cycle(arrayb), arraya)] else: arraysum = arraya A: arraya = [1,1,1,1,1,1,1] arrayb = [0,1,2] arraysum = [] i=0 while i in range(len(arraya)): arraysum.append(arraya[i] + arrayb[i % len(arrayb)]) i+=1 print (arraysum) A: I hope this is understandable. from itertools import cycle def sum_arr(smaller_array, larger_array): new_a = [] for _ in zip(cycle(smaller_array), larger_array): # cycle(0, 1, 2) => 0 1 2 0 1 2 . . . new_a.append(sum(_)) return new_a a = [1,1,1,1,1,1,1] b = [0,1,2] if len(a) < len(b): # check which one is the smaller and to be repeated new_array = sum_arr(a, b) else: new_array = sum_arr(b, a) print(new_array) # [1, 2, 3, 1, 2, 3, 1] A: def Sum(): arrayb = [0,1,2] arraya = [1,1,1,1,1,1,1] arraySum = [] counter = 0 for i in range(len(arraya)): if i % len(arrayb) == 0: counter = 0 arraySum.append(arraya[i] + arrayb[counter]) counter+=1 return arraySum
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 = arraya\n\n", "arraya = [1,1,1,1,1,1,1]\narrayb = [0,1,2]\narraysum = []\n\ni=0\n\nwhile i in range(len(arraya)):\n arraysum.append(arraya[i] + arrayb[i % len(arrayb)])\n i+=1\n\nprint (arraysum)\n\n", "I hope this is understandable.\nfrom itertools import cycle\n\ndef sum_arr(smaller_array, larger_array):\n new_a = []\n\n for _ in zip(cycle(smaller_array), larger_array): # cycle(0, 1, 2) => 0 1 2 0 1 2 . . .\n\n new_a.append(sum(_))\n\n return new_a\n\na = [1,1,1,1,1,1,1]\nb = [0,1,2]\n\nif len(a) < len(b): # check which one is the smaller and to be repeated\n new_array = sum_arr(a, b)\nelse:\n new_array = sum_arr(b, a)\n\nprint(new_array) # [1, 2, 3, 1, 2, 3, 1]\n\n", "def Sum():\narrayb = [0,1,2]\narraya = [1,1,1,1,1,1,1]\narraySum = []\n\ncounter = 0\n\nfor i in range(len(arraya)):\n if i % len(arrayb) == 0:\n counter = 0\n \n arraySum.append(arraya[i] + arrayb[counter])\n counter+=1\nreturn arraySum\n\n" ]
[ 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++ make RUN apk add --no-cache build-base python2-dev gpgme-dev libc-dev RUN apk add --no-cache openssl-dev libffi-dev build-base mariadb-dev libxml2-dev xmlsec-dev xmlsec pkgconf git postgresql-dev RUN apk update RUN pip install --no-cache-dir librabbitmq==1.6.1 RUN pip install --no-cache-dir MySQL-python Error: In file included from clib/librabbitmq/amqp_api.c:43: #10 5.796 /usr/include/assert.h:19:16: error: declaration for parameter '__assert_fail' but no such parameter #10 5.796 19 | _Noreturn void __assert_fail (const char *, const char *, int, const char *); #10 5.796 | ^~~~~~~~~~~~~ #10 5.796 clib/librabbitmq/amqp_api.c:340: error: expected '{' at end of input #10 5.796 340 | } #10 5.796 | #10 5.796 clib/librabbitmq/amqp_api.c:340:1: warning: control reaches end of non-void function [-Wreturn-type] #10 5.796 340 | } #10 5.796 | ^ #10 5.796 error: command 'gcc' failed with exit status 1 #10 5.796 ---------------------------------------- #10 5.805 ERROR: Command errored out with exit status 1: /usr/local/bin/python -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-X4wzDj/librabbitmq/setup.py'"'"'; __file__='"'"'/tmp/pip-install-X4wzDj/librabbitmq/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record /tmp/pip-record-QtKdGu/install-record.txt --single-version-externally-managed --compile --install-headers /usr/local/include/python2.7/librabbitmq Check the logs for full command output. PS: I tried ubuntu:14.04 base image as well, but that gives unable to fetch pypi url A: Try updating Dockerfile by moving RUN apk update On top after your image It worked for me.
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-dev gpgme-dev libc-dev RUN apk add --no-cache openssl-dev libffi-dev build-base mariadb-dev libxml2-dev xmlsec-dev xmlsec pkgconf git postgresql-dev RUN apk update RUN pip install --no-cache-dir librabbitmq==1.6.1 RUN pip install --no-cache-dir MySQL-python Error: In file included from clib/librabbitmq/amqp_api.c:43: #10 5.796 /usr/include/assert.h:19:16: error: declaration for parameter '__assert_fail' but no such parameter #10 5.796 19 | _Noreturn void __assert_fail (const char *, const char *, int, const char *); #10 5.796 | ^~~~~~~~~~~~~ #10 5.796 clib/librabbitmq/amqp_api.c:340: error: expected '{' at end of input #10 5.796 340 | } #10 5.796 | #10 5.796 clib/librabbitmq/amqp_api.c:340:1: warning: control reaches end of non-void function [-Wreturn-type] #10 5.796 340 | } #10 5.796 | ^ #10 5.796 error: command 'gcc' failed with exit status 1 #10 5.796 ---------------------------------------- #10 5.805 ERROR: Command errored out with exit status 1: /usr/local/bin/python -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-X4wzDj/librabbitmq/setup.py'"'"'; __file__='"'"'/tmp/pip-install-X4wzDj/librabbitmq/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record /tmp/pip-record-QtKdGu/install-record.txt --single-version-externally-managed --compile --install-headers /usr/local/include/python2.7/librabbitmq Check the logs for full command output. PS: I tried ubuntu:14.04 base image as well, but that gives unable to fetch pypi url
[ "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 datetime import zoneinfo # UTC offsets of time zones depend on the date, so we need a reference date: dt = datetime.datetime.now(datetime.timezone.utc) print(dt.isoformat(timespec="seconds")) # 2022-11-25T07:40:28+00:00 for z in sorted(zoneinfo.available_timezones()): print(z, dt.astimezone(zoneinfo.ZoneInfo(z)).isoformat(timespec="seconds")) Africa/Abidjan 2022-11-25T07:40:28+00:00 Africa/Accra 2022-11-25T07:40:28+00:00 Africa/Addis_Ababa 2022-11-25T10:40:28+03:00 ... WET 2022-11-25T07:40:28+00:00 Zulu 2022-11-25T07:40:28+00:00 localtime 2022-11-25T08:40:28+01:00 # Unix only, I believe To access only the UTC offset, you can use for example dt.strftime("%z") # to get a string # '+0000' dt.utcoffset() # to get a datetime.timedelta # datetime.timedelta(0)
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(timespec=\"seconds\"))\n# 2022-11-25T07:40:28+00:00\n\nfor z in sorted(zoneinfo.available_timezones()):\n print(z, dt.astimezone(zoneinfo.ZoneInfo(z)).isoformat(timespec=\"seconds\"))\n\nAfrica/Abidjan 2022-11-25T07:40:28+00:00\nAfrica/Accra 2022-11-25T07:40:28+00:00\nAfrica/Addis_Ababa 2022-11-25T10:40:28+03:00\n...\nWET 2022-11-25T07:40:28+00:00\nZulu 2022-11-25T07:40:28+00:00\nlocaltime 2022-11-25T08:40:28+01:00 # Unix only, I believe\n\nTo access only the UTC offset, you can use for example\ndt.strftime(\"%z\") # to get a string\n# '+0000'\n\ndt.utcoffset() # to get a datetime.timedelta\n# datetime.timedelta(0)\n\n" ]
[ 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: | #!/usr/bin/env bash # do some meaningful stuff here before emitting the result myvar="foobar" printf $(params.myvar) | tee $(results.myresult) However, I want to use python instead of a bash script. How can I emit the result variable? I guess I'd have to use something like this in python: var myvar = "foobar" sys.stdout.write(myvar) But how can I write this into $(results.myresult) and mimic the combination of pipe and tee from Linux in python? A: 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)).
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 here before emitting the result myvar="foobar" printf $(params.myvar) | tee $(results.myresult) However, I want to use python instead of a bash script. How can I emit the result variable? I guess I'd have to use something like this in python: var myvar = "foobar" sys.stdout.write(myvar) But how can I write this into $(results.myresult) and mimic the combination of pipe and tee from Linux in python?
[ "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 field. However, to get started in Python, I would suggest the following Python video: https://www.youtube.com/watch?v=rfscVS0vtbw This is the same video I used when I first got started in Python. Once you have the basics down, I would suggest you do some beginner projects just to brush up on the skills you have learned. Some of the ones I recommend for total beginners are programs like Tic-Tac-Toe, Hangman, and Random code generators, or even a program that takes a string and turns it into a simple code (like making every letter "a" into "b" and "b" into "c"). Needless to say, there are many, many simple beginner projects. Do a couple of these (around 3-4). This will get you used to Python (remember, you are just scratching the surface). Next, I would suggest you take a dive into numpy and pandas modules in Python. These two modules are very important for handling data (and that is critical for machine learning). I am not proficient in numpy or pandas, but I did look into them at one point. For numpy, I watched the following video: https://www.youtube.com/watch?v=QUT1VHiLmmI and for pandas I watched videos by the YouTube channel named Corey Schafer that were about pandas. Now, if you do not have knowledge of the math behind machine learning, you can one of two choices. Some of the machine learning tutorials I am suggesting will allow you to make progress in learning machine learning, but you will definitely not understand the underlying concepts (you will not know what each line of code does, what each block of code is meant to be, but you will not understand the why). You can choose to skip this next step, but it is important to know that it is critical for success to understand the underlying mechanisms of something rather than just the surface (as with everything else). So, I would strongly suggest you look into machine learning courses that simply teach theory rather than practice as well: https://www.youtube.com/watch?v=GwIo3gDZCVQ It is important for me to point out that these resources more than likely will not be enough, as you watch these videos, you will end up having questions that they may not go over, so you will have to do a little bit of research on the internet yourself as well After you get those down, you can then actually look into Machine Learning with Python. I believe there are two main ways you can practice Machine Learning: TensorFlow and PyTorch. I am not aware between the primary differences between the two, but I do know that they are quite popular and have plenty of documentation. Again, same technique as before. Go on YouTube, and look into courses about Machine Learning, here are a few: A very, very, long tutorial (~25 hrs) in PyTorch: https://www.youtube.com/watch?v=V_xro1bcAuA Shorter tutorial in PyTorch (~5hrs): https://www.youtube.com/watch?v=c36lUUr864M A 2-part TensorFlow Course: https://www.youtube.com/watch?v=tpCFfeUEGs8 and https://www.youtube.com/watch?v=ZUKz4125WNI&t=0s Also, I would like to add that along with PyTorch and TensorFlow, there is also Keras, but I believe it may not be as popular and/or well-documented as the other two Also, these are just my suggestions for you to get started from the little knowledge I have about machine learning. The common thing with beginning something, is that no matter what it is, it generally starts with scratching the surface of the basics, and just sitting down and watching tutorials for long hours until you get the hang of it
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 the basics down, I would suggest you do some beginner projects just to brush up on the skills you have learned. Some of the ones I recommend for total beginners are programs like Tic-Tac-Toe, Hangman, and Random code generators, or even a program that takes a string and turns it into a simple code (like making every letter \"a\" into \"b\" and \"b\" into \"c\"). Needless to say, there are many, many simple beginner projects. Do a couple of these (around 3-4). This will get you used to Python (remember, you are just scratching the surface).\nNext, I would suggest you take a dive into numpy and pandas modules in Python. These two modules are very important for handling data (and that is critical for machine learning). I am not proficient in numpy or pandas, but I did look into them at one point. For numpy, I watched the following video: https://www.youtube.com/watch?v=QUT1VHiLmmI\nand for pandas I watched videos by the YouTube channel named Corey Schafer that were about pandas.\nNow, if you do not have knowledge of the math behind machine learning, you can one of two choices. Some of the machine learning tutorials I am suggesting will allow you to make progress in learning machine learning, but you will definitely not understand the underlying concepts (you will not know what each line of code does, what each block of code is meant to be, but you will not understand the why). You can choose to skip this next step, but it is important to know that it is critical for success to understand the underlying mechanisms of something rather than just the surface (as with everything else). So, I would strongly suggest you look into machine learning courses that simply teach theory rather than practice as well: https://www.youtube.com/watch?v=GwIo3gDZCVQ\nIt is important for me to point out that these resources more than likely will not be enough, as you watch these videos, you will end up having questions that they may not go over, so you will have to do a little bit of research on the internet yourself as well\nAfter you get those down, you can then actually look into Machine Learning with Python.\nI believe there are two main ways you can practice Machine Learning: TensorFlow and PyTorch. I am not aware between the primary differences between the two, but I do know that they are quite popular and have plenty of documentation.\nAgain, same technique as before. Go on YouTube, and look into courses about Machine Learning, here are a few:\nA very, very, long tutorial (~25 hrs) in PyTorch: https://www.youtube.com/watch?v=V_xro1bcAuA\nShorter tutorial in PyTorch (~5hrs): https://www.youtube.com/watch?v=c36lUUr864M\nA 2-part TensorFlow Course: https://www.youtube.com/watch?v=tpCFfeUEGs8 and https://www.youtube.com/watch?v=ZUKz4125WNI&t=0s\nAlso, I would like to add that along with PyTorch and TensorFlow, there is also Keras, but I believe it may not be as popular and/or well-documented as the other two\nAlso, these are just my suggestions for you to get started from the little knowledge I have about machine learning.\nThe common thing with beginning something, is that no matter what it is, it generally starts with scratching the surface of the basics, and just sitting down and watching tutorials for long hours until you get the hang of it\n" ]
[ 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 must filter only by var2 and the other way around. Is there a way to insert an if condition inside the filter queryset or something else? TY A: 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. family_queryset = ModelClass.objects.all() if var1: family_queryset = family_queryset.filter(foo=var1) if var2: family_queryset = family_queryset.filter(bar=var2) A: More generally, you can create a filter dictionary and filter the dictionary keys for null values using a dict comprehension. filters = { 'foo': var1, 'bar': var2, } filters = {k:v for k,v in filters.items() if v is not None} family_queryset = ModelClass.objects.filter(**filters) You can even use if v instead of if v is not None to also exclude empty strings, for example. A: A different approach using Q Q object encapsulates a SQL expression in a Python object that can be used in database-related operations. Using Q objects we can make complex queries with less and simple code. filters = Q() if my_first_param: filters &= Q(my_first_param=my_first_param) if my_second_param: filters &= Q(my_second_param=my_second_param) # Perform filtration family_queryset = ModelClass.objects.filter(filters)
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 a way to insert an if condition inside the filter queryset or something else? TY
[ "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\nif var2:\n family_queryset = family_queryset.filter(bar=var2)\n\n", "More generally, you can create a filter dictionary and filter the dictionary keys for null values using a dict comprehension.\nfilters = {\n 'foo': var1,\n 'bar': var2,\n}\nfilters = {k:v for k,v in filters.items() if v is not None}\nfamily_queryset = ModelClass.objects.filter(**filters)\n\nYou can even use if v instead of if v is not None to also exclude empty strings, for example.\n", "A different approach using Q\n\nQ object encapsulates a SQL expression in a Python object that can be used in database-related operations. Using Q objects we can make complex queries with less and simple code.\n\nfilters = Q()\nif my_first_param:\n filters &= Q(my_first_param=my_first_param)\nif my_second_param:\n filters &= Q(my_second_param=my_second_param)\n\n# Perform filtration\nfamily_queryset = ModelClass.objects.filter(filters)\n\n\n" ]
[ 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 PC (Windows) using python and the pymodbus library, running at 9600 baud. I can succesfully transfer data. The initial sanity test was a simple analogRead() on one of the Arduinos (sensor 1), writing to it's internal holding register and then having the pymodbus master poll/request that register. I've now connected a second Arduino (sensor 2) which has an I2C connection to a flow sensor. That arduino is running reads of the sensor over I2C and updating 5x holding registers with the data. The master (PC) is polling both Arduinos (sensors 1 and 2) one after the other. It is always successful in acquiring sensor 1's data (only 1 register) but intermittently fails getting sensor 2's data (5 registers). The python console looks like this: Sensor 2: 0,25000,0,0, 0 Sensor 2: 0,25000,0,0, 0 Modbus Error: [Input/Output] No Response received from the remote unit/Unable to decode response Modbus Error: [Input/Output] No Response received from the remote unit/Unable to decode response Sensor 2: 0,25000,0,0, 0 Modbus Error: [Input/Output] No Response received from the remote unit/Unable to decode response Sensor 2: 0,25000,0,0, 0 Modbus Error: [Input/Output] No Response received from the remote unit/Unable to decode response A deeper look at the logs reveals the issue is not all the Bytes are making it accross, see below: 11/24/2022 03:52:59 PM Running transaction 4 11/24/2022 03:52:59 PM SEND: 0x1 0x3 0x0 0x0 0x0 0x5 0x85 0xc9 11/24/2022 03:52:59 PM Changing state to IDLE - Last Frame End - 1669265577.447308, Current Time stamp - 1669265579.457942 11/24/2022 03:52:59 PM New Transaction state "SENDING" 11/24/2022 03:52:59 PM Changing transaction state from "SENDING" to "WAITING FOR REPLY" 11/24/2022 03:52:59 PM {msg_start} received, Expected 15 bytes Received 11 bytes !!!! 11/24/2022 03:52:59 PM Changing transaction state from "WAITING FOR REPLY" to "PROCESSING REPLY" 11/24/2022 03:52:59 PM RECV: 0x1 0x3 0xa 0x0 0x0 0x61 0xa8 0x0 0x0 0x0 0x0 11/24/2022 03:52:59 PM Frame - [b'\x01\x03\n\x00\x00a\xa8\x00\x00\x00\x00'] not ready 11/24/2022 03:52:59 PM Getting transaction 1 11/24/2022 03:52:59 PM Changing transaction state from "PROCESSING REPLY" to "TRANSACTION_COMPLETE" 11/24/2022 03:52:59 PM Modbus Error: [Input/Output] No Response received from the remote unit/Unable to decode response 11/24/2022 03:53:01 PM Current transaction state - TRANSACTION_COMPLETE I've now removed asking sensor 1 for data at all and have my python script only requesting from sensor 2 (the problem sensor) but the problem still remains, my python script is as follows: import serial import time import logging from pymodbus.client import ModbusSerialClient from pymodbus.transaction import ModbusRtuFramer logger = logging.getLogger() logger.setLevel(logging.DEBUG) handler = logging.FileHandler('main.log', 'w', 'utf-8') handler.setFormatter(logging.Formatter(fmt='%(asctime)s %(message)s', datefmt='%m/%d/%Y %I:%M:%S %p')) logger.addHandler(handler) client = ModbusSerialClient("COM12", ModbusRtuFramer, baudrate=9600, timeout=10, reset_socket=False) client.connect() while(1): c2 = client.read_holding_registers(0,5,1) if c2.isError(): logger.error(msg=c2) print(c2) else: print(f"Sensor 2: {c2.getRegister(0)},{c2.getRegister(1)},{c2.getRegister(2)},{c2.getRegister(3)}, {c2.getRegister(4)}") time.sleep(2) I'm not quite sure what's misfiring... I can stream the sensor 2 data perfectly well using a GUI like QModMaster which I know uses libmodbus under the hood. Should I be instead working with the python library pylibmodbus? It requires a compiled libmodbus locally which is a bit of a headache for Windows... Am I missing a setting for pymodbus that could help? I have tried varying the pymodbus timeout which did not work. I have tried decreasing the sample rate for the flow sensor to reduce the frequecy and ensure the Arduino is free/available for Modbus requests. This did not work, in fact decreasing it made the problem worse. I have tried adding basic delays to the python code (time.sleep(2)) to slow down the Modbus requests but this had no impact on the errors. Hope someone knows what's going on as I've spent ages trawling through online sources to find the answer to no avail. If more clarification is needed from my end I can provide :) Thanks! P.S. Arduino code below for reference #include <Arduino.h> #include <ArduinoRS485.h> #include <ArduinoModbus.h> #include <Wire.h> /** * Modbus slave/server */ #define SAMPLE_RATE 50 const int ADDRESS = 0x08; // Sensor I2C Address const float SCALE_FACTOR_FLOW = 500.0; // Scale Factor for flow rate measurement const float SCALE_FACTOR_TEMP = 200.0; // Scale Factor for temperature measurement int count = 0; unsigned long startMillis; unsigned long currentMillis; enum error_types{ no_error, write_mode_error, read_error }; enum error_types error; // Protoypes int stop_continuous_measurement(); int start_continous_measurement(); void setup() { int ret; // Start Serial and I2C Serial.begin(9600); // initialize serial communication Wire.begin(); // join i2c bus (address optional for master) // Set up MODBUS if (!ModbusRTUServer.begin(0x01,9600)) { Serial.println("Could not begin ModbusRTU server..."); while(1); } // configure holding registers at address 0x00, 4 registers for data ModbusRTUServer.configureHoldingRegisters(0x00, 5); // start sensor do { // Soft reset the sensor Wire.beginTransmission(0x00); Wire.write(0x06); ret = Wire.endTransmission(); if (ret != 0) { Serial.println("Error while sending soft reset command, retrying..."); delay(500); // wait long enough for chip reset to complete } } while (ret != 0); delay(50); // wait long enough for chip reset to complete // To perform a measurement, first send 0x3608 to switch to continuous if(start_continous_measurement() !=0) { error = write_mode_error; } startMillis = millis(); } void loop() { ModbusRTUServer.poll(); uint16_t aux_value; uint16_t sensor_flow_value; uint16_t sensor_temp_value; int16_t signed_flow_value; int16_t signed_temp_value; float scaled_flow_value; float scaled_temp_value; byte aux_crc; byte sensor_flow_crc; byte sensor_temp_crc; // measurement mode (H20 calibration), then read 3x (2 bytes + 1 CRC byte) from the sensor. // To perform a IPA based measurement, send 0x3615 instead. // Check datasheet for available measurement commands. error = no_error; currentMillis = millis(); if(currentMillis - startMillis > SAMPLE_RATE){ Wire.requestFrom(ADDRESS, 9); if (Wire.available() < 9) { error = read_error; } else{ sensor_flow_value = Wire.read() << 8; // read the MSB from the sensor sensor_flow_value |= Wire.read(); // read the LSB from the sensor sensor_flow_crc = Wire.read(); sensor_temp_value = Wire.read() << 8; // read the MSB from the sensor sensor_temp_value |= Wire.read(); // read the LSB from the sensor sensor_temp_crc = Wire.read(); aux_value = Wire.read() << 8; // read the MSB from the sensor aux_value |= Wire.read(); // read the LSB from the sensor aux_crc = Wire.read(); signed_flow_value = (int16_t) sensor_flow_value; scaled_flow_value = ((float) signed_flow_value) / SCALE_FACTOR_FLOW; signed_temp_value = (int16_t) sensor_temp_value; scaled_temp_value = ((float) signed_temp_value) / SCALE_FACTOR_TEMP; // write to MODBUS registers ModbusRTUServer.holdingRegisterWrite(0, (uint16_t) count); ModbusRTUServer.holdingRegisterWrite(1, (uint16_t) scaled_temp_value*1000); ModbusRTUServer.holdingRegisterWrite(2, (uint16_t) scaled_flow_value*1000); ModbusRTUServer.holdingRegisterWrite(3,(uint16_t) aux_value); ModbusRTUServer.holdingRegisterWrite(4, (uint16_t) error); } startMillis = currentMillis; } } int start_continous_measurement() { Wire.beginTransmission(ADDRESS); Wire.write(0x36); Wire.write(0x08); return Wire.endTransmission(); } int stop_continuous_measurement() { // To stop the continuous measurement, first send 0x3FF9. Wire.beginTransmission(ADDRESS); Wire.write(0x3F); Wire.write(0xF9); return Wire.endTransmission(); } A: 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 enforced. Also see the similar story: Pymodbus : Wrong byte count in response, and the pymodbus issue.
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 initial sanity test was a simple analogRead() on one of the Arduinos (sensor 1), writing to it's internal holding register and then having the pymodbus master poll/request that register. I've now connected a second Arduino (sensor 2) which has an I2C connection to a flow sensor. That arduino is running reads of the sensor over I2C and updating 5x holding registers with the data. The master (PC) is polling both Arduinos (sensors 1 and 2) one after the other. It is always successful in acquiring sensor 1's data (only 1 register) but intermittently fails getting sensor 2's data (5 registers). The python console looks like this: Sensor 2: 0,25000,0,0, 0 Sensor 2: 0,25000,0,0, 0 Modbus Error: [Input/Output] No Response received from the remote unit/Unable to decode response Modbus Error: [Input/Output] No Response received from the remote unit/Unable to decode response Sensor 2: 0,25000,0,0, 0 Modbus Error: [Input/Output] No Response received from the remote unit/Unable to decode response Sensor 2: 0,25000,0,0, 0 Modbus Error: [Input/Output] No Response received from the remote unit/Unable to decode response A deeper look at the logs reveals the issue is not all the Bytes are making it accross, see below: 11/24/2022 03:52:59 PM Running transaction 4 11/24/2022 03:52:59 PM SEND: 0x1 0x3 0x0 0x0 0x0 0x5 0x85 0xc9 11/24/2022 03:52:59 PM Changing state to IDLE - Last Frame End - 1669265577.447308, Current Time stamp - 1669265579.457942 11/24/2022 03:52:59 PM New Transaction state "SENDING" 11/24/2022 03:52:59 PM Changing transaction state from "SENDING" to "WAITING FOR REPLY" 11/24/2022 03:52:59 PM {msg_start} received, Expected 15 bytes Received 11 bytes !!!! 11/24/2022 03:52:59 PM Changing transaction state from "WAITING FOR REPLY" to "PROCESSING REPLY" 11/24/2022 03:52:59 PM RECV: 0x1 0x3 0xa 0x0 0x0 0x61 0xa8 0x0 0x0 0x0 0x0 11/24/2022 03:52:59 PM Frame - [b'\x01\x03\n\x00\x00a\xa8\x00\x00\x00\x00'] not ready 11/24/2022 03:52:59 PM Getting transaction 1 11/24/2022 03:52:59 PM Changing transaction state from "PROCESSING REPLY" to "TRANSACTION_COMPLETE" 11/24/2022 03:52:59 PM Modbus Error: [Input/Output] No Response received from the remote unit/Unable to decode response 11/24/2022 03:53:01 PM Current transaction state - TRANSACTION_COMPLETE I've now removed asking sensor 1 for data at all and have my python script only requesting from sensor 2 (the problem sensor) but the problem still remains, my python script is as follows: import serial import time import logging from pymodbus.client import ModbusSerialClient from pymodbus.transaction import ModbusRtuFramer logger = logging.getLogger() logger.setLevel(logging.DEBUG) handler = logging.FileHandler('main.log', 'w', 'utf-8') handler.setFormatter(logging.Formatter(fmt='%(asctime)s %(message)s', datefmt='%m/%d/%Y %I:%M:%S %p')) logger.addHandler(handler) client = ModbusSerialClient("COM12", ModbusRtuFramer, baudrate=9600, timeout=10, reset_socket=False) client.connect() while(1): c2 = client.read_holding_registers(0,5,1) if c2.isError(): logger.error(msg=c2) print(c2) else: print(f"Sensor 2: {c2.getRegister(0)},{c2.getRegister(1)},{c2.getRegister(2)},{c2.getRegister(3)}, {c2.getRegister(4)}") time.sleep(2) I'm not quite sure what's misfiring... I can stream the sensor 2 data perfectly well using a GUI like QModMaster which I know uses libmodbus under the hood. Should I be instead working with the python library pylibmodbus? It requires a compiled libmodbus locally which is a bit of a headache for Windows... Am I missing a setting for pymodbus that could help? I have tried varying the pymodbus timeout which did not work. I have tried decreasing the sample rate for the flow sensor to reduce the frequecy and ensure the Arduino is free/available for Modbus requests. This did not work, in fact decreasing it made the problem worse. I have tried adding basic delays to the python code (time.sleep(2)) to slow down the Modbus requests but this had no impact on the errors. Hope someone knows what's going on as I've spent ages trawling through online sources to find the answer to no avail. If more clarification is needed from my end I can provide :) Thanks! P.S. Arduino code below for reference #include <Arduino.h> #include <ArduinoRS485.h> #include <ArduinoModbus.h> #include <Wire.h> /** * Modbus slave/server */ #define SAMPLE_RATE 50 const int ADDRESS = 0x08; // Sensor I2C Address const float SCALE_FACTOR_FLOW = 500.0; // Scale Factor for flow rate measurement const float SCALE_FACTOR_TEMP = 200.0; // Scale Factor for temperature measurement int count = 0; unsigned long startMillis; unsigned long currentMillis; enum error_types{ no_error, write_mode_error, read_error }; enum error_types error; // Protoypes int stop_continuous_measurement(); int start_continous_measurement(); void setup() { int ret; // Start Serial and I2C Serial.begin(9600); // initialize serial communication Wire.begin(); // join i2c bus (address optional for master) // Set up MODBUS if (!ModbusRTUServer.begin(0x01,9600)) { Serial.println("Could not begin ModbusRTU server..."); while(1); } // configure holding registers at address 0x00, 4 registers for data ModbusRTUServer.configureHoldingRegisters(0x00, 5); // start sensor do { // Soft reset the sensor Wire.beginTransmission(0x00); Wire.write(0x06); ret = Wire.endTransmission(); if (ret != 0) { Serial.println("Error while sending soft reset command, retrying..."); delay(500); // wait long enough for chip reset to complete } } while (ret != 0); delay(50); // wait long enough for chip reset to complete // To perform a measurement, first send 0x3608 to switch to continuous if(start_continous_measurement() !=0) { error = write_mode_error; } startMillis = millis(); } void loop() { ModbusRTUServer.poll(); uint16_t aux_value; uint16_t sensor_flow_value; uint16_t sensor_temp_value; int16_t signed_flow_value; int16_t signed_temp_value; float scaled_flow_value; float scaled_temp_value; byte aux_crc; byte sensor_flow_crc; byte sensor_temp_crc; // measurement mode (H20 calibration), then read 3x (2 bytes + 1 CRC byte) from the sensor. // To perform a IPA based measurement, send 0x3615 instead. // Check datasheet for available measurement commands. error = no_error; currentMillis = millis(); if(currentMillis - startMillis > SAMPLE_RATE){ Wire.requestFrom(ADDRESS, 9); if (Wire.available() < 9) { error = read_error; } else{ sensor_flow_value = Wire.read() << 8; // read the MSB from the sensor sensor_flow_value |= Wire.read(); // read the LSB from the sensor sensor_flow_crc = Wire.read(); sensor_temp_value = Wire.read() << 8; // read the MSB from the sensor sensor_temp_value |= Wire.read(); // read the LSB from the sensor sensor_temp_crc = Wire.read(); aux_value = Wire.read() << 8; // read the MSB from the sensor aux_value |= Wire.read(); // read the LSB from the sensor aux_crc = Wire.read(); signed_flow_value = (int16_t) sensor_flow_value; scaled_flow_value = ((float) signed_flow_value) / SCALE_FACTOR_FLOW; signed_temp_value = (int16_t) sensor_temp_value; scaled_temp_value = ((float) signed_temp_value) / SCALE_FACTOR_TEMP; // write to MODBUS registers ModbusRTUServer.holdingRegisterWrite(0, (uint16_t) count); ModbusRTUServer.holdingRegisterWrite(1, (uint16_t) scaled_temp_value*1000); ModbusRTUServer.holdingRegisterWrite(2, (uint16_t) scaled_flow_value*1000); ModbusRTUServer.holdingRegisterWrite(3,(uint16_t) aux_value); ModbusRTUServer.holdingRegisterWrite(4, (uint16_t) error); } startMillis = currentMillis; } } int start_continous_measurement() { Wire.beginTransmission(ADDRESS); Wire.write(0x36); Wire.write(0x08); return Wire.endTransmission(); } int stop_continuous_measurement() { // To stop the continuous measurement, first send 0x3FF9. Wire.beginTransmission(ADDRESS); Wire.write(0x3F); Wire.write(0xF9); return Wire.endTransmission(); }
[ "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 enforced.\nAlso see the similar story: Pymodbus : Wrong byte count in response, and the pymodbus issue.\n" ]
[ 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 plot multiple lines with plt.plot, e.g. like this import numpy as np from matplotlib import pyplot as plt # evenly sampled time at 200ms intervals t = np.arange(0., 5., 0.2) # red dashes, blue squares and green triangles plt.plot(t, t, 'r--', t, t**2, 'bs', t, t**3, 'g^') plt.show() you can use the index after plt.plot() for retrieving each single Line2D object, eg. like this line1 = plt.plot(t, t, 'r--', t, t**2, 'bs', t, t**3, 'g^')[0] line2 = plt.plot(t, t, 'r--', t, t**2, 'bs', t, t**3, 'g^')[1] and then interact with the single Line2D object, for example with x1, y1, = line1.get_data() for more methods see https://matplotlib.org/stable/api/_as_gen/matplotlib.lines.Line2D.html
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\nyou can use the index after plt.plot() for retrieving each single Line2D object, eg. like this\nline1 = plt.plot(t, t, 'r--', t, t**2, 'bs', t, t**3, 'g^')[0]\nline2 = plt.plot(t, t, 'r--', t, t**2, 'bs', t, t**3, 'g^')[1]\n\nand then interact with the single Line2D object, for example with\nx1, y1, = line1.get_data()\n\nfor more methods see https://matplotlib.org/stable/api/_as_gen/matplotlib.lines.Line2D.html\n" ]
[ 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 samples to a ridiculous huge number to get almost all the points, but it's still not 100% accurate: num_pts = 10000000 indices = arange(0, num_pts, dtype=float) + 0.5 phi = arccos(1 - 2 * indices / num_pts) theta = pi * (1 + 5 ** 0.5) * indices t_x, t_y, t_z = cos(theta) * sin(phi), sin(theta) * sin(phi), cos(phi) tmp = [(g_x0 + int(x * g_radius), g_y0 + int(y * g_radius) + g_radius, g_z0 + int(z * g_radius)) for (x, y, z) in zip(t_x, t_y, t_z)] final_coord_result = list(set(tmp)) Here's what you get with a small radius (5): How would you do this? A: This sounds like a job for raster_geometry: import raster_geometry from matplotlib import pyplot as plt # define degree of rasterization radius = 7.5 # create full sphere sphere_coords = raster_geometry.sphere(int(2*radius), radius) # make it hollow sphere_coords = raster_geometry.unfill(sphere_coords) # plot it ax = plt.figure().add_subplot(111, projection='3d') ax.scatter(*sphere_coords.nonzero()) plt.show()
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 points, but it's still not 100% accurate: num_pts = 10000000 indices = arange(0, num_pts, dtype=float) + 0.5 phi = arccos(1 - 2 * indices / num_pts) theta = pi * (1 + 5 ** 0.5) * indices t_x, t_y, t_z = cos(theta) * sin(phi), sin(theta) * sin(phi), cos(phi) tmp = [(g_x0 + int(x * g_radius), g_y0 + int(y * g_radius) + g_radius, g_z0 + int(z * g_radius)) for (x, y, z) in zip(t_x, t_y, t_z)] final_coord_result = list(set(tmp)) Here's what you get with a small radius (5): How would you do this?
[ "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_coords)\n\n# plot it\nax = plt.figure().add_subplot(111, projection='3d')\nax.scatter(*sphere_coords.nonzero())\nplt.show()\n\n" ]
[ 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: que.append(coot.right) OutPut Expected:1 2 5 3 6 4 MY_output: 1 2 5 6 3 4 A: 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 1 / \ 2 3 / \ / \ 4 5 6 7 After first iteration would have que=[2, 3], and then you would pop 3 first instead of 2, which is incorrect. Instead, you should be popping 2, popping from the left(since you are appending the new nodes to the right). So replacing coot = que.pop() with coot = que.pop(0) in your existing code should fix the issue. But note that list.pop(0) is a O(n) operation python. So I would suggest using collections.deque instead. With deque, your code can be - from collections import deque def levelOrder(root): #Write your code here que = deque() que.append(root) while que != []: coot = que.popleft() print(coot.data,end=" ") if coot.left is not None: que.append(coot.left) if coot.right is not None: que.append(coot.right)
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 4 MY_output: 1 2 5 6 3 4
[ "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 first iteration would have que=[2, 3], and then you would pop 3 first instead of 2, which is incorrect. Instead, you should be popping 2, popping from the left(since you are appending the new nodes to the right).\nSo replacing coot = que.pop() with coot = que.pop(0) in your existing code should fix the issue. But note that list.pop(0) is a O(n) operation python. So I would suggest using collections.deque instead.\nWith deque, your code can be -\nfrom collections import deque\ndef levelOrder(root):\n #Write your code here\n que = deque()\n que.append(root)\n while que != []:\n coot = que.popleft()\n print(coot.data,end=\" \")\n\n if coot.left is not None:\n que.append(coot.left)\n\n if coot.right is not None:\n que.append(coot.right)\n\n" ]
[ 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 as pd def main(): test_url_page = 'https://en.wiktionary.org/wiki/son#French' req = requests.get(test_url_page) content = req.text ipa_data = [] soup = BeautifulSoup(content, 'html.parser') french_section = soup.find('span', {'class':'mw-headline'} and {'id':'French'}) for fr_ipas in french_section.find_next('span', {'class':'IPA'}): ipa_data.append(fr_ipas) fr_ipas_all = french_section.find_all_next('span', {'class':'IPA'}) find_next only returns the first element under the french section. find_all and find_all_next returns a list of all the elements within the html. I just want the elements under the french section. There are multiple IPA keys under the french section. A: Close to your goal, but you have to check if the next elements or .find_next_siblings() has your IPA element and break the iteration until there is a <hr>, that defines the next section: french_section = soup.find('span',{'id':'French'}).parent for tag in french_section.find_next_siblings(): if tag == 'hr': break if tag.find('span', {'class':'IPA'}): ipa_data.append(tag.find('span', {'class':'IPA'}) Example from bs4 import BeautifulSoup import requests def main(): test_url_page = 'https://en.wiktionary.org/wiki/son#French' req = requests.get(test_url_page) content = req.text ipa_data = [] soup = BeautifulSoup(content, 'html.parser') french_section = soup.find('span',{'id':'French'}).parent for tag in french_section.find_next_siblings(): if tag == 'hr': break if tag.find('span', {'class':'IPA'}): ipa_data.append(tag.find('span', {'class':'IPA'})) return ipa_data main()
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.org/wiki/son#French' req = requests.get(test_url_page) content = req.text ipa_data = [] soup = BeautifulSoup(content, 'html.parser') french_section = soup.find('span', {'class':'mw-headline'} and {'id':'French'}) for fr_ipas in french_section.find_next('span', {'class':'IPA'}): ipa_data.append(fr_ipas) fr_ipas_all = french_section.find_all_next('span', {'class':'IPA'}) find_next only returns the first element under the french section. find_all and find_all_next returns a list of all the elements within the html. I just want the elements under the french section. There are multiple IPA keys under the french section.
[ "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':\n break\n if tag.find('span', {'class':'IPA'}):\n ipa_data.append(tag.find('span', {'class':'IPA'})\n\nExample\nfrom bs4 import BeautifulSoup\nimport requests\n\ndef main():\n test_url_page = 'https://en.wiktionary.org/wiki/son#French'\n req = requests.get(test_url_page)\n content = req.text\n\n ipa_data = []\n soup = BeautifulSoup(content, 'html.parser')\n french_section = soup.find('span',{'id':'French'}).parent\n for tag in french_section.find_next_siblings():\n if tag == 'hr':\n break\n if tag.find('span', {'class':'IPA'}):\n ipa_data.append(tag.find('span', {'class':'IPA'})) \n \n return ipa_data\n\nmain()\n\n" ]
[ 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.Serializer): normal_field = serializers.CharField(help_text="normal") readonly_field = serializers.CharField(read_only=True, help_text="readonly") # this is the parent one class Parent(serializers.Serializer): nested_field = Nested() In the generated docs, nested serializers in the Parameters part of the page are rendered with field data type and no hint is given about its content, they are just like other fields. Now you can see the problem there, as I would like to inform the user that there is a readonly field that should not be sent as part of the nested data but I can not see a way of doing so. The ideal would be having a model description in Data Type column, just like the Response Class section. Is there any proper way of doing so? A: 1. of everything please use drf-yasg for documentation . 2. you can find its implementation in one of my repository Kirpi and learn how to use that. 3. if you in 3. ; have question,let me know. A: Try to use drf_yasg instead, Swagger will generate the documentation for APIs, but it's not absolutely right! If you want to correct Swagger documentation, you can do it. You will need to use swagger_auto_schema decorator. Below is the sample code: from drf_yasg import openapi from drf_yasg.utils import swagger_auto_schema class ProductSuspendView(CreateAPIView): @swagger_auto_schema( tags=['dashboard'], request_body=openapi.Schema( type=openapi.TYPE_OBJECT, properties={ 'id': openapi.Schema( type=openapi.TYPE_INTEGER, description='Id', ), 'suspend_kinds': openapi.Schema( type=openapi.TYPE_ARRAY, items=openapi.Items(type=openapi.TYPE_INTEGER), description='Array suspend (Inappropriate image: 1, Insufficient information: 2, Bad language: 3) (suspend_kinds=[1,2])' ), } ), responses={ status.HTTP_200_OK: SuccessResponseSerializer, status.HTTP_400_BAD_REQUEST: ErrorResponseSerializer } ) def post(self, request, *args, **kwargs): """ Suspend a product. """ ... if success: return Response({'success': True}, status.HTTP_200_OK) return Response({'success': False}, status.HTTP_400_BAD_REQUEST)
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_field = serializers.CharField(read_only=True, help_text="readonly") # this is the parent one class Parent(serializers.Serializer): nested_field = Nested() In the generated docs, nested serializers in the Parameters part of the page are rendered with field data type and no hint is given about its content, they are just like other fields. Now you can see the problem there, as I would like to inform the user that there is a readonly field that should not be sent as part of the nested data but I can not see a way of doing so. The ideal would be having a model description in Data Type column, just like the Response Class section. Is there any proper way of doing so?
[ "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!\nIf you want to correct Swagger documentation, you can do it. You will need to use swagger_auto_schema decorator. Below is the sample code:\nfrom drf_yasg import openapi\nfrom drf_yasg.utils import swagger_auto_schema\n\nclass ProductSuspendView(CreateAPIView):\n\n @swagger_auto_schema(\n tags=['dashboard'],\n request_body=openapi.Schema(\n type=openapi.TYPE_OBJECT,\n properties={\n 'id': openapi.Schema(\n type=openapi.TYPE_INTEGER,\n description='Id',\n ),\n 'suspend_kinds': openapi.Schema(\n type=openapi.TYPE_ARRAY,\n items=openapi.Items(type=openapi.TYPE_INTEGER),\n description='Array suspend (Inappropriate image: 1, Insufficient information: 2, Bad language: 3) (suspend_kinds=[1,2])'\n ),\n }\n ),\n responses={\n status.HTTP_200_OK: SuccessResponseSerializer,\n status.HTTP_400_BAD_REQUEST: ErrorResponseSerializer\n }\n )\n def post(self, request, *args, **kwargs):\n \"\"\"\n Suspend a product.\n \"\"\"\n ...\n if success:\n return Response({'success': True}, status.HTTP_200_OK)\n\n return Response({'success': False}, status.HTTP_400_BAD_REQUEST)\n\n" ]
[ 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 credentials required. settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': env('DB_NAME'), 'USER': env('DB_USER'), 'PASSWORD': env('DB_PASSWORD'), 'HOST': env('DB_HOST'), 'PORT': env('DB_PORT'), } } What can i do to fix this issue A: I think you did wrong in database in settings.py file. You should use os.environ.get instead of env. Change this: 'NAME': env('DB_NAME'), To this: 'NAME': os.environ.get('DB_NAME'),
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 DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': env('DB_NAME'), 'USER': env('DB_USER'), 'PASSWORD': env('DB_PASSWORD'), 'HOST': env('DB_HOST'), 'PORT': env('DB_PORT'), } } What can i do to fix this issue
[ "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?") print("1 - Add an item") print("2 - Remove an item") print("3 - Print entire list") print("4 - Exit program") addtolist() def shoppinglist(): while True: choice = str(input("\nChoice: ")).lower() shopping_list = [] if choice == "1": print("=====================") print("ADD AN ITEM\n") add_item = str(input("What would you like to add? \nItem name: ")).lower() shopping_list.append(add_item) addtolist() if choice == "2": print("=====================") print("REMOVE AN ITEM\n") print("What would you like to remove") remove_item = str(input("Item name: ")).lower() shopping_list.pop(remove_item) addtolist() if choice == "3": print("=====================") print("PRINTING LIST...\n") for i in shopping_list: print(i) addtolist() if choice == "4": print("=====================") print("Terminating program...") break else: pass shoppinglist() I can't seem to find a solution for the conditional statement if choice == "3". Thank you! A: You need to declare shopping list before the while loop, because now you initialise it every time you pick an option
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 - Remove an item") print("3 - Print entire list") print("4 - Exit program") addtolist() def shoppinglist(): while True: choice = str(input("\nChoice: ")).lower() shopping_list = [] if choice == "1": print("=====================") print("ADD AN ITEM\n") add_item = str(input("What would you like to add? \nItem name: ")).lower() shopping_list.append(add_item) addtolist() if choice == "2": print("=====================") print("REMOVE AN ITEM\n") print("What would you like to remove") remove_item = str(input("Item name: ")).lower() shopping_list.pop(remove_item) addtolist() if choice == "3": print("=====================") print("PRINTING LIST...\n") for i in shopping_list: print(i) addtolist() if choice == "4": print("=====================") print("Terminating program...") break else: pass shoppinglist() I can't seem to find a solution for the conditional statement if choice == "3". Thank you!
[ "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 one format? A: Read files with pandas: csv_df = pd.read_csv('file.csv') xml_df = pd.read_xml('file.xml') xlsx_df = pd.read_excel('file.xlsx') Add tables in db with columns like in your file Add files to db xlsx_df.to_sql('table_name', engine, if_exists='replace', index=False)
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 1 A5 26/02/2022 p 1 A6 30/09/2022 s 1 Expected Dataframe : Id last_dt_of_payment Group payer_status A1 22/08/2022 x 1 A2 21/05/2022 x 0 A3 01/09/2022 y 1 A4 22/01/2022 y 0 A5 26/02/2022 p 1 A6 30/09/2022 s 1 I am trying to Overwrite the payer_status basis the Group and last_dt_of_payment. if payer_status is either x or y and the last_dt_of_payment is done within last 3 months , the payer_status to be tagged as 1 else 0 stuck with applying logic for checking last three months payment. A: EDIT: groups = ['x','y'] #convert to datetimes df['last_dt_of_payment'] = pd.to_datetime(df['last_dt_of_payment'], dayfirst=True) #create testing Period td = pd.Period('2022-09', freq='m') #get column to months periods per = df['last_dt_of_payment'].dt.to_period('m') #chain both mask m = df['Group'].isin(groups) & per.lt(td - 3) #set 0 df.loc[m, 'payer_status'] = 0 print (df) Id last_dt_of_payment Group payer_status 0 A1 2022-08-22 x 1 1 A2 2022-05-21 x 0 2 A3 2022-09-01 y 1 3 A4 2022-01-22 y 0 4 A5 2022-02-26 p 1 5 A6 2022-09-30 s 1
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 A6 30/09/2022 s 1 Expected Dataframe : Id last_dt_of_payment Group payer_status A1 22/08/2022 x 1 A2 21/05/2022 x 0 A3 01/09/2022 y 1 A4 22/01/2022 y 0 A5 26/02/2022 p 1 A6 30/09/2022 s 1 I am trying to Overwrite the payer_status basis the Group and last_dt_of_payment. if payer_status is either x or y and the last_dt_of_payment is done within last 3 months , the payer_status to be tagged as 1 else 0 stuck with applying logic for checking last three months payment.
[ "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'].isin(groups) & per.lt(td - 3)\n\n#set 0\ndf.loc[m, 'payer_status'] = 0\n\nprint (df)\n Id last_dt_of_payment Group payer_status\n0 A1 2022-08-22 x 1\n1 A2 2022-05-21 x 0\n2 A3 2022-09-01 y 1\n3 A4 2022-01-22 y 0\n4 A5 2022-02-26 p 1\n5 A6 2022-09-30 s 1\n\n" ]
[ 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 'self' is not defined def __init__( self, export=False, filename="data.geojson", position="topleft", show_geometry_on_click=True, draw_options=None, edit_options=None, ): super().__init__() self._name = "DrawControl" self.export = export self.filename = filename self.position = position self.show_geometry_on_click = show_geometry_on_click self.draw_options = draw_options or {} self.edit_options = edit_options or {} def render(self, **kwargs): super().render(**kwargs) figure = self.get_root() assert isinstance( figure, Figure ), "You cannot render this Element if it is not in a Figure." export_style = """ <style> #export { position: absolute; top: 5px; right: 10px; z-index: 999; background: white; color: black; padding: 6px; border-radius: 4px; font-family: 'Helvetica Neue'; cursor: pointer; font-size: 12px; text-decoration: none; top: 90px; } </style> """ export_button = """<a href='#' id='export'>Export</a>""" if self.export: figure.header.add_child(Element(export_style), name="export") figure.html.add_child(Element(export_button), name="export_button") I see that self has been defined already. What exactly causes this error and how to fix it? A: Minimal working example: import folium from branca.element import Element, Figure, MacroElement from jinja2 import Template from folium.elements import JSCSSMixin class Draw(JSCSSMixin, MacroElement): def __init__( self, export=False, filename="data.geojson", position="topleft", show_geometry_on_click=True, draw_options=None, edit_options=None, ): super().__init__() self._name = "DrawControl" self.export = export self.filename = filename self.position = position self.show_geometry_on_click = show_geometry_on_click self.draw_options = draw_options or {} self.edit_options = edit_options or {} def render(self, **kwargs): super().render(**kwargs) figure = self.get_root() assert isinstance( figure, Figure ), "You cannot render this Element if it is not in a Figure." export_style = """ <style> #export { position: absolute; top: 5px; right: 10px; z-index: 999; background: white; color: black; padding: 6px; border-radius: 4px; font-family: 'Helvetica Neue'; cursor: pointer; font-size: 12px; text-decoration: none; top: 90px; } </style> """ export_button = """<a href='#' id='export'>Export</a>""" if self.export: figure.header.add_child(Element(export_style), name="export") figure.html.add_child(Element(export_button), name="export_button") m = folium.Map(location=[38,35], zoom_start=10) draw = Draw(export=True) draw.add_to(m) m Then, you can edit class Draw as you desire.
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, export=False, filename="data.geojson", position="topleft", show_geometry_on_click=True, draw_options=None, edit_options=None, ): super().__init__() self._name = "DrawControl" self.export = export self.filename = filename self.position = position self.show_geometry_on_click = show_geometry_on_click self.draw_options = draw_options or {} self.edit_options = edit_options or {} def render(self, **kwargs): super().render(**kwargs) figure = self.get_root() assert isinstance( figure, Figure ), "You cannot render this Element if it is not in a Figure." export_style = """ <style> #export { position: absolute; top: 5px; right: 10px; z-index: 999; background: white; color: black; padding: 6px; border-radius: 4px; font-family: 'Helvetica Neue'; cursor: pointer; font-size: 12px; text-decoration: none; top: 90px; } </style> """ export_button = """<a href='#' id='export'>Export</a>""" if self.export: figure.header.add_child(Element(export_style), name="export") figure.html.add_child(Element(export_button), name="export_button") I see that self has been defined already. What exactly causes this error and how to fix it?
[ "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 position=\"topleft\",\n show_geometry_on_click=True,\n draw_options=None,\n edit_options=None,\n ):\n super().__init__()\n self._name = \"DrawControl\"\n self.export = export\n self.filename = filename\n self.position = position\n self.show_geometry_on_click = show_geometry_on_click\n self.draw_options = draw_options or {}\n self.edit_options = edit_options or {}\n\n def render(self, **kwargs):\n super().render(**kwargs)\n\n figure = self.get_root()\n assert isinstance(\n figure, Figure\n ), \"You cannot render this Element if it is not in a Figure.\"\n\n export_style = \"\"\"\n <style>\n #export {\n position: absolute;\n top: 5px;\n right: 10px;\n z-index: 999;\n background: white;\n color: black;\n padding: 6px;\n border-radius: 4px;\n font-family: 'Helvetica Neue';\n cursor: pointer;\n font-size: 12px;\n text-decoration: none;\n top: 90px;\n }\n </style>\n \"\"\"\n export_button = \"\"\"<a href='#' id='export'>Export</a>\"\"\"\n if self.export:\n figure.header.add_child(Element(export_style), name=\"export\")\n figure.html.add_child(Element(export_button), name=\"export_button\")\n\n \nm = folium.Map(location=[38,35], zoom_start=10)\ndraw = Draw(export=True)\ndraw.add_to(m)\n\nm\n\nThen, you can edit class Draw as you desire.\n" ]
[ 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 first line of my code is import os, os.path. This is my code for it: parent_path = os.path.abspath(os.path.join(os.getcwd(), os.pardir)) Here is the full code: import pandas as pd import os from os import path parent_path = os.path.abspath(os.path.join(os.getcwd(), os.pardir)) print(os.path.abspath(os.path.join(os.getcwd(), os.pardir))) Thanks to everyone :) I have tried restarting VS Code, the computer and that sort of things, changing import os, os.path to import os and in the next line from os import path and stills the same.
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 it: parent_path = os.path.abspath(os.path.join(os.getcwd(), os.pardir)) Here is the full code: import pandas as pd import os from os import path parent_path = os.path.abspath(os.path.join(os.getcwd(), os.pardir)) print(os.path.abspath(os.path.join(os.getcwd(), os.pardir))) Thanks to everyone :) I have tried restarting VS Code, the computer and that sort of things, changing import os, os.path to import os and in the next line from os import path and stills the same.
[]
[]
[ "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 running the command py -m pip list and see if os is there.\nIf this is on Windows computer, then a place to start troubleshooting is to check if python is added to your $PATH correctly.\n" ]
[ -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-%m-%d") df["year"] = df["date"].dt.year df["month"] = df["date"].dt.month df.groupby(by = "year", as_index = False).agg({"month":pd.Series.nunique}) year month 2015 3 2016 12 2017 12 2018 12 2019 12 2020 12 2021 12 2022 9 Notice that with this data, 2015 and 2022 are not full years. My thinking was that because I have 84 months worth of data in total (3 + (6*12) + 9 = 84), I could split the data into four groups so that each group would have approximately 21 months worth of data in total 84 / 4 = 21. To do this, I would first begin with the earliest date in my data set which is 2015-10-02. With this earliest data I would add on 21 months: from dateutil.relativedelta import relativedelta min_date = df["date"].min().date() print([min_date, min_date + relativedelta(months = 21)] #output [datetime.date(2015, 10, 2), datetime.date(2017, 7, 2)] This date range would constitute the first bin which the first group would fall into The second group would fall into a date range where the minimum date would be one day more than the maximum date of the previous group's date range: "2017-07-02" + relativedelta(days = 1) = "2017-07-03" This would ensure that the bins of the different groups do not overlap. The last group would have a bit less data in it as it would include data up till the latest date in the entire dataset which is 2022-09-30 Overall, the date range bins for the different groups would look something like this Group Date Range A "2015-10-02", "2017-07-02" B "2017-07-03", "2019-04-03" C "2019-04-04", "2021-01-04" D "2021-01-05", "2022-9-30" I know that I could find these date ranges manually and use them to filter the data set to produce the groups with np.select but this isn't very efficient. df["Group"] = np.select( condlist = [ (df["date"] >= "2015-10-02") & (df["date"] <= "2017-07-02"), (df["date"] >= "2017-07-03") & (df["date"] <= "2019-04-03"), (df["date"] >= "2019-04-04") & (df["date"] <= "2021-01-04"), (df["date"] >= "2021-01-05") & (df["date"] <= "2022-09-30") ], choicelist = ["A", "B", "C", "D"] ) Surely there must be a way to find these values (in the way that I want them) without having to find them manually A: You may want to take a look at pd.cut. # toy data df = pd.DataFrame(pd.date_range('2020-01-01', '2022-01-01'), columns = ['date']) date 0 2020-01-01 1 2020-01-02 2 2020-01-03 3 2020-01-04 4 2020-01-05 .. ... You can generate the labels and boundaries for the bins. from numpy import datetime64 bin_labels = [1, 2, 3, 4] cut_bins = [datetime64('2019-12-31'), datetime64('2020-04-01'), datetime64('2020-12-31'), datetime64('2021-09-01'), datetime64('2022-01-01')] And save the bins into a new column. df['cut'] = pd.cut(df['date'], bins = cut_bins, labels = bin_labels] date cut 0 2020-01-01 1 1 2020-01-02 1 2 2020-01-03 1 3 2020-01-04 1 4 2020-01-05 1 .. ... .. 727 2021-12-28 4 728 2021-12-29 4 729 2021-12-30 4 730 2021-12-31 4 731 2022-01-01 4 Hope it helps. A: I have found a way which I think works (for those who may be interested in binning date-time values in the future) - assume the data is the same as given in the question description: from dateutil.relativedelta import relativedelta import numpy as np dates = [] start = df["date"].min().date() dates.append(np.datetime64(start)) while start <= df["date"].max().date(): start = start + relativedetla(months = 21) dates.append(np.datetime64(start)) df["Group"] = pd.cut( df["date"], bins = dates, labels = ["A", "B", "C", "D"], right = False #right = False ensures no group overlap in date values )
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["month"] = df["date"].dt.month df.groupby(by = "year", as_index = False).agg({"month":pd.Series.nunique}) year month 2015 3 2016 12 2017 12 2018 12 2019 12 2020 12 2021 12 2022 9 Notice that with this data, 2015 and 2022 are not full years. My thinking was that because I have 84 months worth of data in total (3 + (6*12) + 9 = 84), I could split the data into four groups so that each group would have approximately 21 months worth of data in total 84 / 4 = 21. To do this, I would first begin with the earliest date in my data set which is 2015-10-02. With this earliest data I would add on 21 months: from dateutil.relativedelta import relativedelta min_date = df["date"].min().date() print([min_date, min_date + relativedelta(months = 21)] #output [datetime.date(2015, 10, 2), datetime.date(2017, 7, 2)] This date range would constitute the first bin which the first group would fall into The second group would fall into a date range where the minimum date would be one day more than the maximum date of the previous group's date range: "2017-07-02" + relativedelta(days = 1) = "2017-07-03" This would ensure that the bins of the different groups do not overlap. The last group would have a bit less data in it as it would include data up till the latest date in the entire dataset which is 2022-09-30 Overall, the date range bins for the different groups would look something like this Group Date Range A "2015-10-02", "2017-07-02" B "2017-07-03", "2019-04-03" C "2019-04-04", "2021-01-04" D "2021-01-05", "2022-9-30" I know that I could find these date ranges manually and use them to filter the data set to produce the groups with np.select but this isn't very efficient. df["Group"] = np.select( condlist = [ (df["date"] >= "2015-10-02") & (df["date"] <= "2017-07-02"), (df["date"] >= "2017-07-03") & (df["date"] <= "2019-04-03"), (df["date"] >= "2019-04-04") & (df["date"] <= "2021-01-04"), (df["date"] >= "2021-01-05") & (df["date"] <= "2022-09-30") ], choicelist = ["A", "B", "C", "D"] ) Surely there must be a way to find these values (in the way that I want them) without having to find them manually
[ "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 numpy import datetime64\nbin_labels = [1, 2, 3, 4]\ncut_bins = [datetime64('2019-12-31'), datetime64('2020-04-01'), datetime64('2020-12-31'), datetime64('2021-09-01'), datetime64('2022-01-01')]\n\nAnd save the bins into a new column.\ndf['cut'] = pd.cut(df['date'], bins = cut_bins, labels = bin_labels]\n\n date cut\n0 2020-01-01 1\n1 2020-01-02 1\n2 2020-01-03 1\n3 2020-01-04 1\n4 2020-01-05 1\n.. ... ..\n727 2021-12-28 4\n728 2021-12-29 4\n729 2021-12-30 4\n730 2021-12-31 4\n731 2022-01-01 4\n\nHope it helps.\n", "I have found a way which I think works (for those who may be interested in binning date-time values in the future) - assume the data is the same as given in the question description:\nfrom dateutil.relativedelta import relativedelta\nimport numpy as np\n\ndates = []\nstart = df[\"date\"].min().date()\ndates.append(np.datetime64(start))\nwhile start <= df[\"date\"].max().date():\n start = start + relativedetla(months = 21)\n dates.append(np.datetime64(start))\n\ndf[\"Group\"] = pd.cut(\n df[\"date\"], bins = dates,\n labels = [\"A\", \"B\", \"C\", \"D\"],\n right = False #right = False ensures no group overlap in date values\n)\n\n" ]
[ 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 multiple sheets. For Ex: In the master file, the formula is "=LEFT(B11, FIND(" ", B11,1))" for row 11, however, this becomes the first row in the new split file but the formula is still referring to row 11 which gives "#VALUE" error in the new file. Any ideas on how to resolve this one? I have tried achieving this using pandas and openpyxl and failed, PFB the code. To Load the file wb = load_workbook(filepath) sheets = wb.get_sheet_names() sheet_name = wb[sheets[0]] master_df = pd.DataFrame(sheet_name.values, index=False) master_df.columns = master_df.iloc[0] master_df = master_df[1:] print(master_df) To split amd export the file temp_df = master_df[master_df['Filter Column'] == filter_criteria] sp.export_file(temp_df, output_path + "/" + <"output file name">) A: def update_formula(df: pd.DataFrame, formula_col): ''' Function to update formulas for each Manager :param df: DataFrame for one specific manager. ''' for _col in formula_col: col_alpha = formula_col[_col][0] formula = formula_col[_col][1] index = 2 for ind, row in df.iterrows(): df.at[ind, _col] = Translator(formula, origin=col_alpha + '2').translate_formula(col_alpha + str(index)) index = index + 1 Here I am giving DataFrame and a list of columns which have formula in them as input. Later I am iterating over DataFrame and updating formula for each cell in that column using OpenpyXl Translator method. This is the best solution I have figured yet. Please let me know if there is a better way.
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(B11, FIND(" ", B11,1))" for row 11, however, this becomes the first row in the new split file but the formula is still referring to row 11 which gives "#VALUE" error in the new file. Any ideas on how to resolve this one? I have tried achieving this using pandas and openpyxl and failed, PFB the code. To Load the file wb = load_workbook(filepath) sheets = wb.get_sheet_names() sheet_name = wb[sheets[0]] master_df = pd.DataFrame(sheet_name.values, index=False) master_df.columns = master_df.iloc[0] master_df = master_df[1:] print(master_df) To split amd export the file temp_df = master_df[master_df['Filter Column'] == filter_criteria] sp.export_file(temp_df, output_path + "/" + <"output file name">)
[ "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 ind, row in df.iterrows():\n df.at[ind, _col] = Translator(formula, origin=col_alpha + '2').translate_formula(col_alpha + str(index))\n index = index + 1\n\nHere I am giving DataFrame and a list of columns which have formula in them as input. Later I am iterating over DataFrame and updating formula for each cell in that column using OpenpyXl Translator method.\nThis is the best solution I have figured yet.\nPlease let me know if there is a better way.\n" ]
[ 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 'assign' Here is my code for pruning #pruning import tensorflow_model_optimization as tfmot import numpy as np origModelFile = 'modeltest.h5' model = tf.keras.models.load_model(origModelFile) prune_low_magnitude = tfmot.sparsity.keras.prune_low_magnitude epochs = 15 batch_size = 2048 validation_split = 0.1 num_images = x_train.shape[0] * (1 - validation_split) end_step = np.ceil(num_images / batch_size).astype(np.int32) * epochs pruning_params = { 'pruning_schedule': tfmot.sparsity.keras.PolynomialDecay(initial_sparsity=.95, final_sparsity=.8, begin_step=0, end_step=end_step) } model_for_pruning = prune_low_magnitude(model, **pruning_params) #this line gives the error model_for_pruning.compile(optimizer='adam', loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True), metrics=['accuracy']) pruned_model = tfmot.sparsity.keras.strip_pruning(model_for_pruning) pruned_model.summary() And here is the full stack trace of the error --------------------------------------------------------------------------- AttributeError Traceback (most recent call last) ~\AppData\Local\Temp\ipykernel_33564\3560105584.py in <module> 13 end_step=end_step) 14 } ---> 15 model_for_pruning = prune_low_magnitude(model, **pruning_params) 16 17 model_for_pruning.compile(optimizer='adam', A:\Anaconda\lib\site-packages\tensorflow_model_optimization\python\core\keras\metrics.py in inner(*args, **kwargs) 72 except Exception as error: 73 self.bool_gauge.get_cell(MonitorBoolGauge._FAILURE_LABEL).set(True) ---> 74 raise error 75 76 if self.bool_gauge: A:\Anaconda\lib\site-packages\tensorflow_model_optimization\python\core\keras\metrics.py in inner(*args, **kwargs) 67 def inner(*args, **kwargs): 68 try: ---> 69 results = func(*args, **kwargs) 70 self.bool_gauge.get_cell(MonitorBoolGauge._SUCCESS_LABEL).set(True) 71 return results A:\Anaconda\lib\site-packages\tensorflow_model_optimization\python\core\sparsity\keras\prune.py in prune_low_magnitude(to_prune, pruning_schedule, block_size, block_pooling_type, pruning_policy, sparsity_m_by_n, **kwargs) 208 if pruning_policy: 209 pruning_policy.ensure_model_supports_pruning(to_prune) --> 210 return _add_pruning_wrapper(to_prune) 211 elif is_keras_layer: 212 params.update(kwargs) A:\Anaconda\lib\site-packages\tensorflow_model_optimization\python\core\sparsity\keras\prune.py in _add_pruning_wrapper(layer) 179 raise ValueError('Subclassed models are not supported currently.') 180 --> 181 return keras.models.clone_model( 182 layer, input_tensors=None, clone_function=_add_pruning_wrapper) 183 if isinstance(layer, pruning_wrapper.PruneLowMagnitude): A:\Anaconda\lib\site-packages\keras\models\cloning.py in clone_model(model, input_tensors, clone_function) 446 model, input_tensors=input_tensors, layer_fn=clone_function) 447 else: --> 448 return _clone_functional_model( 449 model, input_tensors=input_tensors, layer_fn=clone_function) 450 A:\Anaconda\lib\site-packages\keras\models\cloning.py in _clone_functional_model(model, input_tensors, layer_fn) 187 # Reconstruct model from the config, using the cloned layers. 188 input_tensors, output_tensors, created_layers = ( --> 189 functional.reconstruct_from_config(model_configs, 190 created_layers=created_layers)) 191 metrics_names = model.metrics_names A:\Anaconda\lib\site-packages\keras\engine\functional.py in reconstruct_from_config(config, custom_objects, created_layers) 1310 while layer_nodes: 1311 node_data = layer_nodes[0] -> 1312 if process_node(layer, node_data): 1313 layer_nodes.pop(0) 1314 else: A:\Anaconda\lib\site-packages\keras\engine\functional.py in process_node(layer, node_data) 1254 input_tensors = ( 1255 base_layer_utils.unnest_if_single_tensor(input_tensors)) -> 1256 output_tensors = layer(input_tensors, **kwargs) 1257 1258 # Update node index map. A:\Anaconda\lib\site-packages\keras\utils\traceback_utils.py in error_handler(*args, **kwargs) 65 except Exception as e: # pylint: disable=broad-except 66 filtered_tb = _process_traceback_frames(e.__traceback__) ---> 67 raise e.with_traceback(filtered_tb) from None 68 finally: 69 del filtered_tb A:\Anaconda\lib\site-packages\tensorflow_model_optimization\python\core\sparsity\keras\pruning_wrapper.py in tf__call(self, inputs, training, **kwargs) 71 update_mask = ag__.converted_call(ag__.ld(utils).smart_cond, (ag__.ld(training), ag__.ld(add_update), ag__.ld(no_op)), None, fscope) 72 ag__.converted_call(ag__.ld(self).add_update, (ag__.ld(update_mask),), None, fscope) ---> 73 ag__.converted_call(ag__.ld(self).add_update, (ag__.converted_call(ag__.ld(self).pruning_obj.weight_mask_op, (), None, fscope),), None, fscope) 74 75 def get_state_1(): A:\Anaconda\lib\site-packages\tensorflow_model_optimization\python\core\sparsity\keras\pruning_impl.py in tf__weight_mask_op(self) 11 try: 12 do_return = True ---> 13 retval_ = ag__.converted_call(ag__.ld(tf).group, (ag__.converted_call(ag__.ld(self)._weight_assign_objs, (), None, fscope),), None, fscope) 14 except: 15 do_return = False A:\Anaconda\lib\site-packages\tensorflow_model_optimization\python\core\sparsity\keras\pruning_impl.py in tf___weight_assign_objs(self) 122 _ = ag__.Undefined('_') 123 masked_weight = ag__.Undefined('masked_weight') --> 124 ag__.if_stmt(ag__.converted_call(ag__.ld(tf).distribute.get_replica_context, (), None, fscope), if_body_1, else_body_1, get_state_4, set_state_4, (), 0) 125 try: 126 do_return = True A:\Anaconda\lib\site-packages\tensorflow_model_optimization\python\core\sparsity\keras\pruning_impl.py in if_body_1() 98 def else_body(): 99 pass --> 100 ag__.if_stmt(ag__.ld(values_and_vars), if_body, else_body, get_state_2, set_state_2, (), 0) 101 102 def else_body_1(): A:\Anaconda\lib\site-packages\tensorflow_model_optimization\python\core\sparsity\keras\pruning_impl.py in if_body() 94 95 def if_body(): ---> 96 ag__.converted_call(ag__.ld(assign_objs).append, (ag__.converted_call(ag__.converted_call(ag__.ld(tf).distribute.get_replica_context, (), None, fscope).merge_call, (ag__.ld(update_fn),), dict(args=(ag__.ld(values_and_vars),)), fscope),), None, fscope) 97 98 def else_body(): A:\Anaconda\lib\site-packages\tensorflow_model_optimization\python\core\sparsity\keras\pruning_impl.py in update_fn(distribution, values_and_vars) 52 var = ag__.Undefined('var') 53 value = ag__.Undefined('value') ---> 54 ag__.for_stmt(ag__.ld(values_and_vars), None, loop_body, get_state, set_state, (), {'iterate_names': '(value, var)'}) 55 try: 56 do_return_1 = True A:\Anaconda\lib\site-packages\tensorflow_model_optimization\python\core\sparsity\keras\pruning_impl.py in loop_body(itr) 49 def loop_body(itr): 50 (value, var) = itr ---> 51 ag__.converted_call(ag__.ld(update_objs).append, (ag__.converted_call(ag__.ld(distribution).extended.update, (ag__.ld(var), ag__.ld(update_var)), dict(args=(ag__.ld(value),)), fscope_1),), None, fscope_1) 52 var = ag__.Undefined('var') 53 value = ag__.Undefined('value') A:\Anaconda\lib\site-packages\tensorflow_model_optimization\python\core\sparsity\keras\pruning_impl.py in update_var(variable, reduced_value) 34 try: 35 do_return_2 = True ---> 36 retval__2 = ag__.converted_call(ag__.ld(tf_compat).assign, (ag__.ld(variable), ag__.ld(reduced_value)), None, fscope_2) 37 except: 38 do_return_2 = False A:\Anaconda\lib\site-packages\tensorflow_model_optimization\python\core\keras\compat.py in tf__assign(ref, value, name) 34 do_return = False 35 raise ---> 36 ag__.if_stmt(ag__.converted_call(ag__.ld(hasattr), (ag__.ld(tf), 'assign'), None, fscope), if_body, else_body, get_state, set_state, ('do_return', 'retval_'), 2) 37 return fscope.ret(retval_, do_return) 38 return tf__assign A:\Anaconda\lib\site-packages\tensorflow_model_optimization\python\core\keras\compat.py in else_body() 30 try: 31 do_return = True ---> 32 retval_ = ag__.converted_call(ag__.ld(ref).assign, (ag__.ld(value),), dict(name=ag__.ld(name)), fscope) 33 except: 34 do_return = False AttributeError: Exception encountered when calling layer "prune_low_magnitude_conv2d" (type PruneLowMagnitude). in user code: File "A:\Anaconda\lib\site-packages\tensorflow_model_optimization\python\core\sparsity\keras\pruning_wrapper.py", line 288, in call * self.add_update(self.pruning_obj.weight_mask_op()) File "A:\Anaconda\lib\site-packages\tensorflow_model_optimization\python\core\sparsity\keras\pruning_impl.py", line 254, in weight_mask_op * return tf.group(self._weight_assign_objs()) File "A:\Anaconda\lib\site-packages\tensorflow_model_optimization\python\core\sparsity\keras\pruning_impl.py", line 225, in update_var * return tf_compat.assign(variable, reduced_value) File "A:\Anaconda\lib\site-packages\tensorflow_model_optimization\python\core\keras\compat.py", line 28, in assign * return ref.assign(value, name=name) AttributeError: 'tensorflow.python.framework.ops.EagerTensor' object has no attribute 'assign' Call arguments received by layer "prune_low_magnitude_conv2d" (type PruneLowMagnitude): • inputs=tf.Tensor(shape=(None, 14, 8, 8), dtype=float32) • training=False • kwargs=<class 'inspect._empty'> I was attempting to follow the example here but with my own model A: ##Pruning base_model = tf.keras.models.load_model('modelclustored2.h5') base_model.load_weights(pretrained_weights) # optional but recommended. model_for_pruning = tfmot.sparsity.keras.prune_low_magnitude(base_model) callbacks = [ tfmot.sparsity.keras.UpdatePruningStep(), # Log sparsity and other metrics in Tensorboard. #tfmot.sparsity.keras.PruningSummaries(log_dir=log_dir), callbacks.ReduceLROnPlateau(monitor='loss', patience=10), callbacks.EarlyStopping(monitor='loss', patience=15, min_delta=1e-4) ] model_for_pruning.compile(optimizer=optimizers.Adam(5e-4), loss='mean_squared_error', metrics=['mae', 'mse']) model_for_pruning.summary() Just needed to go about things in a different way
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 as np origModelFile = 'modeltest.h5' model = tf.keras.models.load_model(origModelFile) prune_low_magnitude = tfmot.sparsity.keras.prune_low_magnitude epochs = 15 batch_size = 2048 validation_split = 0.1 num_images = x_train.shape[0] * (1 - validation_split) end_step = np.ceil(num_images / batch_size).astype(np.int32) * epochs pruning_params = { 'pruning_schedule': tfmot.sparsity.keras.PolynomialDecay(initial_sparsity=.95, final_sparsity=.8, begin_step=0, end_step=end_step) } model_for_pruning = prune_low_magnitude(model, **pruning_params) #this line gives the error model_for_pruning.compile(optimizer='adam', loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True), metrics=['accuracy']) pruned_model = tfmot.sparsity.keras.strip_pruning(model_for_pruning) pruned_model.summary() And here is the full stack trace of the error --------------------------------------------------------------------------- AttributeError Traceback (most recent call last) ~\AppData\Local\Temp\ipykernel_33564\3560105584.py in <module> 13 end_step=end_step) 14 } ---> 15 model_for_pruning = prune_low_magnitude(model, **pruning_params) 16 17 model_for_pruning.compile(optimizer='adam', A:\Anaconda\lib\site-packages\tensorflow_model_optimization\python\core\keras\metrics.py in inner(*args, **kwargs) 72 except Exception as error: 73 self.bool_gauge.get_cell(MonitorBoolGauge._FAILURE_LABEL).set(True) ---> 74 raise error 75 76 if self.bool_gauge: A:\Anaconda\lib\site-packages\tensorflow_model_optimization\python\core\keras\metrics.py in inner(*args, **kwargs) 67 def inner(*args, **kwargs): 68 try: ---> 69 results = func(*args, **kwargs) 70 self.bool_gauge.get_cell(MonitorBoolGauge._SUCCESS_LABEL).set(True) 71 return results A:\Anaconda\lib\site-packages\tensorflow_model_optimization\python\core\sparsity\keras\prune.py in prune_low_magnitude(to_prune, pruning_schedule, block_size, block_pooling_type, pruning_policy, sparsity_m_by_n, **kwargs) 208 if pruning_policy: 209 pruning_policy.ensure_model_supports_pruning(to_prune) --> 210 return _add_pruning_wrapper(to_prune) 211 elif is_keras_layer: 212 params.update(kwargs) A:\Anaconda\lib\site-packages\tensorflow_model_optimization\python\core\sparsity\keras\prune.py in _add_pruning_wrapper(layer) 179 raise ValueError('Subclassed models are not supported currently.') 180 --> 181 return keras.models.clone_model( 182 layer, input_tensors=None, clone_function=_add_pruning_wrapper) 183 if isinstance(layer, pruning_wrapper.PruneLowMagnitude): A:\Anaconda\lib\site-packages\keras\models\cloning.py in clone_model(model, input_tensors, clone_function) 446 model, input_tensors=input_tensors, layer_fn=clone_function) 447 else: --> 448 return _clone_functional_model( 449 model, input_tensors=input_tensors, layer_fn=clone_function) 450 A:\Anaconda\lib\site-packages\keras\models\cloning.py in _clone_functional_model(model, input_tensors, layer_fn) 187 # Reconstruct model from the config, using the cloned layers. 188 input_tensors, output_tensors, created_layers = ( --> 189 functional.reconstruct_from_config(model_configs, 190 created_layers=created_layers)) 191 metrics_names = model.metrics_names A:\Anaconda\lib\site-packages\keras\engine\functional.py in reconstruct_from_config(config, custom_objects, created_layers) 1310 while layer_nodes: 1311 node_data = layer_nodes[0] -> 1312 if process_node(layer, node_data): 1313 layer_nodes.pop(0) 1314 else: A:\Anaconda\lib\site-packages\keras\engine\functional.py in process_node(layer, node_data) 1254 input_tensors = ( 1255 base_layer_utils.unnest_if_single_tensor(input_tensors)) -> 1256 output_tensors = layer(input_tensors, **kwargs) 1257 1258 # Update node index map. A:\Anaconda\lib\site-packages\keras\utils\traceback_utils.py in error_handler(*args, **kwargs) 65 except Exception as e: # pylint: disable=broad-except 66 filtered_tb = _process_traceback_frames(e.__traceback__) ---> 67 raise e.with_traceback(filtered_tb) from None 68 finally: 69 del filtered_tb A:\Anaconda\lib\site-packages\tensorflow_model_optimization\python\core\sparsity\keras\pruning_wrapper.py in tf__call(self, inputs, training, **kwargs) 71 update_mask = ag__.converted_call(ag__.ld(utils).smart_cond, (ag__.ld(training), ag__.ld(add_update), ag__.ld(no_op)), None, fscope) 72 ag__.converted_call(ag__.ld(self).add_update, (ag__.ld(update_mask),), None, fscope) ---> 73 ag__.converted_call(ag__.ld(self).add_update, (ag__.converted_call(ag__.ld(self).pruning_obj.weight_mask_op, (), None, fscope),), None, fscope) 74 75 def get_state_1(): A:\Anaconda\lib\site-packages\tensorflow_model_optimization\python\core\sparsity\keras\pruning_impl.py in tf__weight_mask_op(self) 11 try: 12 do_return = True ---> 13 retval_ = ag__.converted_call(ag__.ld(tf).group, (ag__.converted_call(ag__.ld(self)._weight_assign_objs, (), None, fscope),), None, fscope) 14 except: 15 do_return = False A:\Anaconda\lib\site-packages\tensorflow_model_optimization\python\core\sparsity\keras\pruning_impl.py in tf___weight_assign_objs(self) 122 _ = ag__.Undefined('_') 123 masked_weight = ag__.Undefined('masked_weight') --> 124 ag__.if_stmt(ag__.converted_call(ag__.ld(tf).distribute.get_replica_context, (), None, fscope), if_body_1, else_body_1, get_state_4, set_state_4, (), 0) 125 try: 126 do_return = True A:\Anaconda\lib\site-packages\tensorflow_model_optimization\python\core\sparsity\keras\pruning_impl.py in if_body_1() 98 def else_body(): 99 pass --> 100 ag__.if_stmt(ag__.ld(values_and_vars), if_body, else_body, get_state_2, set_state_2, (), 0) 101 102 def else_body_1(): A:\Anaconda\lib\site-packages\tensorflow_model_optimization\python\core\sparsity\keras\pruning_impl.py in if_body() 94 95 def if_body(): ---> 96 ag__.converted_call(ag__.ld(assign_objs).append, (ag__.converted_call(ag__.converted_call(ag__.ld(tf).distribute.get_replica_context, (), None, fscope).merge_call, (ag__.ld(update_fn),), dict(args=(ag__.ld(values_and_vars),)), fscope),), None, fscope) 97 98 def else_body(): A:\Anaconda\lib\site-packages\tensorflow_model_optimization\python\core\sparsity\keras\pruning_impl.py in update_fn(distribution, values_and_vars) 52 var = ag__.Undefined('var') 53 value = ag__.Undefined('value') ---> 54 ag__.for_stmt(ag__.ld(values_and_vars), None, loop_body, get_state, set_state, (), {'iterate_names': '(value, var)'}) 55 try: 56 do_return_1 = True A:\Anaconda\lib\site-packages\tensorflow_model_optimization\python\core\sparsity\keras\pruning_impl.py in loop_body(itr) 49 def loop_body(itr): 50 (value, var) = itr ---> 51 ag__.converted_call(ag__.ld(update_objs).append, (ag__.converted_call(ag__.ld(distribution).extended.update, (ag__.ld(var), ag__.ld(update_var)), dict(args=(ag__.ld(value),)), fscope_1),), None, fscope_1) 52 var = ag__.Undefined('var') 53 value = ag__.Undefined('value') A:\Anaconda\lib\site-packages\tensorflow_model_optimization\python\core\sparsity\keras\pruning_impl.py in update_var(variable, reduced_value) 34 try: 35 do_return_2 = True ---> 36 retval__2 = ag__.converted_call(ag__.ld(tf_compat).assign, (ag__.ld(variable), ag__.ld(reduced_value)), None, fscope_2) 37 except: 38 do_return_2 = False A:\Anaconda\lib\site-packages\tensorflow_model_optimization\python\core\keras\compat.py in tf__assign(ref, value, name) 34 do_return = False 35 raise ---> 36 ag__.if_stmt(ag__.converted_call(ag__.ld(hasattr), (ag__.ld(tf), 'assign'), None, fscope), if_body, else_body, get_state, set_state, ('do_return', 'retval_'), 2) 37 return fscope.ret(retval_, do_return) 38 return tf__assign A:\Anaconda\lib\site-packages\tensorflow_model_optimization\python\core\keras\compat.py in else_body() 30 try: 31 do_return = True ---> 32 retval_ = ag__.converted_call(ag__.ld(ref).assign, (ag__.ld(value),), dict(name=ag__.ld(name)), fscope) 33 except: 34 do_return = False AttributeError: Exception encountered when calling layer "prune_low_magnitude_conv2d" (type PruneLowMagnitude). in user code: File "A:\Anaconda\lib\site-packages\tensorflow_model_optimization\python\core\sparsity\keras\pruning_wrapper.py", line 288, in call * self.add_update(self.pruning_obj.weight_mask_op()) File "A:\Anaconda\lib\site-packages\tensorflow_model_optimization\python\core\sparsity\keras\pruning_impl.py", line 254, in weight_mask_op * return tf.group(self._weight_assign_objs()) File "A:\Anaconda\lib\site-packages\tensorflow_model_optimization\python\core\sparsity\keras\pruning_impl.py", line 225, in update_var * return tf_compat.assign(variable, reduced_value) File "A:\Anaconda\lib\site-packages\tensorflow_model_optimization\python\core\keras\compat.py", line 28, in assign * return ref.assign(value, name=name) AttributeError: 'tensorflow.python.framework.ops.EagerTensor' object has no attribute 'assign' Call arguments received by layer "prune_low_magnitude_conv2d" (type PruneLowMagnitude): • inputs=tf.Tensor(shape=(None, 14, 8, 8), dtype=float32) • training=False • kwargs=<class 'inspect._empty'> I was attempting to follow the example here but with my own model
[ "##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 metrics in Tensorboard.\n #tfmot.sparsity.keras.PruningSummaries(log_dir=log_dir),\n callbacks.ReduceLROnPlateau(monitor='loss', patience=10),\n callbacks.EarlyStopping(monitor='loss', patience=15, min_delta=1e-4)\n \n]\n\nmodel_for_pruning.compile(optimizer=optimizers.Adam(5e-4), loss='mean_squared_error', metrics=['mae', 'mse'])\n\n\nmodel_for_pruning.summary()\n\nJust needed to go about things in a different way\n" ]
[ 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 definition, if I remove "backref="documents" for the counterparties relationship I get the same error, but on the next line as it tries to add the document. Database Model: documents_counterparties = Table( "documents_counterparties", Base.metadata, Column("document_id", ForeignKey("documents.id"), primary_key=True), Column("counterparty_id", ForeignKey( "counterparties.id"), primary_key=True) ) class Document(Base): __tablename__ = "documents" id = Column(Integer, primary_key=True, index=True) name = Column(String, index=True) start_date = Column(Date) end_date = Column(Date) owner_id = Column(Integer, ForeignKey("users.id")) owner = relationship("User", back_populates="documents") counterparties = relationship( "Counterparty", secondary=documents_counterparties, backref="documents" ) Resolver: def create_document(db: Session, document: DocumentCreate, user_id: int): db_document = models.Document(**document.dict(), owner_id=user_id) #<- errors here db.add(db_document) db.commit() db.refresh(db_document) return db_document EDIT: DocumentCreate class DocumentBase(BaseModel): name: str start_date: datetime.date end_date: datetime.date class DocumentCreate(DocumentBase): counterparties: "list[CounterpartyClean]" A: As @MatsLindh alluded to the issue is with types. The solution is here: How to use nested pydantic models for sqlalchemy in a flexible way Edit to include solution used: Credit to Daan Beverdam: I gave every nested pydantic model a Meta class containing the corresponding SQLAlchemy model. Like so: from pydantic import BaseModel from models import ChildDBModel, ParentDBModel class ChildModel(BaseModel): some_attribute: str = 'value' class Meta: orm_model = ChildDBModel class ParentModel(BaseModel): child: ChildModel That allowed me to write a generic function that loops through the pydantic object and transforms submodels into SQLAlchemy models: def is_pydantic(obj: object): """ Checks whether an object is pydantic. """ return type(obj).__class__.__name__ == "ModelMetaclass" def parse_pydantic_schema(schema): """ Iterates through pydantic schema and parses nested schemas to a dictionary containing SQLAlchemy models. Only works if nested schemas have specified the Meta.orm_model. """ parsed_schema = dict(schema) for key, value in parsed_schema.items(): try: if isinstance(value, list) and len(value): if is_pydantic(value[0]): parsed_schema[key] = [schema.Meta.orm_model(**schema.dict()) for schema in value] else: if is_pydantic(value): parsed_schema[key] = value.Meta.orm_model(**value.dict()) except AttributeError: raise AttributeError("Found nested Pydantic model but Meta.orm_model was not specified.") return parsed_schema The parse_pydantic_schema function returns a dictionary representation of the pydantic model where submodels are substituted by the corresponding SQLAlchemy model specified in Meta.orm_model. You can use this return value to create the parent SQLAlchemy model in one go: parsed_schema = parse_pydantic_schema(parent_model) # parent_model is an instance of pydantic ParentModel new_db_model = ParentDBModel(**parsed_schema) # do your db actions/commit here If you want you can even extend this to also automatically create the parent model, but that requires you to also specify the Meta.orm_model for all pydantic models. A: I share an improved implementation of code from @Steven that I have used. Works well for any model that has Meta.orm_model defined. In case it doesn't, it additionally provides the information about the model that is missing the definition - much better than generic mapping failed. def is_pydantic(obj: object): """ Checks whether an object is pydantic. """ return type(obj).__class__.__name__ == "ModelMetaclass" def model_to_entity(schema): """ Iterates through pydantic schema and parses nested schemas to a dictionary containing SQLAlchemy models. Only works if nested schemas have specified the Meta.orm_model. """ if is_pydantic(schema): try: converted_model = model_to_entity(dict(schema)) return schema.Meta.orm_model(**converted_model) except AttributeError: model_name = schema.__class__.__name__ raise AttributeError(f"Failed converting pydantic model: {model_name}.Meta.orm_model not specified.") elif isinstance(schema, list): return [model_to_entity(model) for model in schema] elif isinstance(schema, dict): for key, model in schema.items(): schema[key] = model_to_entity(model) return schema
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 relationship I get the same error, but on the next line as it tries to add the document. Database Model: documents_counterparties = Table( "documents_counterparties", Base.metadata, Column("document_id", ForeignKey("documents.id"), primary_key=True), Column("counterparty_id", ForeignKey( "counterparties.id"), primary_key=True) ) class Document(Base): __tablename__ = "documents" id = Column(Integer, primary_key=True, index=True) name = Column(String, index=True) start_date = Column(Date) end_date = Column(Date) owner_id = Column(Integer, ForeignKey("users.id")) owner = relationship("User", back_populates="documents") counterparties = relationship( "Counterparty", secondary=documents_counterparties, backref="documents" ) Resolver: def create_document(db: Session, document: DocumentCreate, user_id: int): db_document = models.Document(**document.dict(), owner_id=user_id) #<- errors here db.add(db_document) db.commit() db.refresh(db_document) return db_document EDIT: DocumentCreate class DocumentBase(BaseModel): name: str start_date: datetime.date end_date: datetime.date class DocumentCreate(DocumentBase): counterparties: "list[CounterpartyClean]"
[ "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 pydantic import BaseModel\nfrom models import ChildDBModel, ParentDBModel\n\nclass ChildModel(BaseModel):\n some_attribute: str = 'value'\n class Meta:\n orm_model = ChildDBModel\n\nclass ParentModel(BaseModel):\n child: ChildModel\n\nThat allowed me to write a generic function that loops through the pydantic object and transforms submodels into SQLAlchemy models:\ndef is_pydantic(obj: object):\n \"\"\" Checks whether an object is pydantic. \"\"\"\n return type(obj).__class__.__name__ == \"ModelMetaclass\"\n\n\ndef parse_pydantic_schema(schema):\n \"\"\"\n Iterates through pydantic schema and parses nested schemas\n to a dictionary containing SQLAlchemy models.\n Only works if nested schemas have specified the Meta.orm_model.\n \"\"\"\n parsed_schema = dict(schema)\n for key, value in parsed_schema.items():\n try:\n if isinstance(value, list) and len(value):\n if is_pydantic(value[0]):\n parsed_schema[key] = [schema.Meta.orm_model(**schema.dict()) for schema in value]\n else:\n if is_pydantic(value):\n parsed_schema[key] = value.Meta.orm_model(**value.dict())\n except AttributeError:\n raise AttributeError(\"Found nested Pydantic model but Meta.orm_model was not specified.\")\n return parsed_schema\n\nThe parse_pydantic_schema function returns a dictionary representation of the pydantic model where submodels are substituted by the corresponding SQLAlchemy model specified in Meta.orm_model. You can use this return value to create the parent SQLAlchemy model in one go:\nparsed_schema = parse_pydantic_schema(parent_model) # parent_model is an instance of pydantic ParentModel \nnew_db_model = ParentDBModel(**parsed_schema)\n# do your db actions/commit here\n\nIf you want you can even extend this to also automatically create the parent model, but that requires you to also specify the Meta.orm_model for all pydantic models.\n", "I share an improved implementation of code from @Steven that I have used.\nWorks well for any model that has Meta.orm_model defined.\nIn case it doesn't, it additionally provides the information about the model that is missing the definition - much better than generic mapping failed.\ndef is_pydantic(obj: object):\n \"\"\" Checks whether an object is pydantic. \"\"\"\n return type(obj).__class__.__name__ == \"ModelMetaclass\"\n\n\ndef model_to_entity(schema):\n \"\"\"\n Iterates through pydantic schema and parses nested schemas\n to a dictionary containing SQLAlchemy models.\n Only works if nested schemas have specified the Meta.orm_model.\n \"\"\"\n if is_pydantic(schema):\n try:\n converted_model = model_to_entity(dict(schema))\n return schema.Meta.orm_model(**converted_model)\n\n except AttributeError:\n model_name = schema.__class__.__name__\n raise AttributeError(f\"Failed converting pydantic model: {model_name}.Meta.orm_model not specified.\")\n\n elif isinstance(schema, list):\n return [model_to_entity(model) for model in schema]\n\n elif isinstance(schema, dict):\n for key, model in schema.items():\n schema[key] = model_to_entity(model)\n\n return schema\n\n" ]
[ 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(winner) break I want to make it so that there will not be any repeats in the inventory list but the for loop doesn't work for it. What should I do? Thank you!
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 in the inventory list but the for loop doesn't work for it. What should I do? Thank you!
[]
[]
[ "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=myDtype) output: [('myID', 5) ('myID', 10)] This is not working df = pd.DataFrame(data) df = df.to_records(index=False, column_dtypes=myDtype) ValueError: invalid literal for int() with base 10: 'myID' What I am doing wroing with pandas to_records()? A: Ok so from what I understand, the way you wrote your variable myDtype isn't compatible with the column names your dataframe has. Your current dataframe columns are int values of 0 and 1, causing your error (trying to match the int 0 to your naming "myID"). (Not entirely sure about that one so someone might want to complement, I'll edit the answer.) I was able to remove the error by referring the column_dtypes with a dictionary : data = [("myID", 5), ("myID", 10)] myDtype = numpy.dtype([('myID', numpy.str_, 4), ('length', numpy.uint16)]) df = pd.DataFrame(data, columns=["myID", "length"]) df_records = df.to_records(index=False, column_dtypes={"myID": "<U4", "length": "<u2"}) With the following result : rec.array([('myID', 5), ('myID', 10)], dtype=[('myID', '<U4'), ('length', '<u2')]) A: column_dtypes argument in the to_records() function of a pandas dataframe expects a dict datatype as its input. But you are passing myDtype as the argument which is of type numpy.dtype. Try this, it should work - df = pd.DataFrame(data, columns=["myID", "length"]) df_rec = df.to_records(index = False, column_dtypes = {"myID": "<U4", "length": "<u2"}) The output is - >>> df_rec rec.array([('myID', 5), ('myID', 10)], dtype=[('myID', '<U4'), ('length', '<u2')])
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 df = pd.DataFrame(data) df = df.to_records(index=False, column_dtypes=myDtype) ValueError: invalid literal for int() with base 10: 'myID' What I am doing wroing with pandas to_records()?
[ "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 want to complement, I'll edit the answer.)\nI was able to remove the error by referring the column_dtypes with a dictionary :\n data = [(\"myID\", 5), (\"myID\", 10)]\n myDtype = numpy.dtype([('myID', numpy.str_, 4),\n ('length', numpy.uint16)])\n df = pd.DataFrame(data, columns=[\"myID\", \"length\"])\n df_records = df.to_records(index=False, column_dtypes={\"myID\": \"<U4\", \"length\": \"<u2\"})\n\nWith the following result :\nrec.array([('myID', 5), ('myID', 10)],\n dtype=[('myID', '<U4'), ('length', '<u2')])\n\n", "column_dtypes argument in the to_records() function of a pandas dataframe expects a dict datatype as its input. But you are passing myDtype as the argument which is of type numpy.dtype.\nTry this, it should work -\ndf = pd.DataFrame(data, columns=[\"myID\", \"length\"])\ndf_rec = df.to_records(index = False, column_dtypes = {\"myID\": \"<U4\", \"length\": \"<u2\"})\n\nThe output is -\n>>> df_rec\nrec.array([('myID', 5), ('myID', 10)],\n dtype=[('myID', '<U4'), ('length', '<u2')])\n\n" ]
[ 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 stock price time series data df: Date Open High Low Close volume 0 2015-02-02 09:15:00+05:30 586.60 589.70 584.85 584.95 171419 1 2015-02-02 09:20:00+05:30 584.95 585.30 581.25 582.30 59338 2 2015-02-02 09:25:00+05:30 582.30 585.05 581.70 581.70 52299 3 2015-02-02 09:30:00+05:30 581.70 583.25 581.70 582.60 44143 4 2015-02-02 09:35:00+05:30 582.75 584.00 582.75 582.90 42731 ... ... ... ... ... ... ... 99995 2020-07-06 11:40:00+05:30 106.85 106.90 106.55 106.70 735032 99996 2020-07-06 11:45:00+05:30 106.80 107.30 106.70 107.25 1751810 99997 2020-07-06 11:50:00+05:30 107.30 107.50 107.10 107.35 1608952 99998 2020-07-06 11:55:00+05:30 107.35 107.45 107.10 107.20 959097 99999 2020-07-06 12:00:00+05:30 107.20 107.35 107.10 107.20 865438 at each step the agent has access to previous 1000 prices + current price of stock = 1001 and it can take 3 possible action from 0,1,2 then i wrapped it in TFPyEnvironment to convert it to tf_environment the prices that the agent can observe is a 1d numpy array. prices = [584.95 582.3 581.7 ... 107.35 107.2 107.2 ] TimeStep Specs TimeStep Specs: TimeStep( {'discount': BoundedTensorSpec(shape=(), dtype=tf.float32, name='discount', minimum=array(0., dtype=float32), maximum=array(1., dtype=float32)), 'observation': BoundedTensorSpec(shape=(1001,), dtype=tf.float32, name='_observation', minimum=array(0., dtype=float32), maximum=array(3.4028235e+38, dtype=float32)), 'reward': TensorSpec(shape=(), dtype=tf.float32, name='reward'), 'step_type': TensorSpec(shape=(), dtype=tf.int32, name='step_type')}) Action Specs: BoundedTensorSpec(shape=(), dtype=tf.int32, name='_action', minimum=array(0, dtype=int32), maximum=array(2, dtype=int32)) then i build a dqn agent but i want to build it with a Conv1d layer my network consist of Conv1D, MaxPool1D, Conv1D, MaxPool1D, Dense_64, Dense_32 , q_value_layer i created a list layers using tf.keras.layers api and stored it in dense_layers list and created a Sequential Network DQN_Agent `learning_rate = 1e-3 action_tensor_spec = tensor_spec.from_spec(tf_env.action_spec()) num_actions = action_tensor_spec.maximum - action_tensor_spec.minimum + 1 dense_layers = [] dense_layers.append(tf.keras.layers.Conv1D( 64, kernel_size=(10), activation=tf.keras.activations.relu, input_shape=(1,1001), )) dense_layers.append( tf.keras.layers.MaxPool1D( pool_size=2, strides=None, padding='valid', )) dense_layers.append(tf.keras.layers.Conv1D( 64, kernel_size=(10), activation=tf.keras.activations.relu, )) dense_layers.append( tf.keras.layers.MaxPool1D( pool_size=2, strides=None, padding='valid', )) dense_layers.append( tf.keras.layers.Dense( 64, activation=tf.keras.activations.relu, )) dense_layers.append( tf.keras.layers.Dense( 32, activation=tf.keras.activations.relu, )) q_values_layer = tf.keras.layers.Dense( num_actions, activation=None, kernel_initializer=tf.keras.initializers.RandomUniform( minval=-0.03, maxval=0.03), bias_initializer=tf.keras.initializers.Constant(-0.2)) q_net = sequential.Sequential(dense_layers + [q_values_layer])` `optimizer = tf.keras.optimizers.Adam(learning_rate=learning_rate) train_step_counter = tf.Variable(0) agent = dqn_agent.DqnAgent( tf_env.time_step_spec(), tf_env.action_spec(), q_network=q_net, optimizer=optimizer, td_errors_loss_fn=common.element_wise_squared_loss, train_step_counter=train_step_counter) agent.initialize()` but when i passed the q_net as a q_network to DqnAgent i came accross this error `--------------------------------------------------------------------------- ValueError Traceback (most recent call last) in () 68 optimizer=optimizer, 69 td_errors_loss_fn=common.element_wise_squared_loss, ---> 70 train_step_counter=train_step_counter) 71 72 agent.initialize() 7 frames /usr/local/lib/python3.7/dist-packages/tf_agents/networks/sequential.py in call(self, inputs, network_state, **kwargs) 222 else: 223 # Does not maintain state. --> 224 inputs = layer(inputs, **layer_kwargs) 225 226 return inputs, tuple(next_network_state) ValueError: Exception encountered when calling layer "sequential_54" (type Sequential). Input 0 of layer "conv1d_104" is incompatible with the layer: expected min_ndim=3, found ndim=2. Full shape received: (1, 1001) Call arguments received by layer "sequential_54" (type Sequential): • inputs=tf.Tensor(shape=(1, 1001), dtype=float32) • network_state=() • kwargs={'step_type': 'tf.Tensor(shape=(1,), dtype=int32)', 'training': 'None'} In call to configurable 'DqnAgent' (<class 'tf_agents.agents.dqn.dqn_agent.DqnAgent'>)` i know it has something to do with the input shape of first layer of cov1d but cant figure out what am doing wrong at each time_step the agent is reciveing a observation of prices of 1d array of length 1001 then the input shape of conv1d should be (1,1001) but its wrong and i don't know how to solve this error need help A: 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 parameter that sets the conv_type. However, there is a workaround. Just copy the network you want to use, and change the line that calls the EncodingNetwork, so that the conv_type is set to 1D. I had also open a github issue about that here: https://github.com/tensorflow/agents/issues/779
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-02-02 09:15:00+05:30 586.60 589.70 584.85 584.95 171419 1 2015-02-02 09:20:00+05:30 584.95 585.30 581.25 582.30 59338 2 2015-02-02 09:25:00+05:30 582.30 585.05 581.70 581.70 52299 3 2015-02-02 09:30:00+05:30 581.70 583.25 581.70 582.60 44143 4 2015-02-02 09:35:00+05:30 582.75 584.00 582.75 582.90 42731 ... ... ... ... ... ... ... 99995 2020-07-06 11:40:00+05:30 106.85 106.90 106.55 106.70 735032 99996 2020-07-06 11:45:00+05:30 106.80 107.30 106.70 107.25 1751810 99997 2020-07-06 11:50:00+05:30 107.30 107.50 107.10 107.35 1608952 99998 2020-07-06 11:55:00+05:30 107.35 107.45 107.10 107.20 959097 99999 2020-07-06 12:00:00+05:30 107.20 107.35 107.10 107.20 865438 at each step the agent has access to previous 1000 prices + current price of stock = 1001 and it can take 3 possible action from 0,1,2 then i wrapped it in TFPyEnvironment to convert it to tf_environment the prices that the agent can observe is a 1d numpy array. prices = [584.95 582.3 581.7 ... 107.35 107.2 107.2 ] TimeStep Specs TimeStep Specs: TimeStep( {'discount': BoundedTensorSpec(shape=(), dtype=tf.float32, name='discount', minimum=array(0., dtype=float32), maximum=array(1., dtype=float32)), 'observation': BoundedTensorSpec(shape=(1001,), dtype=tf.float32, name='_observation', minimum=array(0., dtype=float32), maximum=array(3.4028235e+38, dtype=float32)), 'reward': TensorSpec(shape=(), dtype=tf.float32, name='reward'), 'step_type': TensorSpec(shape=(), dtype=tf.int32, name='step_type')}) Action Specs: BoundedTensorSpec(shape=(), dtype=tf.int32, name='_action', minimum=array(0, dtype=int32), maximum=array(2, dtype=int32)) then i build a dqn agent but i want to build it with a Conv1d layer my network consist of Conv1D, MaxPool1D, Conv1D, MaxPool1D, Dense_64, Dense_32 , q_value_layer i created a list layers using tf.keras.layers api and stored it in dense_layers list and created a Sequential Network DQN_Agent `learning_rate = 1e-3 action_tensor_spec = tensor_spec.from_spec(tf_env.action_spec()) num_actions = action_tensor_spec.maximum - action_tensor_spec.minimum + 1 dense_layers = [] dense_layers.append(tf.keras.layers.Conv1D( 64, kernel_size=(10), activation=tf.keras.activations.relu, input_shape=(1,1001), )) dense_layers.append( tf.keras.layers.MaxPool1D( pool_size=2, strides=None, padding='valid', )) dense_layers.append(tf.keras.layers.Conv1D( 64, kernel_size=(10), activation=tf.keras.activations.relu, )) dense_layers.append( tf.keras.layers.MaxPool1D( pool_size=2, strides=None, padding='valid', )) dense_layers.append( tf.keras.layers.Dense( 64, activation=tf.keras.activations.relu, )) dense_layers.append( tf.keras.layers.Dense( 32, activation=tf.keras.activations.relu, )) q_values_layer = tf.keras.layers.Dense( num_actions, activation=None, kernel_initializer=tf.keras.initializers.RandomUniform( minval=-0.03, maxval=0.03), bias_initializer=tf.keras.initializers.Constant(-0.2)) q_net = sequential.Sequential(dense_layers + [q_values_layer])` `optimizer = tf.keras.optimizers.Adam(learning_rate=learning_rate) train_step_counter = tf.Variable(0) agent = dqn_agent.DqnAgent( tf_env.time_step_spec(), tf_env.action_spec(), q_network=q_net, optimizer=optimizer, td_errors_loss_fn=common.element_wise_squared_loss, train_step_counter=train_step_counter) agent.initialize()` but when i passed the q_net as a q_network to DqnAgent i came accross this error `--------------------------------------------------------------------------- ValueError Traceback (most recent call last) in () 68 optimizer=optimizer, 69 td_errors_loss_fn=common.element_wise_squared_loss, ---> 70 train_step_counter=train_step_counter) 71 72 agent.initialize() 7 frames /usr/local/lib/python3.7/dist-packages/tf_agents/networks/sequential.py in call(self, inputs, network_state, **kwargs) 222 else: 223 # Does not maintain state. --> 224 inputs = layer(inputs, **layer_kwargs) 225 226 return inputs, tuple(next_network_state) ValueError: Exception encountered when calling layer "sequential_54" (type Sequential). Input 0 of layer "conv1d_104" is incompatible with the layer: expected min_ndim=3, found ndim=2. Full shape received: (1, 1001) Call arguments received by layer "sequential_54" (type Sequential): • inputs=tf.Tensor(shape=(1, 1001), dtype=float32) • network_state=() • kwargs={'step_type': 'tf.Tensor(shape=(1,), dtype=int32)', 'training': 'None'} In call to configurable 'DqnAgent' (<class 'tf_agents.agents.dqn.dqn_agent.DqnAgent'>)` i know it has something to do with the input shape of first layer of cov1d but cant figure out what am doing wrong at each time_step the agent is reciveing a observation of prices of 1d array of length 1001 then the input shape of conv1d should be (1,1001) but its wrong and i don't know how to solve this error need help
[ "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 parameter that sets the conv_type.\nHowever, there is a workaround. Just copy the network you want to use, and change the line that calls the EncodingNetwork, so that the conv_type is set to 1D. I had also open a github issue about that here:\nhttps://github.com/tensorflow/agents/issues/779\n" ]
[ 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, 1, 12, 0, 0, 0, has_year_zero=True),) (cftime.Datetime360Day(2006, 1, 2, 12, 0, 0, 0, has_year_zero=True),) (cftime.Datetime360Day(2006, 1, 3, 12, 0, 0, 0, has_year_zero=True),) (cftime.Datetime360Day(2006, 1, 4, 12, 0, 0, 0, has_year_zero=True),) (cftime.Datetime360Day(2006, 1, 5, 12, 0, 0, 0, has_year_zero=True),) (cftime.Datetime360Day(2006, 1, 6, 12, 0, 0, 0, has_year_zero=True),) (cftime.Datetime360Day(2006, 1, 7, 12, 0, 0, 0, has_year_zero=True),) (cftime.Datetime360Day(2006, 1, 8, 12, 0, 0, 0, has_year_zero=True),) I would like to change this column to normal datetime. Is there any solution please! Thanks! A: I assume you've tried pandas pd.to_datetime() already, right? If not, give that a shot. It generally works really well. A: Datetime360Day is a calendar with every year being 360 days long (divided into 30 day months) Generally (in around all languages) if there is no means that can help you to do the conversion natively : You have to use the datetime api and format a string coming from the calendar output. Regards
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.Datetime360Day(2006, 1, 2, 12, 0, 0, 0, has_year_zero=True),) (cftime.Datetime360Day(2006, 1, 3, 12, 0, 0, 0, has_year_zero=True),) (cftime.Datetime360Day(2006, 1, 4, 12, 0, 0, 0, has_year_zero=True),) (cftime.Datetime360Day(2006, 1, 5, 12, 0, 0, 0, has_year_zero=True),) (cftime.Datetime360Day(2006, 1, 6, 12, 0, 0, 0, has_year_zero=True),) (cftime.Datetime360Day(2006, 1, 7, 12, 0, 0, 0, has_year_zero=True),) (cftime.Datetime360Day(2006, 1, 8, 12, 0, 0, 0, has_year_zero=True),) I would like to change this column to normal datetime. Is there any solution please! Thanks!
[ "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 conversion natively :\nYou have to use the datetime api and format a string coming from the calendar output.\nRegards\n" ]
[ 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_person_ids = [0, 1, 2] all_statuses = ['pass', 'fail'] all_years = [1980, 1981, 1982] I'd like to populate the original data frame with count=0 for missing data combinations (of person_id, status, and year), i.e. I'd like the new data frame to contain: person_id status year count 0 'pass' 1980 4 0 'pass' 1981 0 0 'pass' 1982 0 0 'fail' 1980 0 0 'fail' 1981 0 0 'fail' 1982 2 1 'pass' 1980 0 1 'pass' 1981 2 1 'pass' 1982 0 1 'fail' 1980 0 1 'fail' 1981 0 1 'fail' 1982 0 2 'pass' 1980 0 2 'pass' 1981 0 2 'pass' 1982 0 2 'fail' 1980 0 2 'fail' 1981 0 2 'fail' 1982 0 Is there an efficient way to achieve this in pandas? A: 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: In [77]: import itertools all_person_ids = [0, 1, 2] all_statuses = ['pass', 'fail'] all_years = [1980, 1981, 1982] combined = [all_person_ids, all_statuses, all_years] df1 = pd.DataFrame(columns = ['person_id', 'status', 'year'], data=list(itertools.product(*combined))) df1 Out[77]: person_id status year 0 0 pass 1980 1 0 pass 1981 2 0 pass 1982 3 0 fail 1980 4 0 fail 1981 5 0 fail 1982 6 1 pass 1980 7 1 pass 1981 8 1 pass 1982 9 1 fail 1980 10 1 fail 1981 11 1 fail 1982 12 2 pass 1980 13 2 pass 1981 14 2 pass 1982 15 2 fail 1980 16 2 fail 1981 17 2 fail 1982 In [82]: df1 = df1.merge(df, how='left').fillna(0) df1 Out[82]: person_id status year count 0 0 pass 1980 4 1 0 pass 1981 0 2 0 pass 1982 0 3 0 fail 1980 0 4 0 fail 1981 0 5 0 fail 1982 1 6 1 pass 1980 0 7 1 pass 1981 2 8 1 pass 1982 0 9 1 fail 1980 0 10 1 fail 1981 0 11 1 fail 1982 0 12 2 pass 1980 0 13 2 pass 1981 0 14 2 pass 1982 0 15 2 fail 1980 0 16 2 fail 1981 0 17 2 fail 1982 0 A: create a MultiIndex by MultiIndex.from_product() and then set_index(), reindex(), reset_index(). import pandas as pd import io all_person_ids = [0, 1, 2] all_statuses = ['pass', 'fail'] all_years = [1980, 1981, 1982] df = pd.read_csv(io.BytesIO("""person_id status year count 0 pass 1980 4 0 fail 1982 1 1 pass 1981 2"""), delim_whitespace=True) names = ["person_id", "status", "year"] mind = pd.MultiIndex.from_product( [all_person_ids, all_statuses, all_years], names=names) df.set_index(names).reindex(mind, fill_value=0).reset_index() A: You can use pyjanitor's complete method. It accepts column names as input as well as {name: values} dictionaries with the exhaustive list of wanted values to complete: import janitor df.complete({'person_id': [0,1,2]}, 'status', 'year').fillna(0, downcast='infer') output: person_id status year count 0 0 'fail' 1980 0 1 0 'fail' 1981 0 2 0 'fail' 1982 1 3 0 'pass' 1980 4 4 0 'pass' 1981 0 5 0 'pass' 1982 0 6 1 'fail' 1980 0 7 1 'fail' 1981 0 8 1 'fail' 1982 0 9 1 'pass' 1980 0 10 1 'pass' 1981 2 11 1 'pass' 1982 0 12 2 'fail' 1980 0 13 2 'fail' 1981 0 14 2 'fail' 1982 0 15 2 'pass' 1980 0 16 2 'pass' 1981 0 17 2 'pass' 1982 0 A: all_person_ids = [0, 1, 2] all_statuses = ['pass', 'fail'] all_years = [1980, 1981, 1982] pd.Series(all_person_ids).to_frame('person_id').merge(pd.Series(all_statuses).to_frame('status'), how='cross')\ .merge(pd.Series(all_years).to_frame('year'), how='cross')\ .merge(df1,on=['person_id','status','year'], how='left')\ .fillna(0) person_id status year count 0 0 pass 1980 4.0 1 0 pass 1981 0.0 2 0 pass 1982 0.0 3 0 fail 1980 0.0 4 0 fail 1981 0.0 5 0 fail 1982 1.0 6 1 pass 1980 0.0 7 1 pass 1981 2.0 8 1 pass 1982 0.0 9 1 fail 1980 0.0 10 1 fail 1981 0.0 11 1 fail 1982 0.0 12 2 pass 1980 0.0 13 2 pass 1981 0.0 14 2 pass 1982 0.0 15 2 fail 1980 0.0 16 2 fail 1981 0.0 17 2 fail 1982 0.0
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_years = [1980, 1981, 1982] I'd like to populate the original data frame with count=0 for missing data combinations (of person_id, status, and year), i.e. I'd like the new data frame to contain: person_id status year count 0 'pass' 1980 4 0 'pass' 1981 0 0 'pass' 1982 0 0 'fail' 1980 0 0 'fail' 1981 0 0 'fail' 1982 2 1 'pass' 1980 0 1 'pass' 1981 2 1 'pass' 1982 0 1 'fail' 1980 0 1 'fail' 1981 0 1 'fail' 1982 0 2 'pass' 1980 0 2 'pass' 1981 0 2 'pass' 1982 0 2 'fail' 1980 0 2 'fail' 1981 0 2 'fail' 1982 0 Is there an efficient way to achieve this in pandas?
[ "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_person_ids, all_statuses, all_years]\ndf1 = pd.DataFrame(columns = ['person_id', 'status', 'year'], data=list(itertools.product(*combined)))\ndf1\n\nOut[77]:\n person_id status year\n0 0 pass 1980\n1 0 pass 1981\n2 0 pass 1982\n3 0 fail 1980\n4 0 fail 1981\n5 0 fail 1982\n6 1 pass 1980\n7 1 pass 1981\n8 1 pass 1982\n9 1 fail 1980\n10 1 fail 1981\n11 1 fail 1982\n12 2 pass 1980\n13 2 pass 1981\n14 2 pass 1982\n15 2 fail 1980\n16 2 fail 1981\n17 2 fail 1982\n\nIn [82]: \ndf1 = df1.merge(df, how='left').fillna(0)\ndf1\n\nOut[82]:\n person_id status year count\n0 0 pass 1980 4\n1 0 pass 1981 0\n2 0 pass 1982 0\n3 0 fail 1980 0\n4 0 fail 1981 0\n5 0 fail 1982 1\n6 1 pass 1980 0\n7 1 pass 1981 2\n8 1 pass 1982 0\n9 1 fail 1980 0\n10 1 fail 1981 0\n11 1 fail 1982 0\n12 2 pass 1980 0\n13 2 pass 1981 0\n14 2 pass 1982 0\n15 2 fail 1980 0\n16 2 fail 1981 0\n17 2 fail 1982 0\n\n", "create a MultiIndex by MultiIndex.from_product() and then set_index(), reindex(), reset_index(). \nimport pandas as pd\nimport io\n\nall_person_ids = [0, 1, 2]\nall_statuses = ['pass', 'fail']\nall_years = [1980, 1981, 1982]\ndf = pd.read_csv(io.BytesIO(\"\"\"person_id status year count\n0 pass 1980 4\n0 fail 1982 1\n1 pass 1981 2\"\"\"), delim_whitespace=True)\nnames = [\"person_id\", \"status\", \"year\"]\n\nmind = pd.MultiIndex.from_product(\n [all_person_ids, all_statuses, all_years], names=names)\ndf.set_index(names).reindex(mind, fill_value=0).reset_index()\n\n", "You can use pyjanitor's complete method.\nIt accepts column names as input as well as {name: values} dictionaries with the exhaustive list of wanted values to complete:\nimport janitor\ndf.complete({'person_id': [0,1,2]}, 'status', 'year').fillna(0, downcast='infer')\n\noutput:\n person_id status year count\n0 0 'fail' 1980 0\n1 0 'fail' 1981 0\n2 0 'fail' 1982 1\n3 0 'pass' 1980 4\n4 0 'pass' 1981 0\n5 0 'pass' 1982 0\n6 1 'fail' 1980 0\n7 1 'fail' 1981 0\n8 1 'fail' 1982 0\n9 1 'pass' 1980 0\n10 1 'pass' 1981 2\n11 1 'pass' 1982 0\n12 2 'fail' 1980 0\n13 2 'fail' 1981 0\n14 2 'fail' 1982 0\n15 2 'pass' 1980 0\n16 2 'pass' 1981 0\n17 2 'pass' 1982 0\n\n", "all_person_ids = [0, 1, 2]\nall_statuses = ['pass', 'fail']\nall_years = [1980, 1981, 1982]\n\n\npd.Series(all_person_ids).to_frame('person_id').merge(pd.Series(all_statuses).to_frame('status'), how='cross')\\\n .merge(pd.Series(all_years).to_frame('year'), how='cross')\\\n .merge(df1,on=['person_id','status','year'], how='left')\\\n .fillna(0)\n\n person_id status year count\n0 0 pass 1980 4.0\n1 0 pass 1981 0.0\n2 0 pass 1982 0.0\n3 0 fail 1980 0.0\n4 0 fail 1981 0.0\n5 0 fail 1982 1.0\n6 1 pass 1980 0.0\n7 1 pass 1981 2.0\n8 1 pass 1982 0.0\n9 1 fail 1980 0.0\n10 1 fail 1981 0.0\n11 1 fail 1982 0.0\n12 2 pass 1980 0.0\n13 2 pass 1981 0.0\n14 2 pass 1982 0.0\n15 2 fail 1980 0.0\n16 2 fail 1981 0.0\n17 2 fail 1982 0.0\n\n" ]
[ 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 not grab - a random name/string. I didn't expect it to grab that one, but it did, and assigned a wrong price to this! It happens just after a mineral with this "unexpected name" and then whole rest of list has wrong prices. See image below: So as this string is different than any other, further code can't split it and gives error: cutted2 = split2.pop(1) ^^^^^^^^^^^^^ IndexError: pop index out of range I tried to ignore these errors and used one of methods used in different Stackoverflow page: try: cutted2 = split2.pop(1) except IndexError: continue It did work, no errors appeared...But then it was assigning wrong prices to wrong minerals (as I noticed)!!! How can I change code to just IGNORE these "strange" names and just go on with list? Below is whole code, it stops on URL5 as I remember and gives this pop index error: import requests from bs4 import BeautifulSoup import re def collecter(URL): headers = {"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.114 Safari/537.36"} soup = BeautifulSoup(requests.get(URL, headers=headers).text, "lxml") names = [n.getText(strip=True) for n in soup.select("table tr td font a")] prices = [ p.getText(strip=True).split("Price:")[-1] for p in soup.select("table tr td font font") ] names[:] = [" ".join(n.split()) for n in names if not n.startswith("[")] prices[:] = [p for p in prices if p] with open("Minerals.txt", "a+", encoding='utf-8') as file: for name, price in zip(names, prices): # print(f"{name}\n{price}") # print("-" * 50) filename = str(name)+" "+str(price)+"\n" split1 = filename.split(' / ') cutted1 = split1.pop(0) split2 = cutted1.split(": ") try: cutted2 = split2.pop(1) except IndexError: continue two_prices = cutted2+" "+split1.pop(0)+"\n" file.write(two_prices) URL1 = "https://www.fabreminerals.com/search_results.php?LANG=EN&SearchTerms=&submit=Buscar&MineralSpeciment=&Country=&Locality=&PriceRange=&checkbox=enventa&First=0" URL2 = "https://www.fabreminerals.com/search_results.php?LANG=EN&SearchTerms=&submit=Buscar&MineralSpeciment=&Country=&Locality=&PriceRange=&checkbox=enventa&First=25" URL3 = "https://www.fabreminerals.com/search_results.php?LANG=EN&SearchTerms=&submit=Buscar&MineralSpeciment=&Country=&Locality=&PriceRange=&checkbox=enventa&First=50" URL4 = "https://www.fabreminerals.com/search_results.php?LANG=EN&SearchTerms=&submit=Buscar&MineralSpeciment=&Country=&Locality=&PriceRange=&checkbox=enventa&First=75" URL5 = "https://www.fabreminerals.com/search_results.php?LANG=EN&SearchTerms=&submit=Buscar&MineralSpeciment=&Country=&Locality=&PriceRange=&checkbox=enventa&First=100" URL6 = "https://www.fabreminerals.com/search_results.php?LANG=EN&SearchTerms=&submit=Buscar&MineralSpeciment=&Country=&Locality=&PriceRange=&checkbox=enventa&First=125" URL7 = "https://www.fabreminerals.com/search_results.php?LANG=EN&SearchTerms=&submit=Buscar&MineralSpeciment=&Country=&Locality=&PriceRange=&checkbox=enventa&First=150" URL8 = "https://www.fabreminerals.com/search_results.php?LANG=EN&SearchTerms=&submit=Buscar&MineralSpeciment=&Country=&Locality=&PriceRange=&checkbox=enventa&First=175" URL9 = "https://www.fabreminerals.com/search_results.php?LANG=EN&SearchTerms=&submit=Buscar&MineralSpeciment=&Country=&Locality=&PriceRange=&checkbox=enventa&First=200" URL10 = "https://www.fabreminerals.com/search_results.php?LANG=EN&SearchTerms=&submit=Buscar&MineralSpeciment=&Country=&Locality=&PriceRange=&checkbox=enventa&First=225" URL11 = "https://www.fabreminerals.com/search_results.php?LANG=EN&SearchTerms=&submit=Buscar&MineralSpeciment=&Country=&Locality=&PriceRange=&checkbox=enventa&First=250" URL12 = "https://www.fabreminerals.com/search_results.php?LANG=EN&SearchTerms=&submit=Buscar&MineralSpeciment=&Country=&Locality=&PriceRange=&checkbox=enventa&First=275" URL13 = "https://www.fabreminerals.com/search_results.php?LANG=EN&SearchTerms=&submit=Buscar&MineralSpeciment=&Country=&Locality=&PriceRange=&checkbox=enventa&First=300" URL14 = "https://www.fabreminerals.com/search_results.php?LANG=EN&SearchTerms=&submit=Buscar&MineralSpeciment=&Country=&Locality=&PriceRange=&checkbox=enventa&First=325" collecter(URL1) collecter(URL2) collecter(URL3) collecter(URL4) collecter(URL5) collecter(URL6) collecter(URL7) collecter(URL8) collecter(URL9) collecter(URL10) collecter(URL11) collecter(URL12) collecter(URL13) collecter(URL14) EDIT: THIS IS FULLY WORKING CODE BELOW, THANKS FOR HELP GUYS! import requests from bs4 import BeautifulSoup import re for URL in range(0,2569,25): headers = {"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.114 Safari/537.36"} soup = BeautifulSoup(requests.get(f'https://www.fabreminerals.com/search_results.php?LANG=EN&SearchTerms=&submit=Buscar&MineralSpeciment=&Country=&Locality=&PriceRange=&checkbox=enventa&First={URL}', headers=headers).text, "lxml") names = [n.getText(strip=True) for n in soup.select("table tr td font>a")] prices = [p.getText(strip=True).split("Price:")[-1] for p in soup.select("table tr td font>font")] names[:] = [" ".join(n.split()) for n in names if not n.startswith("[") ] prices[:] = [p for p in prices if p] with open("MineralsList.txt", "a+", encoding='utf-8') as file: for name, price in zip(names, prices): # print(f"{name}\n{price}") # print("-" * 50) filename = str(name)+" "+str(price)+"\n" split1 = filename.split(' / ') cutted1 = split1.pop(0) split2 = cutted1.split(": ") cutted2 = split2.pop(1) try: two_prices = cutted2+" "+split1.pop(0)+"\n" except IndexError: two_prices = cutted2+"\n" file.write(two_prices) But after some changes it stops on new error - it can't find a string by given properties, so error "IndexError: pop from empty list" appears... Not even soup.select("table tr td font>font") helped, like it did in 'names' A: 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: soup.select("table tr td font>a") Adding a further criteria that the link is to an individual item rather than the next/prev page links at the bottom of the page will also help: soup.select("table tr td font>a[href*='CODE']") A: You can try the next example along with pagination import requests from bs4 import BeautifulSoup for URL in range(0,100,25): headers = {"User-Agent": "Mozilla/5.0"} soup = BeautifulSoup(requests.get(f'https://www.fabreminerals.com/search_results.php?LANG=EN&SearchTerms=&submit=Buscar&MineralSpeciment=&Country=&Locality=&PriceRange=&checkbox=enventa&First={URL}', headers=headers).text, "lxml") names = [ x.get_text(strip=True) for x in soup.select('table tr td font a')][:25] print(names) prices = [ x.get_text(strip=True) for x in soup.select('table tr td font:nth-child(3)')][:25] print(prices) # with open("Minerals.txt", "a+", encoding='utf-8') as file: # for name, price in zip(names, prices): # # print(f"{name}\n{price}") # # print("-" * 50) # filename = str(name)+" "+str(price)+"\n" # split1 = filename.split(' / ') # cutted1 = split1.pop(0) # split2 = cutted1.split(": ") # try: # cutted2 = split2.pop(1) # except IndexError: # continue # two_prices = cutted2+" "+split1.pop(0)+"\n" # file.write(two_prices) Output: ["NX51AH2:\n'lepidolite' after Elbaite with Elbaite", "TH27AL9:\n'Pearceite' with Calcite", "TFM69AN5:\n'Stilbite'", 'SM90CEX:\nAcanthite', 'TMA97AN5:\nAcanthite', 'TB90AE8:\n Acanthite', 'TZ71AK9:\nAcanthite', 'EC63G1:\nAcanthite', 'MN56K9:\nAcanthite', 'TF89AL3:\nAcanthite (Se-bearing) with Polybasite (Se-bearing) and Calcite', 'TP66AJ8:\nAcanthite (Se-bearing) with Pyrite', 'TY86AN2:\nAcanthite after Polybasite', 'TA66AF6:\nAcanthite with Calcite', 'JFD104AO2:\nAcanthite with Calcite', 'TX36AL6:\nAcanthite with Calcite', 'TA48AH1:\nAcanthite with Chalcopyrite', 'EF89L9:\nAcanthite with Pyrite and Calcite', 'TX89AN0:\nAcanthite with Siderite and Proustite', 'EA56K0:\nAcanthite with Silver', 'EC48K0:\nAcanthite with Silver', '11AT12:\nAcanthite, Calcite', '9EF89L9:\nAcanthite, Pyrite, Calcite', 'SM75TDA:\nAdamite', '2M14:\nAdamite', '20MJX66:\nAdamite'] ['Price:€580 / US$598 / ¥84010 / AUD$890', 'Price:€220 / US$227 / ¥31860 / AUD$330', 'Price:€450 / US$464 / ¥65180 / AUD$690', 'Price:€90 / US$92 / ¥13030 / AUD$130', 'Price:€240 / US$247 / ¥34760 / AUD$370', 'Price:€540 / US$557 / ¥78220 / AUD$830', 'Price:€580 / US$598 / ¥84010 / AUD$890', 'Price:€85 / US$87 / ¥12310 / AUD$130', 'Price:€155 / US$159 / ¥22450 / AUD$230', 'Price:€460 / US$474 / ¥66630 / AUD$700', 'Price:€1500 / US$1547 / ¥217290 / AUD$2310', 'Price:€1600 / US$1651 / ¥231770 / AUD$2460', 'Price:€160 / US$165 / ¥23170 / AUD$240', 'Price:€240 / US$247 / ¥34760 / AUD$370', 'Price:€1200 / US$1238 / ¥173830 / AUD$1850', 'Price:€290 / US$299 / ¥42000 / AUD$440', 'Price:€480 / US$495 / ¥69530 / AUD$740', 'Price:€4800 / US$4953 / ¥695320 / AUD$7400', 'Price:€150 / US$154 / ¥21720 / AUD$230', 'Price:€290 / US$299 / ¥42000 / AUD$440', 'Price:€70 / US$72 / ¥10140 / AUD$100', 'Price:€320 / US$330 / ¥46350 / AUD$490', 'Price:€75 / US$77 / ¥10860 / AUD$110', 'Price:€90 / US$92 / ¥13030 / AUD$130', 'Price:€140 / US$144 / ¥20280 / AUD$215'] ['5TD76M9:\nAdamite', 'MA54AE9:\nAdamite (variety Cu-bearing adamite) with Calcite', 'EA11Y6:\nAdamite (variety cuprian)', 'EB14Y6:\nAdamite (variety cuprian)', 'MC11X8:\nAdamite (variety cuprian) with Smithsonite', 'JRM10AN8:\nAegirine', 'MFA46AP3:\nAegirine with Zircon, Orthoclase and Quartz (variety smoky)', 'EM48AF8:\nAlabandite with Calcite', 'MC92T6:\nAlabandite with Calcite and Rhodochrosite', 'TF16AN1:\nAlabandite with Rhodochrosite', 'TX17S1:\nAlabandite with Rhodochrosite', 'TD34S1:\nAlabandite with Rhodochrosite', '10TR46:\nAlmandine', 'HM90EJ:\nAnalcime', 'EFH36AP3:\nAnalcime with Natrolite, Rhodochrosite and Serandite', 'ELR67AP1:\nAnalcime with Quartz', 'EML88AP1:\nAnalcime with Quartz', 'TF87AF4:\nAndorite', 'TR88AJ3:\nAndorite', 'ND56AN0:\nAndorite with Zinkenite', 'SM180NH:\nAndradite (variety demantoid)', 'MT86AL3:\nAndradite (variety demantoid) with Calcite', 'MA27AL7:\nAndradite (variety demantoid) with Calcite', 'TC80TL:\nAndradite (variety topazolite) with Clinochlore', 'TC85TE:\nAndradite (variety topazolite) with Clinochlore'] ['Price:€180 / US$185 / ¥26070 / AUD$270', 'Price:€840 / US$866 / ¥121680 / AUD$1290', 'Price:€60 / US$61 / ¥8690 / AUD$90', 'Price:€90 / US$92 / ¥13030 / AUD$130', 'Price:€70 / US$72 / ¥10140 / AUD$100', 'Price:€580 / US$598 / ¥84010 / AUD$890', 'Price:€1600 / US$1651 / ¥231770 / AUD$2468', 'Price:€2700 / US$2786 / ¥391120 / AUD$4160', 'Price:€740 / US$763 / ¥107190 / AUD$1140', 'Price:€110 / US$113 / ¥15930 / AUD$160', 'Price:€220 / US$227 / ¥31860 / AUD$330', 'Price:€920 / US$949 / ¥133270 / AUD$1410', 'Price:€140 / US$144 / ¥20280 / AUD$210', 'Price:€90 / US$92 / ¥13030 / AUD$130', 'Price:€130 / US$134 / ¥18830 / AUD$200', 'Price:€260 / US$268 / ¥37660 / AUD$400', 'Price:€380 / US$392 / ¥55040 / AUD$580', 'Price:€240 / US$247 / ¥34760 / AUD$370', 'Price:€390 / US$402 / ¥56490 / AUD$600', 'Price:€150 / US$154 / ¥21720 / AUD$230', 'Price:€180 / US$185 / ¥26070 / AUD$270', 'Price:€1600 / US$1651 / ¥231770 / AUD$2460', 'Price:€2200 / US$2270 / ¥318690 / AUD$3390', 'Price:€80 / US$82 / ¥11580 / AUD$120', 'Price:€85 / US$87 / ¥12310 / AUD$130'] ['T29NAK3:\nAndradite (variety topazolite) with Clinochlore', 'TC85TV:\nAndradite (variety topazolite) with Clinochlore', 'T89GH5:\nAndradite (variety topazolite) with Clinochlore', 'TQ94Q0:\nAndradite (variety topazolite) with Stilbite', 'SM140TFV:\nAndradite on Microcline', 'HM140NG:\nAndradite with Calcite', 'GM66R9:\nAndradite with Clinochlore', 'SM70TYW:\nAndradite with Epidote', 'TC290TVH:\nAndradite with Epidote and Microcline', 'TKX11AO7:\nAndradite with Microcline', 'TC2100TEJ:\nAndradite with Microcline', 'TH16AN2:\nAndradite with Microcline', 'TTX66AO7:\nAndradite with Microcline', 'TC2150TJL:\nAndradite with Microcline', 'TQ96AN2:\nAndradite with Microcline', 'TF48AF2:\nAnglesite', 'MA47AL4:\nAnglesite with Galena', 'LQ88AE6:\nAnglesite with Galena', 'ER90AL8:\nAnglesite with Galena', 'TP70AE1:\nAnglesite with Galena', 'N54NAL5:\nAnglesite with Galena', 'GV96R9:\nAnhydrite with Calcite and Pyrite', '11TV99:\nAnhydrite, Calcite', 'MG26AL4:\nAnorthoroselite with Calcite', 'XM260NFF:\nAragonite'] ['Price:€240 / US$247 / ¥34760 / AUD$370', 'Price:€85 / US$87 / ¥12310 / AUD$130', 'Price:€220 / US$227 / ¥31860 / AUD$330', 'Price:€980 / US$1011 / ¥141960 / AUD$1510', 'Price:€140 / US$144 / ¥20280 / AUD$210', 'Price:€140 / US$144 / ¥20280 / AUD$210', 'Price:€160 / US$165 / ¥23170 / AUD$240', 'Price:€70 / US$72 / ¥10140 / AUD$100', 'Price:€90 / US$92 / ¥13030 / AUD$130', 'Price:€70 / US$72 / ¥10140 / AUD$100', 'Price:€100 / US$103 / ¥14480 / AUD$150', 'Price:€110 / US$113 / ¥15930 / AUD$160', 'Price:€140 / US$144 / ¥20280 / AUD$210', 'Price:€150 / US$154 / ¥21720 / AUD$230', 'Price:€220 / US$227 / ¥31860 / AUD$330', 'Price:€380 / US$392 / ¥55040 / AUD$580', 'Price:€220 / US$227 / ¥31860 / AUD$330', 'Price:€360 / US$371 / ¥52140 / AUD$550', 'Price:€540 / US$557 / ¥78220 / AUD$830', 'Price:€540 / US$557 / ¥78220 / AUD$830', 'Price:€940 / US$969 / ¥136160 / AUD$1450', 'Price:€220 / US$227 / ¥31860 / AUD$330', 'Price:€460 / US$474 / ¥66630 / AUD$700', 'Price:€140 / US$144 / ¥20280 / AUD$210', 'Price:€60 / US$61 / ¥8690 / AUD$92'] ['XM295EAR:\nAragonite', 'ETE46AP2:\nAragonite', 'EXM26AP0:\nAragonite', 'EYB26AP0:\nAragonite', 'EXE56AP2:\nAragonite', 'ETF46AP0:\nAragonite', 'XM2160ERF:\nAragonite', 'EXM46AP0:\nAragonite', 'XM2190MEX:\nAragonite', 'XM2780EFT:\nAragonite', 'EHM93AO9:\nAragonite', 'TYB37AO8:\nAragonite (variety Cu-bearing aragonite)', 'SM99AM3:\nAragonite (variety cuprian)', '1M06:\nAragonite (variety flos ferri)', 'TG69AL3:\nAragonite (variety tarnowitzite)', 'MLC96AO2:\nAragonite on Calcite', 'MLE68AO2:\nAragonite on Calcite', 'MTB66AP3:\nAragonite with Quartz (variety hematoide)', 'MXF96AP3:\nAragonite with Quartz (variety hematoide)', 'MRR47AP3:\nAragonite with Quartz (variety hematoide)', 'MTR37AP3:\nAragonite with Quartz (variety hematoide)', 'JFD193AP3:\nArfvedsonite with Microcline', 'TFX76AO7:\nArsenopyrite with Calcite, Pyrite, Sphalerite and Rhodochrosite', 'NB37AL3:\nArsenopyrite with Muscovite', 'HM220NX:\nArsenopyrite with Muscovite'] ['Price:€95 / US$98 / ¥13760 / AUD$146', 'Price:€140 / US$144 / ¥20280 / AUD$210', 'Price:€140 / US$144 / ¥20280 / AUD$210', 'Price:€140 / US$144 / ¥20280 / AUD$210', 'Price:€150 / US$154 / ¥21720 / AUD$230', 'Price:€150 / US$154 / ¥21720 / AUD$230', 'Price:€160 / US$165 / ¥23170 / AUD$246', 'Price:€160 / US$165 / ¥23170 / AUD$240', 'Price:€190 / US$196 / ¥27520 / AUD$293', 'Price:€780 / US$804 / ¥112990 / AUD$1203', 'Price:€880 / US$908 / ¥127470 / AUD$1350', 'Price:€240 / US$247 / ¥34760 / AUD$370', 'Price:€480 / US$495 / ¥69530 / AUD$740', 'Price:€100 / US$103 / ¥14480 / AUD$150', 'Price:€460 / US$474 / ¥66630 / AUD$700', 'Price:€190 / US$196 / ¥27520 / AUD$290', 'Price:€360 / US$371 / ¥52140 / AUD$550', 'Price:€160 / US$165 / ¥23170 / AUD$246', 'Price:€190 / US$196 / ¥27520 / AUD$293', 'Price:€230 / US$237 / ¥33310 / AUD$354', 'Price:€230 / US$237 / ¥33310 / AUD$354', 'Price:€240 / US$247 / ¥34760 / AUD$370', 'Price:€170 / US$175 / ¥24620 / AUD$260', 'Price:€220 / US$227 / ¥31860 / AUD$330', 'Price:€220 / US$227 / ¥31860 / AUD$330']
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 assigned a wrong price to this! It happens just after a mineral with this "unexpected name" and then whole rest of list has wrong prices. See image below: So as this string is different than any other, further code can't split it and gives error: cutted2 = split2.pop(1) ^^^^^^^^^^^^^ IndexError: pop index out of range I tried to ignore these errors and used one of methods used in different Stackoverflow page: try: cutted2 = split2.pop(1) except IndexError: continue It did work, no errors appeared...But then it was assigning wrong prices to wrong minerals (as I noticed)!!! How can I change code to just IGNORE these "strange" names and just go on with list? Below is whole code, it stops on URL5 as I remember and gives this pop index error: import requests from bs4 import BeautifulSoup import re def collecter(URL): headers = {"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.114 Safari/537.36"} soup = BeautifulSoup(requests.get(URL, headers=headers).text, "lxml") names = [n.getText(strip=True) for n in soup.select("table tr td font a")] prices = [ p.getText(strip=True).split("Price:")[-1] for p in soup.select("table tr td font font") ] names[:] = [" ".join(n.split()) for n in names if not n.startswith("[")] prices[:] = [p for p in prices if p] with open("Minerals.txt", "a+", encoding='utf-8') as file: for name, price in zip(names, prices): # print(f"{name}\n{price}") # print("-" * 50) filename = str(name)+" "+str(price)+"\n" split1 = filename.split(' / ') cutted1 = split1.pop(0) split2 = cutted1.split(": ") try: cutted2 = split2.pop(1) except IndexError: continue two_prices = cutted2+" "+split1.pop(0)+"\n" file.write(two_prices) URL1 = "https://www.fabreminerals.com/search_results.php?LANG=EN&SearchTerms=&submit=Buscar&MineralSpeciment=&Country=&Locality=&PriceRange=&checkbox=enventa&First=0" URL2 = "https://www.fabreminerals.com/search_results.php?LANG=EN&SearchTerms=&submit=Buscar&MineralSpeciment=&Country=&Locality=&PriceRange=&checkbox=enventa&First=25" URL3 = "https://www.fabreminerals.com/search_results.php?LANG=EN&SearchTerms=&submit=Buscar&MineralSpeciment=&Country=&Locality=&PriceRange=&checkbox=enventa&First=50" URL4 = "https://www.fabreminerals.com/search_results.php?LANG=EN&SearchTerms=&submit=Buscar&MineralSpeciment=&Country=&Locality=&PriceRange=&checkbox=enventa&First=75" URL5 = "https://www.fabreminerals.com/search_results.php?LANG=EN&SearchTerms=&submit=Buscar&MineralSpeciment=&Country=&Locality=&PriceRange=&checkbox=enventa&First=100" URL6 = "https://www.fabreminerals.com/search_results.php?LANG=EN&SearchTerms=&submit=Buscar&MineralSpeciment=&Country=&Locality=&PriceRange=&checkbox=enventa&First=125" URL7 = "https://www.fabreminerals.com/search_results.php?LANG=EN&SearchTerms=&submit=Buscar&MineralSpeciment=&Country=&Locality=&PriceRange=&checkbox=enventa&First=150" URL8 = "https://www.fabreminerals.com/search_results.php?LANG=EN&SearchTerms=&submit=Buscar&MineralSpeciment=&Country=&Locality=&PriceRange=&checkbox=enventa&First=175" URL9 = "https://www.fabreminerals.com/search_results.php?LANG=EN&SearchTerms=&submit=Buscar&MineralSpeciment=&Country=&Locality=&PriceRange=&checkbox=enventa&First=200" URL10 = "https://www.fabreminerals.com/search_results.php?LANG=EN&SearchTerms=&submit=Buscar&MineralSpeciment=&Country=&Locality=&PriceRange=&checkbox=enventa&First=225" URL11 = "https://www.fabreminerals.com/search_results.php?LANG=EN&SearchTerms=&submit=Buscar&MineralSpeciment=&Country=&Locality=&PriceRange=&checkbox=enventa&First=250" URL12 = "https://www.fabreminerals.com/search_results.php?LANG=EN&SearchTerms=&submit=Buscar&MineralSpeciment=&Country=&Locality=&PriceRange=&checkbox=enventa&First=275" URL13 = "https://www.fabreminerals.com/search_results.php?LANG=EN&SearchTerms=&submit=Buscar&MineralSpeciment=&Country=&Locality=&PriceRange=&checkbox=enventa&First=300" URL14 = "https://www.fabreminerals.com/search_results.php?LANG=EN&SearchTerms=&submit=Buscar&MineralSpeciment=&Country=&Locality=&PriceRange=&checkbox=enventa&First=325" collecter(URL1) collecter(URL2) collecter(URL3) collecter(URL4) collecter(URL5) collecter(URL6) collecter(URL7) collecter(URL8) collecter(URL9) collecter(URL10) collecter(URL11) collecter(URL12) collecter(URL13) collecter(URL14) EDIT: THIS IS FULLY WORKING CODE BELOW, THANKS FOR HELP GUYS! import requests from bs4 import BeautifulSoup import re for URL in range(0,2569,25): headers = {"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.114 Safari/537.36"} soup = BeautifulSoup(requests.get(f'https://www.fabreminerals.com/search_results.php?LANG=EN&SearchTerms=&submit=Buscar&MineralSpeciment=&Country=&Locality=&PriceRange=&checkbox=enventa&First={URL}', headers=headers).text, "lxml") names = [n.getText(strip=True) for n in soup.select("table tr td font>a")] prices = [p.getText(strip=True).split("Price:")[-1] for p in soup.select("table tr td font>font")] names[:] = [" ".join(n.split()) for n in names if not n.startswith("[") ] prices[:] = [p for p in prices if p] with open("MineralsList.txt", "a+", encoding='utf-8') as file: for name, price in zip(names, prices): # print(f"{name}\n{price}") # print("-" * 50) filename = str(name)+" "+str(price)+"\n" split1 = filename.split(' / ') cutted1 = split1.pop(0) split2 = cutted1.split(": ") cutted2 = split2.pop(1) try: two_prices = cutted2+" "+split1.pop(0)+"\n" except IndexError: two_prices = cutted2+"\n" file.write(two_prices) But after some changes it stops on new error - it can't find a string by given properties, so error "IndexError: pop from empty list" appears... Not even soup.select("table tr td font>font") helped, like it did in 'names'
[ "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 page will also help:\nsoup.select(\"table tr td font>a[href*='CODE']\")\n\n", "You can try the next example along with pagination\nimport requests\nfrom bs4 import BeautifulSoup\n\nfor URL in range(0,100,25):\n headers = {\"User-Agent\": \"Mozilla/5.0\"}\n\n soup = BeautifulSoup(requests.get(f'https://www.fabreminerals.com/search_results.php?LANG=EN&SearchTerms=&submit=Buscar&MineralSpeciment=&Country=&Locality=&PriceRange=&checkbox=enventa&First={URL}', headers=headers).text, \"lxml\")\n\n names = [ x.get_text(strip=True) for x in soup.select('table tr td font a')][:25]\n print(names)\n prices = [ x.get_text(strip=True) for x in soup.select('table tr td font:nth-child(3)')][:25]\n print(prices)\n\n # with open(\"Minerals.txt\", \"a+\", encoding='utf-8') as file:\n # for name, price in zip(names, prices):\n # # print(f\"{name}\\n{price}\")\n # # print(\"-\" * 50)\n # filename = str(name)+\" \"+str(price)+\"\\n\"\n # split1 = filename.split(' / ') \n # cutted1 = split1.pop(0)\n # split2 = cutted1.split(\": \")\n # try:\n # cutted2 = split2.pop(1)\n # except IndexError:\n # continue\n # two_prices = cutted2+\" \"+split1.pop(0)+\"\\n\"\n # file.write(two_prices)\n \n\nOutput:\n[\"NX51AH2:\\n'lepidolite' after Elbaite with Elbaite\", \"TH27AL9:\\n'Pearceite' with Calcite\", \"TFM69AN5:\\n'Stilbite'\", 'SM90CEX:\\nAcanthite', 'TMA97AN5:\\nAcanthite', 'TB90AE8:\\n Acanthite', 'TZ71AK9:\\nAcanthite', 'EC63G1:\\nAcanthite', 'MN56K9:\\nAcanthite', 'TF89AL3:\\nAcanthite (Se-bearing) with Polybasite (Se-bearing) and Calcite', 'TP66AJ8:\\nAcanthite (Se-bearing) with Pyrite', 'TY86AN2:\\nAcanthite after Polybasite', 'TA66AF6:\\nAcanthite with Calcite', 'JFD104AO2:\\nAcanthite with Calcite', 'TX36AL6:\\nAcanthite with Calcite', 'TA48AH1:\\nAcanthite with Chalcopyrite', 'EF89L9:\\nAcanthite with Pyrite and Calcite', 'TX89AN0:\\nAcanthite with Siderite and Proustite', 'EA56K0:\\nAcanthite with Silver', 'EC48K0:\\nAcanthite with Silver', '11AT12:\\nAcanthite, Calcite', '9EF89L9:\\nAcanthite, Pyrite, Calcite', 'SM75TDA:\\nAdamite', '2M14:\\nAdamite', '20MJX66:\\nAdamite']\n['Price:€580 / US$598 / ¥84010 / AUD$890', 'Price:€220 / US$227 / ¥31860 / AUD$330', 'Price:€450 / US$464 / ¥65180 / AUD$690', 'Price:€90 / US$92 / ¥13030 / AUD$130', 'Price:€240 / US$247 / ¥34760 / AUD$370', 'Price:€540 / US$557 / \n¥78220 / AUD$830', 'Price:€580 / US$598 / ¥84010 / AUD$890', 'Price:€85 / US$87 / ¥12310 / AUD$130', 'Price:€155 / US$159 / ¥22450 / AUD$230', 'Price:€460 / US$474 / ¥66630 / AUD$700', 'Price:€1500 / US$1547 / ¥217290 / AUD$2310', 'Price:€1600 / US$1651 / ¥231770 / AUD$2460', 'Price:€160 / US$165 / ¥23170 / AUD$240', 'Price:€240 / US$247 / ¥34760 / AUD$370', 'Price:€1200 / US$1238 / ¥173830 / AUD$1850', 'Price:€290 / US$299 / ¥42000 / AUD$440', 'Price:€480 / US$495 / ¥69530 / AUD$740', 'Price:€4800 / US$4953 / ¥695320 / AUD$7400', 'Price:€150 / US$154 / ¥21720 / AUD$230', 'Price:€290 / US$299 / ¥42000 / AUD$440', 'Price:€70 / US$72 / ¥10140 / AUD$100', 'Price:€320 / US$330 / ¥46350 / AUD$490', 'Price:€75 / US$77 / ¥10860 / AUD$110', 'Price:€90 / US$92 / ¥13030 / AUD$130', 'Price:€140 / US$144 / ¥20280 / AUD$215']\n['5TD76M9:\\nAdamite', 'MA54AE9:\\nAdamite (variety Cu-bearing adamite) with Calcite', 'EA11Y6:\\nAdamite (variety cuprian)', 'EB14Y6:\\nAdamite (variety cuprian)', 'MC11X8:\\nAdamite (variety cuprian) with Smithsonite', 'JRM10AN8:\\nAegirine', 'MFA46AP3:\\nAegirine with Zircon, Orthoclase and Quartz (variety smoky)', 'EM48AF8:\\nAlabandite with Calcite', 'MC92T6:\\nAlabandite with Calcite and Rhodochrosite', 'TF16AN1:\\nAlabandite with Rhodochrosite', 'TX17S1:\\nAlabandite with Rhodochrosite', 'TD34S1:\\nAlabandite with Rhodochrosite', '10TR46:\\nAlmandine', 'HM90EJ:\\nAnalcime', 'EFH36AP3:\\nAnalcime with Natrolite, Rhodochrosite and Serandite', 'ELR67AP1:\\nAnalcime with Quartz', 'EML88AP1:\\nAnalcime with Quartz', 'TF87AF4:\\nAndorite', 'TR88AJ3:\\nAndorite', 'ND56AN0:\\nAndorite with Zinkenite', 'SM180NH:\\nAndradite (variety demantoid)', 'MT86AL3:\\nAndradite (variety demantoid) with Calcite', 'MA27AL7:\\nAndradite (variety demantoid) with Calcite', 'TC80TL:\\nAndradite (variety topazolite) with Clinochlore', 'TC85TE:\\nAndradite (variety topazolite) with Clinochlore']\n['Price:€180 / US$185 / ¥26070 / AUD$270', 'Price:€840 / US$866 / ¥121680 / AUD$1290', 'Price:€60 / US$61 / ¥8690 / \nAUD$90', 'Price:€90 / US$92 / ¥13030 / AUD$130', 'Price:€70 / US$72 / ¥10140 / AUD$100', 'Price:€580 / US$598 / ¥84010 / AUD$890', 'Price:€1600 / US$1651 / ¥231770 / AUD$2468', 'Price:€2700 / US$2786 / ¥391120 / AUD$4160', 'Price:€740 / US$763 / ¥107190 / AUD$1140', 'Price:€110 / US$113 / ¥15930 / AUD$160', 'Price:€220 / US$227 / ¥31860 / AUD$330', 'Price:€920 / US$949 / ¥133270 / AUD$1410', 'Price:€140 / US$144 / ¥20280 / AUD$210', 'Price:€90 / US$92 / ¥13030 / AUD$130', 'Price:€130 / US$134 / ¥18830 / AUD$200', 'Price:€260 / US$268 / ¥37660 / AUD$400', 'Price:€380 / US$392 / ¥55040 / AUD$580', 'Price:€240 / US$247 / ¥34760 / AUD$370', 'Price:€390 / US$402 / ¥56490 / AUD$600', 'Price:€150 / US$154 / ¥21720 / AUD$230', 'Price:€180 / US$185 / ¥26070 / AUD$270', 'Price:€1600 / US$1651 / ¥231770 / AUD$2460', 'Price:€2200 / US$2270 / ¥318690 / AUD$3390', 'Price:€80 / US$82 / ¥11580 / AUD$120', 'Price:€85 / US$87 / ¥12310 / AUD$130']\n['T29NAK3:\\nAndradite (variety topazolite) with Clinochlore', 'TC85TV:\\nAndradite (variety topazolite) with Clinochlore', 'T89GH5:\\nAndradite (variety topazolite) with Clinochlore', 'TQ94Q0:\\nAndradite (variety topazolite) with Stilbite', 'SM140TFV:\\nAndradite on Microcline', 'HM140NG:\\nAndradite with Calcite', 'GM66R9:\\nAndradite with Clinochlore', 'SM70TYW:\\nAndradite with Epidote', 'TC290TVH:\\nAndradite with Epidote and Microcline', 'TKX11AO7:\\nAndradite with Microcline', 'TC2100TEJ:\\nAndradite with Microcline', 'TH16AN2:\\nAndradite with Microcline', 'TTX66AO7:\\nAndradite with Microcline', 'TC2150TJL:\\nAndradite with Microcline', 'TQ96AN2:\\nAndradite with Microcline', 'TF48AF2:\\nAnglesite', 'MA47AL4:\\nAnglesite with Galena', 'LQ88AE6:\\nAnglesite with Galena', 'ER90AL8:\\nAnglesite with Galena', 'TP70AE1:\\nAnglesite with Galena', 'N54NAL5:\\nAnglesite with Galena', 'GV96R9:\\nAnhydrite with Calcite and Pyrite', '11TV99:\\nAnhydrite, Calcite', 'MG26AL4:\\nAnorthoroselite with Calcite', 'XM260NFF:\\nAragonite']\n['Price:€240 / US$247 / ¥34760 / AUD$370', 'Price:€85 / US$87 / ¥12310 / AUD$130', 'Price:€220 / US$227 / ¥31860 / AUD$330', 'Price:€980 / US$1011 / ¥141960 / AUD$1510', 'Price:€140 / US$144 / ¥20280 / AUD$210', 'Price:€140 / US$144 / ¥20280 / AUD$210', 'Price:€160 / US$165 / ¥23170 / AUD$240', 'Price:€70 / US$72 / ¥10140 / AUD$100', 'Price:€90 / US$92 / ¥13030 / AUD$130', 'Price:€70 / US$72 / ¥10140 / AUD$100', 'Price:€100 / US$103 / ¥14480 / AUD$150', 'Price:€110 / US$113 / ¥15930 / AUD$160', 'Price:€140 / US$144 / ¥20280 / AUD$210', 'Price:€150 / US$154 / ¥21720 / AUD$230', 'Price:€220 / US$227 / ¥31860 / AUD$330', 'Price:€380 / US$392 / ¥55040 / AUD$580', 'Price:€220 / US$227 / ¥31860 / AUD$330', 'Price:€360 / US$371 / ¥52140 / AUD$550', 'Price:€540 / US$557 / ¥78220 / AUD$830', 'Price:€540 / US$557 / ¥78220 / AUD$830', 'Price:€940 / US$969 / ¥136160 / AUD$1450', 'Price:€220 / US$227 / ¥31860 / AUD$330', 'Price:€460 / US$474 / ¥66630 / AUD$700', 'Price:€140 / US$144 / ¥20280 / AUD$210', 'Price:€60 / US$61 / ¥8690 / AUD$92'] \n['XM295EAR:\\nAragonite', 'ETE46AP2:\\nAragonite', 'EXM26AP0:\\nAragonite', 'EYB26AP0:\\nAragonite', 'EXE56AP2:\\nAragonite', 'ETF46AP0:\\nAragonite', 'XM2160ERF:\\nAragonite', 'EXM46AP0:\\nAragonite', 'XM2190MEX:\\nAragonite', 'XM2780EFT:\\nAragonite', 'EHM93AO9:\\nAragonite', 'TYB37AO8:\\nAragonite (variety Cu-bearing aragonite)', 'SM99AM3:\\nAragonite (variety cuprian)', '1M06:\\nAragonite (variety flos ferri)', 'TG69AL3:\\nAragonite (variety tarnowitzite)', 'MLC96AO2:\\nAragonite on Calcite', 'MLE68AO2:\\nAragonite on Calcite', 'MTB66AP3:\\nAragonite with Quartz (variety hematoide)', 'MXF96AP3:\\nAragonite with Quartz (variety hematoide)', 'MRR47AP3:\\nAragonite with Quartz (variety hematoide)', 'MTR37AP3:\\nAragonite with Quartz (variety hematoide)', 'JFD193AP3:\\nArfvedsonite with Microcline', 'TFX76AO7:\\nArsenopyrite with Calcite, Pyrite, Sphalerite and Rhodochrosite', 'NB37AL3:\\nArsenopyrite with Muscovite', 'HM220NX:\\nArsenopyrite with Muscovite']\n['Price:€95 / US$98 / ¥13760 / AUD$146', 'Price:€140 / US$144 / ¥20280 / AUD$210', 'Price:€140 / US$144 / ¥20280 / AUD$210', 'Price:€140 / US$144 / ¥20280 / AUD$210', 'Price:€150 / US$154 / ¥21720 / AUD$230', 'Price:€150 / US$154 / \n¥21720 / AUD$230', 'Price:€160 / US$165 / ¥23170 / AUD$246', 'Price:€160 / US$165 / ¥23170 / AUD$240', 'Price:€190 / US$196 / ¥27520 / AUD$293', 'Price:€780 / US$804 / ¥112990 / AUD$1203', 'Price:€880 / US$908 / ¥127470 / AUD$1350', 'Price:€240 / US$247 / ¥34760 / AUD$370', 'Price:€480 / US$495 / ¥69530 / AUD$740', 'Price:€100 / US$103 / ¥14480 / AUD$150', 'Price:€460 / US$474 / ¥66630 / AUD$700', 'Price:€190 / US$196 / ¥27520 / AUD$290', 'Price:€360 / US$371 \n/ ¥52140 / AUD$550', 'Price:€160 / US$165 / ¥23170 / AUD$246', 'Price:€190 / US$196 / ¥27520 / AUD$293', 'Price:€230 / US$237 / ¥33310 / AUD$354', 'Price:€230 / US$237 / ¥33310 / AUD$354', 'Price:€240 / US$247 / ¥34760 / AUD$370', 'Price:€170 / US$175 / ¥24620 / AUD$260', 'Price:€220 / US$227 / ¥31860 / AUD$330', 'Price:€220 / US$227 / ¥31860 / AUD$330']\n\n" ]
[ 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. Currently I have temp_board = ma.masked_where(board == value, board, True) boxes = np.full((3, 3), False) for x in range(3): for y in range(3): boxes[x, y] = not np.any(temp_board.mask[x * 3:(x + 1) * 3, y * 3:(y + 1) * 3]) board is a 9x9 matrix containing numbers 0-9 but value can only equal 1-9 Here is an example of what the output should look like # input board = np.array([[4, 0, 9, 0, 7, 2, 0, 1, 3], [7, 0, 2, 8, 3, 0, 6, 0, 0], [0, 1, 6, 0, 4, 9, 8, 7, 0], [2, 0, 0, 1, 0, 0, 0, 6, 0], [5, 4, 7, 0, 0, 0, 2, 0, 0], [6, 9, 0, 0, 0, 4, 0, 3, 5], [8, 0, 3, 4, 0, 0, 0, 0, 6], [0, 0, 0, 0, 0, 3, 1, 0, 0], [0, 6, 0, 9, 0, 0, 0, 4, 0]]) value = 9 # output [[False False True] [False True True] [ True False True]] The method I am using works but is terribly inefficient, I was wondering if there was a faster way to do this. A: One way, not very subtle, but fast, would be to have a lookup index table look=np.zeros((9,9,9), dtype=bool) look[0,:3,:3]=True look[1,:3,3:6]=True look[2,:3,6:]=True look[3,3:6,:3]=True look[4,3:6,3:6]=True look[5,3:6,6:]=True look[6,6:,:3]=True look[7,6:,3:6]=True look[8,6:,6:]=True def inblock(board, blnum, val): return val in board[look[blnum]] To get directly you matrix, you can then ~(look*board == value).any(axis=(1,2)).reshape(3,3) look*board is a 9x9x9 matrix, filtering only one block each ((look*board)[k] contains 0 everywhere, but in block k, which are a copy of the board). (look*board == value) is a boolean version of that. so (look*board == value).any(axis=(1,2)) are 9 values, True iff block[k] contains value. Since I use a 1 dimension block array, you can reshape to get 3x3 matrix. And then negate the result to imitate your output. Note that there are surely more subtle ways to build the look table. For example, using your own for loop, slightly modified. But well, that in only one time. Alternative Just to be even more direct (and, frankly, what I was looking for, when I started to think to your question), would be this look=np.zeros((3,3,9,9), dtype=bool) for i in range(3): for j in range(3): look[i,j,i*3:(i+1)*3,j*3:(j+1)*3] = True ~np.einsum('ijkl,kl', look, board==value) The fact that I use (3,3,9,9) shape and then avoid reshape is not really the point (it is the same cost, just a presentation problem). I could have done that for the previous solution. Nor is the fact that this time, I use a double loop to create the look table. That again, I could have done it before. It is not look that changes. Just the usage of einsum. It is not better than my previous solution. But it is what I had in mind at first: use a sort of matrix multiplication. Timings ~(look*board == value).any(axis=(2,3)) : 18.9 μs (Note this is my previous solution, adapted to (3,3,9,9) shape ~np.einsum('ijkl,kl', look, board==value) : 13.6 μs So, my second solution is not only the one I wanted. But it appears it is also faster.
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 range(3): for y in range(3): boxes[x, y] = not np.any(temp_board.mask[x * 3:(x + 1) * 3, y * 3:(y + 1) * 3]) board is a 9x9 matrix containing numbers 0-9 but value can only equal 1-9 Here is an example of what the output should look like # input board = np.array([[4, 0, 9, 0, 7, 2, 0, 1, 3], [7, 0, 2, 8, 3, 0, 6, 0, 0], [0, 1, 6, 0, 4, 9, 8, 7, 0], [2, 0, 0, 1, 0, 0, 0, 6, 0], [5, 4, 7, 0, 0, 0, 2, 0, 0], [6, 9, 0, 0, 0, 4, 0, 3, 5], [8, 0, 3, 4, 0, 0, 0, 0, 6], [0, 0, 0, 0, 0, 3, 1, 0, 0], [0, 6, 0, 9, 0, 0, 0, 4, 0]]) value = 9 # output [[False False True] [False True True] [ True False True]] The method I am using works but is terribly inefficient, I was wondering if there was a faster way to do this.
[ "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(board, blnum, val):\n return val in board[look[blnum]]\n\nTo get directly you matrix, you can then\n~(look*board == value).any(axis=(1,2)).reshape(3,3)\n\nlook*board is a 9x9x9 matrix, filtering only one block each ((look*board)[k] contains 0 everywhere, but in block k, which are a copy of the board).\n(look*board == value) is a boolean version of that.\nso (look*board == value).any(axis=(1,2)) are 9 values, True iff block[k] contains value.\nSince I use a 1 dimension block array, you can reshape to get 3x3 matrix.\nAnd then negate the result to imitate your output.\nNote that there are surely more subtle ways to build the look table. For example, using your own for loop, slightly modified. But well, that in only one time.\nAlternative\nJust to be even more direct (and, frankly, what I was looking for, when I started to think to your question), would be this\nlook=np.zeros((3,3,9,9), dtype=bool)\nfor i in range(3):\n for j in range(3):\n look[i,j,i*3:(i+1)*3,j*3:(j+1)*3] = True\n\n~np.einsum('ijkl,kl', look, board==value)\n\nThe fact that I use (3,3,9,9) shape and then avoid reshape is not really the point (it is the same cost, just a presentation problem). I could have done that for the previous solution.\nNor is the fact that this time, I use a double loop to create the look table. That again, I could have done it before. It is not look that changes. Just the usage of einsum. It is not better than my previous solution. But it is what I had in mind at first: use a sort of matrix multiplication.\nTimings\n~(look*board == value).any(axis=(2,3)) : 18.9 μs\n(Note this is my previous solution, adapted to (3,3,9,9) shape\n~np.einsum('ijkl,kl', look, board==value) : 13.6 μs\nSo, my second solution is not only the one I wanted. But it appears it is also faster.\n" ]
[ 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 before first _: df['Column3'] = df.index.str.extract(r'([^_]+)', expand=False) print (df) column1 column2 Column3 catA_gas abc abc catA catB_green abc abc catB catA_apple abc abc catA Or if need 2 new columns use Index.to_series and Series.str.split: df[['Column3','Column4']] = df.index.to_series().str.split('_', expand=True) print (df) column1 column2 Column3 Column4 catA_gas abc abc catA gas catB_green abc abc catB green catA_apple abc abc catA apple
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_series and Series.str.split:\ndf[['Column3','Column4']] = df.index.to_series().str.split('_', expand=True)\nprint (df)\n column1 column2 Column3 Column4\ncatA_gas abc abc catA gas\ncatB_green abc abc catB green\ncatA_apple abc abc catA apple\n\n" ]
[ 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 1690.5 2.0 46.000 2.0 2 7 1 10800 1700.5 2.0 101.000 4.0 3 7 2 0 1682.5 2.0 12.500 1.0 4 7 2 3600 1692.5 2.0 33.500 2.0 5 7 2 10800 1702.5 2.0 86.500 4.0 6 7 3 0 1684.5 2.0 8.500 1.0 7 7 3 3600 1694.5 2.0 15.000 2.0 8 7 3 10800 1704.5 2.0 34.000 4.0 What I need to do is Calculate the deviation (%) from averages with a "seconds"-value not equal to 0 from those averages with a seconds value of zero, where the subject_id and Setting_id are the same i.e. setting_id ==7 & subject_id ==1 would be: (result/baseline)*100 ------> for 3600 seconds: (46/24)*100 = +192% ------> for 10800 seconds: (101/24)*100 = +421% .... baseline = average-result with a seconds value of 0 .... result = average-result with a seconds value other than 0 The resulting df should look like this setting_id subject_id seconds owner_id average deviation duration_id 0 7 1 0 2 24 0 1 1 7 1 3600 2 46 192 2 2 7 1 10800 2 101 421 4 I want to use these calculations then to plot a regression graph (with seaborn) of deviations from baseline I have played around with this df for 2 days now and tried different forloops but I just can´t figure out the correct way. A: You can use: # identify rows with 0 m = df['seconds'].eq(0) # compute the sum of rows with 0 s = (df['average'].where(m) .groupby([df['setting_id'], df['subject_id']]) .sum() ) # compute the deviation per group deviation = ( df[['setting_id', 'subject_id']] .merge(s, left_on=['setting_id', 'subject_id'], right_index=True, how='left') ['average'] .rdiv(df['average']).mul(100) .round().astype(int) # optional .mask(m, 0) ) df['deviation'] = deviation # or # out = df.assign(deviation=deviation) Output: setting_id subject_id seconds result_id owner_id average duration_id deviation 0 7 1 0 1680.5 2.0 24.0 1.0 0 1 7 1 3600 1690.5 2.0 46.0 2.0 192 2 7 1 10800 1700.5 2.0 101.0 4.0 421 3 7 2 0 1682.5 2.0 12.5 1.0 0 4 7 2 3600 1692.5 2.0 33.5 2.0 268 5 7 2 10800 1702.5 2.0 86.5 4.0 692 6 7 3 0 1684.5 2.0 8.5 1.0 0 7 7 3 3600 1694.5 2.0 15.0 2.0 176 8 7 3 10800 1704.5 2.0 34.0 4.0 400
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 1 10800 1700.5 2.0 101.000 4.0 3 7 2 0 1682.5 2.0 12.500 1.0 4 7 2 3600 1692.5 2.0 33.500 2.0 5 7 2 10800 1702.5 2.0 86.500 4.0 6 7 3 0 1684.5 2.0 8.500 1.0 7 7 3 3600 1694.5 2.0 15.000 2.0 8 7 3 10800 1704.5 2.0 34.000 4.0 What I need to do is Calculate the deviation (%) from averages with a "seconds"-value not equal to 0 from those averages with a seconds value of zero, where the subject_id and Setting_id are the same i.e. setting_id ==7 & subject_id ==1 would be: (result/baseline)*100 ------> for 3600 seconds: (46/24)*100 = +192% ------> for 10800 seconds: (101/24)*100 = +421% .... baseline = average-result with a seconds value of 0 .... result = average-result with a seconds value other than 0 The resulting df should look like this setting_id subject_id seconds owner_id average deviation duration_id 0 7 1 0 2 24 0 1 1 7 1 3600 2 46 192 2 2 7 1 10800 2 101 421 4 I want to use these calculations then to plot a regression graph (with seaborn) of deviations from baseline I have played around with this df for 2 days now and tried different forloops but I just can´t figure out the correct way.
[ "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_id', 'subject_id'], right_index=True, how='left')\n ['average']\n .rdiv(df['average']).mul(100)\n .round().astype(int) # optional\n .mask(m, 0)\n)\n\ndf['deviation'] = deviation\n# or\n# out = df.assign(deviation=deviation)\n\nOutput:\n setting_id subject_id seconds result_id owner_id average duration_id deviation\n0 7 1 0 1680.5 2.0 24.0 1.0 0\n1 7 1 3600 1690.5 2.0 46.0 2.0 192\n2 7 1 10800 1700.5 2.0 101.0 4.0 421\n3 7 2 0 1682.5 2.0 12.5 1.0 0\n4 7 2 3600 1692.5 2.0 33.5 2.0 268\n5 7 2 10800 1702.5 2.0 86.5 4.0 692\n6 7 3 0 1684.5 2.0 8.5 1.0 0\n7 7 3 3600 1694.5 2.0 15.0 2.0 176\n8 7 3 10800 1704.5 2.0 34.0 4.0 400\n\n" ]
[ 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 to page 22 it is easy within pyPdf to iterate over each page of the document or each destination in the document's outline; however, i cannot figure out how to get the page number where the destination points. does anybody know how to find the referencing page number for each destination in the outline? A: I figured it out: class Darrell(pyPdf.PdfFileReader): def getDestinationPageNumbers(self): def _setup_outline_page_ids(outline, _result=None): if _result is None: _result = {} for obj in outline: if isinstance(obj, pyPdf.pdf.Destination): _result[(id(obj), obj.title)] = obj.page.idnum elif isinstance(obj, list): _setup_outline_page_ids(obj, _result) return _result def _setup_page_id_to_num(pages=None, _result=None, _num_pages=None): if _result is None: _result = {} if pages is None: _num_pages = [] pages = self.trailer["/Root"].getObject()["/Pages"].getObject() t = pages["/Type"] if t == "/Pages": for page in pages["/Kids"]: _result[page.idnum] = len(_num_pages) _setup_page_id_to_num(page.getObject(), _result, _num_pages) elif t == "/Page": _num_pages.append(1) return _result outline_page_ids = _setup_outline_page_ids(self.getOutlines()) page_id_to_page_numbers = _setup_page_id_to_num() result = {} for (_, title), page_idnum in outline_page_ids.iteritems(): result[title] = page_id_to_page_numbers.get(page_idnum, '???') return result pdf = Darrell(open(PATH-TO-PDF, 'rb')) template = '%-5s %s' print template % ('page', 'title') for p,t in sorted([(v,k) for k,v in pdf.getDestinationPageNumbers().iteritems()]): print template % (p+1,t) A: Small update to @darrell class to be able to parse UTF-8 outlines, which I post as answer because comment would be hard to read. Problem is in pyPdf.pdf.Destination.title which may be returned in two flavors: pyPdf.generic.TextStringObject pyPdf.generic.ByteStringObject so that output from _setup_outline_page_ids() function returns also two different types for title object, which fails with UnicodeDecodeError if outline title contains anything then ASCII. I added this code to solve the problem: if isinstance(title, pyPdf.generic.TextStringObject): title = title.encode('utf-8') of whole class: class PdfOutline(pyPdf.PdfFileReader): def getDestinationPageNumbers(self): def _setup_outline_page_ids(outline, _result=None): if _result is None: _result = {} for obj in outline: if isinstance(obj, pyPdf.pdf.Destination): _result[(id(obj), obj.title)] = obj.page.idnum elif isinstance(obj, list): _setup_outline_page_ids(obj, _result) return _result def _setup_page_id_to_num(pages=None, _result=None, _num_pages=None): if _result is None: _result = {} if pages is None: _num_pages = [] pages = self.trailer["/Root"].getObject()["/Pages"].getObject() t = pages["/Type"] if t == "/Pages": for page in pages["/Kids"]: _result[page.idnum] = len(_num_pages) _setup_page_id_to_num(page.getObject(), _result, _num_pages) elif t == "/Page": _num_pages.append(1) return _result outline_page_ids = _setup_outline_page_ids(self.getOutlines()) page_id_to_page_numbers = _setup_page_id_to_num() result = {} for (_, title), page_idnum in outline_page_ids.iteritems(): if isinstance(title, pyPdf.generic.TextStringObject): title = title.encode('utf-8') result[title] = page_id_to_page_numbers.get(page_idnum, '???') return result A: Darrell's class can be modified slightly to produce a multi-level table of contents for a pdf (in the manner of pdftoc in the pdftk toolkit.) My modification adds one more parameter to _setup_page_id_to_num, an integer "level" which defaults to 1. Each invocation increments the level. Instead of storing just the page number in the result, we store the pair of page number and level. Appropriate modifications should be applied when using the returned result. I am using this to implement the "PDF Hacks" browser-based page-at-a-time document viewer with a sidebar table of contents which reflects LaTeX section, subsection etc bookmarks. I am working on a shared system where pdftk can not be installed but where python is available. A: This is just what I was looking for. Darrell's additions to PdfFileReader should be part of PyPDF2. I wrote a little recipe that uses PyPDF2 and sejda-console to split a PDF by bookmarks. In my case there are several Level 1 sections that I want to keep together. This script allows me to do that and give the resulting files meaningful names. import operator import os import subprocess import sys import time import PyPDF2 as pyPdf # need to have sejda-console installed # change this to point to your installation sejda = 'C:\\sejda-console-1.0.0.M2\\bin\\sejda-console.bat' class Darrell(pyPdf.PdfFileReader): ... if __name__ == '__main__': t0= time.time() # get the name of the file to split as a command line arg pdfname = sys.argv[1] # open up the pdf pdf = Darrell(open(pdfname, 'rb')) # build list of (pagenumbers, newFileNames) splitlist = [(1,'FrontMatter')] # Customize name of first section template = '%-5s %s' print template % ('Page', 'Title') print '-'*72 for t,p in sorted(pdf.getDestinationPageNumbers().iteritems(), key=operator.itemgetter(1)): # Customize this to get it to split where you want if t.startswith('Chapter') or \ t.startswith('Preface') or \ t.startswith('References'): print template % (p+1, t) # this customizes how files are renamed new = t.replace('Chapter ', 'Chapter')\ .replace(': ', '-')\ .replace(': ', '-')\ .replace(' ', '_') splitlist.append((p+1, new)) # call sejda tools and split document call = sejda call += ' splitbypages' call += ' -f "%s"'%pdfname call += ' -o ./' call += ' -n ' call += ' '.join([str(p) for p,t in splitlist[1:]]) print '\n', call subprocess.call(call) print '\nsejda-console has completed.\n\n' # rename the split files for p,t in splitlist: old ='./%i_'%p + pdfname new = './' + t + '.pdf' print 'renaming "%s"\n to "%s"...'%(old, new), try: os.remove(new) except OSError: pass try: os.rename(old, new) print' succeeded.\n' except: print' failed.\n' print '\ndone. Spliting took %.2f seconds'%(time.time() - t0) A: A solution 10 years later for newer python and PyPDF: from PyPDF2 import PdfReader, PdfWriter filename = "main.pdf" with open(filename, "rb") as f: r = PdfReader(f) bookmarks = list(map(lambda x: (x.title, r.get_destination_page_number(x)), r.outline)) print(bookmarks) for i, b in enumerate(bookmarks): begin = b[1] end = bookmarks[i+1][1] if i < len(bookmarks) - 1 else len(r.pages) # print(len(r.pages[begin:end])) name = b[0] + ".pdf" print(f"{name=}: {begin=}, {end=}") with open(name, "wb") as f: w = PdfWriter(f) for p in r.pages[begin:end]: w.add_page(p) w.write(f)
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 pyPdf to iterate over each page of the document or each destination in the document's outline; however, i cannot figure out how to get the page number where the destination points. does anybody know how to find the referencing page number for each destination in the outline?
[ "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):\n _result[(id(obj), obj.title)] = obj.page.idnum\n elif isinstance(obj, list):\n _setup_outline_page_ids(obj, _result)\n return _result\n\n def _setup_page_id_to_num(pages=None, _result=None, _num_pages=None):\n if _result is None:\n _result = {}\n if pages is None:\n _num_pages = []\n pages = self.trailer[\"/Root\"].getObject()[\"/Pages\"].getObject()\n t = pages[\"/Type\"]\n if t == \"/Pages\":\n for page in pages[\"/Kids\"]:\n _result[page.idnum] = len(_num_pages)\n _setup_page_id_to_num(page.getObject(), _result, _num_pages)\n elif t == \"/Page\":\n _num_pages.append(1)\n return _result\n\n outline_page_ids = _setup_outline_page_ids(self.getOutlines())\n page_id_to_page_numbers = _setup_page_id_to_num()\n\n result = {}\n for (_, title), page_idnum in outline_page_ids.iteritems():\n result[title] = page_id_to_page_numbers.get(page_idnum, '???')\n return result\n\npdf = Darrell(open(PATH-TO-PDF, 'rb'))\ntemplate = '%-5s %s'\nprint template % ('page', 'title')\nfor p,t in sorted([(v,k) for k,v in pdf.getDestinationPageNumbers().iteritems()]):\n print template % (p+1,t)\n\n", "Small update to @darrell class to be able to parse UTF-8 outlines, which I post as answer because comment would be hard to read. \nProblem is in pyPdf.pdf.Destination.title which may be returned in two flavors:\n\npyPdf.generic.TextStringObject\npyPdf.generic.ByteStringObject\n\nso that output from _setup_outline_page_ids() function returns also two different types for title object, which fails with UnicodeDecodeError if outline title contains anything then ASCII.\nI added this code to solve the problem:\nif isinstance(title, pyPdf.generic.TextStringObject):\n title = title.encode('utf-8')\n\nof whole class:\nclass PdfOutline(pyPdf.PdfFileReader):\n\n def getDestinationPageNumbers(self):\n\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):\n _result[(id(obj), obj.title)] = obj.page.idnum\n elif isinstance(obj, list):\n _setup_outline_page_ids(obj, _result)\n return _result\n\n def _setup_page_id_to_num(pages=None, _result=None, _num_pages=None):\n if _result is None:\n _result = {}\n if pages is None:\n _num_pages = []\n pages = self.trailer[\"/Root\"].getObject()[\"/Pages\"].getObject()\n t = pages[\"/Type\"]\n if t == \"/Pages\":\n for page in pages[\"/Kids\"]:\n _result[page.idnum] = len(_num_pages)\n _setup_page_id_to_num(page.getObject(), _result, _num_pages)\n elif t == \"/Page\":\n _num_pages.append(1)\n return _result\n\n outline_page_ids = _setup_outline_page_ids(self.getOutlines())\n page_id_to_page_numbers = _setup_page_id_to_num()\n\n result = {}\n for (_, title), page_idnum in outline_page_ids.iteritems():\n if isinstance(title, pyPdf.generic.TextStringObject):\n title = title.encode('utf-8')\n result[title] = page_id_to_page_numbers.get(page_idnum, '???')\n return result\n\n", "Darrell's class can be modified slightly to produce a multi-level table of contents for a pdf (in the manner of pdftoc in the pdftk toolkit.) \nMy modification adds one more parameter to _setup_page_id_to_num, an integer \"level\" which defaults to 1. Each invocation increments the level. Instead of storing just the page number in the result, we store the pair of page number and level. Appropriate modifications should be applied when using the returned result. \nI am using this to implement the \"PDF Hacks\" browser-based page-at-a-time document viewer with a sidebar table of contents which reflects LaTeX section, subsection etc bookmarks. I am working on a shared system where pdftk can not be installed but where python is available.\n", "This is just what I was looking for. Darrell's additions to PdfFileReader should be part of PyPDF2.\nI wrote a little recipe that uses PyPDF2 and sejda-console to split a PDF by bookmarks. In my case there are several Level 1 sections that I want to keep together. This script allows me to do that and give the resulting files meaningful names.\nimport operator\nimport os\nimport subprocess\nimport sys\nimport time\n\nimport PyPDF2 as pyPdf\n\n# need to have sejda-console installed\n# change this to point to your installation\nsejda = 'C:\\\\sejda-console-1.0.0.M2\\\\bin\\\\sejda-console.bat'\n\nclass Darrell(pyPdf.PdfFileReader):\n ...\n\nif __name__ == '__main__':\n t0= time.time()\n\n # get the name of the file to split as a command line arg\n pdfname = sys.argv[1]\n\n # open up the pdf\n pdf = Darrell(open(pdfname, 'rb'))\n\n # build list of (pagenumbers, newFileNames)\n splitlist = [(1,'FrontMatter')] # Customize name of first section\n\n template = '%-5s %s'\n print template % ('Page', 'Title')\n print '-'*72\n for t,p in sorted(pdf.getDestinationPageNumbers().iteritems(),\n key=operator.itemgetter(1)):\n\n # Customize this to get it to split where you want\n if t.startswith('Chapter') or \\\n t.startswith('Preface') or \\\n t.startswith('References'):\n\n print template % (p+1, t)\n\n # this customizes how files are renamed\n new = t.replace('Chapter ', 'Chapter')\\\n .replace(': ', '-')\\\n .replace(': ', '-')\\\n .replace(' ', '_')\n splitlist.append((p+1, new))\n\n # call sejda tools and split document\n call = sejda\n call += ' splitbypages'\n call += ' -f \"%s\"'%pdfname\n call += ' -o ./'\n call += ' -n '\n call += ' '.join([str(p) for p,t in splitlist[1:]])\n print '\\n', call\n subprocess.call(call)\n print '\\nsejda-console has completed.\\n\\n'\n\n # rename the split files\n for p,t in splitlist:\n old ='./%i_'%p + pdfname\n new = './' + t + '.pdf'\n print 'renaming \"%s\"\\n to \"%s\"...'%(old, new),\n\n try:\n os.remove(new)\n except OSError:\n pass\n\n try:\n os.rename(old, new)\n print' succeeded.\\n'\n except:\n print' failed.\\n'\n\n print '\\ndone. Spliting took %.2f seconds'%(time.time() - t0)\n\n", "A solution 10 years later for newer python and PyPDF:\nfrom PyPDF2 import PdfReader, PdfWriter\nfilename = \"main.pdf\"\n\nwith open(filename, \"rb\") as f:\n r = PdfReader(f)\n\n bookmarks = list(map(lambda x: (x.title, r.get_destination_page_number(x)), r.outline))\n print(bookmarks)\n for i, b in enumerate(bookmarks):\n begin = b[1]\n end = bookmarks[i+1][1] if i < len(bookmarks) - 1 else len(r.pages)\n # print(len(r.pages[begin:end]))\n name = b[0] + \".pdf\"\n print(f\"{name=}: {begin=}, {end=}\")\n with open(name, \"wb\") as f:\n w = PdfWriter(f)\n for p in r.pages[begin:end]:\n w.add_page(p)\n w.write(f)\n\n" ]
[ 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) for token in doc: print(token.text) When I execute this code with a small string it works fine. But when I use a 50 megabyte csv I get the message Text of length 62235045 exceeds maximum of 1000000. The parser and NER models require roughly 1GB of temporary memory per 100,000 characters in the input. This means long texts may cause memory allocation errors. If you're not using the parser or NER, it's probably safe to increase the `nlp.max_length` limit. The limit is in number of characters, so you can check whether your inputs are too long by checking `len(text)`. When I increase the limit to this size my computer gets hard problems.. How can I fix this? It can't be anything special to want to tokenize this amount of data. A: 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. If you only want to tokenize, use spacy.blank("de") and then you can probably increase nlp.max_length to a fairly large limit without running out of RAM. (You'll still eventually run out of RAM if the text gets extremely long, but this takes much much longer than with the parser or NER.) If you want to run the full de_core_news_sm pipeline, then you'd need to break your text up into smaller units. Meaningful units like paragraphs or sections can make sense. The linguistic analysis from the provided pipelines mostly depends on local context within a few neighboring sentences, so having longer texts isn't helpful. Use nlp.pipe to process batches of text more efficiently, see: https://spacy.io/usage/processing-pipelines#processing If you have CSV input, then it might make sense to use individual text fields as the units?
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) When I execute this code with a small string it works fine. But when I use a 50 megabyte csv I get the message Text of length 62235045 exceeds maximum of 1000000. The parser and NER models require roughly 1GB of temporary memory per 100,000 characters in the input. This means long texts may cause memory allocation errors. If you're not using the parser or NER, it's probably safe to increase the `nlp.max_length` limit. The limit is in number of characters, so you can check whether your inputs are too long by checking `len(text)`. When I increase the limit to this size my computer gets hard problems.. How can I fix this? It can't be anything special to want to tokenize this amount of data.
[ "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_length to a fairly large limit without running out of RAM. (You'll still eventually run out of RAM if the text gets extremely long, but this takes much much longer than with the parser or NER.)\nIf you want to run the full de_core_news_sm pipeline, then you'd need to break your text up into smaller units. Meaningful units like paragraphs or sections can make sense. The linguistic analysis from the provided pipelines mostly depends on local context within a few neighboring sentences, so having longer texts isn't helpful. Use nlp.pipe to process batches of text more efficiently, see: https://spacy.io/usage/processing-pipelines#processing\nIf you have CSV input, then it might make sense to use individual text fields as the units?\n" ]
[ 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 Prologix GPIB-USB Controller (see prologix.biz). We found a tutorial at http://heliosoph.mit-links.info/gpib-on-debian-linux-the-easy-way/ and did all of the steps, and it worked! As we don't have the test equipment yet, we wanted to write an emulator in Python using openpty. We do have the GPIB-USB Controller, just not what gets connected to that. I got the emulator working as a perfect replacement for the GPIB-USB. This means that I would follow the "GPIB on Debian ..." tutorial (above) and get output that I programmed the emulator to return. The input and output were done in the same manner as the tutorial just reading and writing to/from a pty device (ie /dev/pts/2) instead of the tty (ie /dev/ttyUSB0). Now that the emulator works, we want to write a front end that can be used to write scripts easily. The goal is to make a kind of macro system that writes a bunch of commands when we call a function. PROBLEM: exists using both the emulator and the device I am using the following Python functions to read, write, and open the tty/pty devices, but I am not getting the same result that I get if I just use echo and cat in bash. tty = os.open(tty_path, os.O_RDWR) os.read(tty, 100) os.write(tty, "++ver") for example, I would expect the following to be equivalent $ cat < /dev/pty/2 & # According to the tutorial, this must be run in parallel $ echo "++ver" > /dev/pty/2 Prologix GPIB Version 1.2.3.4 ... and tty = os.open("/dev/pyt/2", os.o_RDWR) os.read(tty, 100) # In separate Thread to be run in parallel os.write(tty, "++ver") # in main thread The output is very different, please explain why and how I can fix it. FULL CODE is here: http://pastebin.com/PWVsMjD7 A: Well, I asked too soon. I hope someone benefits from this self answer. So 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 import serial class VISA: def __init__(self, tty_name): self.ser = serial.Serial() self.ser.port = tty_name # If it breaks try the below #self.serConf() # Uncomment lines here till it works self.ser.open() self.ser.flushInput() self.ser.flushOutput() self.addr = None self.setAddress(0) def cmd(self, cmd_str): self.ser.write(cmd_str + "\n") sleep(0.5) return self.ser.readline() def serConf(self): self.ser.baudrate = 9600 self.ser.bytesize = serial.EIGHTBITS self.ser.parity = serial.PARITY_NONE self.ser.stopbits = serial.STOPBITS_ONE self.ser.timeout = 0 # Non-Block reading self.ser.xonxoff = False # Disable Software Flow Control self.ser.rtscts = False # Disable (RTS/CTS) flow Control self.ser.dsrdtr = False # Disable (DSR/DTR) flow Control self.ser.writeTimeout = 2 def close(self): self.ser.close() A: You do not actually have to use any special module to read from TTY. Option O_NOCTTY solved my problems with CDCACM example MCU app. I'm sure it will work for you (as you work on Linux too). #!/usr/bin/env python3 import io, os tty = io.TextIOWrapper( io.FileIO( os.open( "/dev/ttyACM1", os.O_NOCTTY | os.O_RDWR), "r+")) for line in iter(tty.readline, None): print(line.strip()) A: Stumbled on this while looking into pty/tty usage in python. I think the original code did not work because echo will add a newline and the python os.write will not. This is shown in your self answer here self.ser.write(cmd_str + "\n") So the original code may have worked if it were os.write(tty, "++ver\n")
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.biz). We found a tutorial at http://heliosoph.mit-links.info/gpib-on-debian-linux-the-easy-way/ and did all of the steps, and it worked! As we don't have the test equipment yet, we wanted to write an emulator in Python using openpty. We do have the GPIB-USB Controller, just not what gets connected to that. I got the emulator working as a perfect replacement for the GPIB-USB. This means that I would follow the "GPIB on Debian ..." tutorial (above) and get output that I programmed the emulator to return. The input and output were done in the same manner as the tutorial just reading and writing to/from a pty device (ie /dev/pts/2) instead of the tty (ie /dev/ttyUSB0). Now that the emulator works, we want to write a front end that can be used to write scripts easily. The goal is to make a kind of macro system that writes a bunch of commands when we call a function. PROBLEM: exists using both the emulator and the device I am using the following Python functions to read, write, and open the tty/pty devices, but I am not getting the same result that I get if I just use echo and cat in bash. tty = os.open(tty_path, os.O_RDWR) os.read(tty, 100) os.write(tty, "++ver") for example, I would expect the following to be equivalent $ cat < /dev/pty/2 & # According to the tutorial, this must be run in parallel $ echo "++ver" > /dev/pty/2 Prologix GPIB Version 1.2.3.4 ... and tty = os.open("/dev/pyt/2", os.o_RDWR) os.read(tty, 100) # In separate Thread to be run in parallel os.write(tty, "++ver") # in main thread The output is very different, please explain why and how I can fix it. FULL CODE is here: http://pastebin.com/PWVsMjD7
[ "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):\n self.ser = serial.Serial()\n self.ser.port = tty_name\n # If it breaks try the below\n #self.serConf() # Uncomment lines here till it works\n\n self.ser.open()\n self.ser.flushInput()\n self.ser.flushOutput()\n\n self.addr = None\n self.setAddress(0)\n\n def cmd(self, cmd_str):\n self.ser.write(cmd_str + \"\\n\")\n sleep(0.5)\n return self.ser.readline()\n\n def serConf(self):\n self.ser.baudrate = 9600\n self.ser.bytesize = serial.EIGHTBITS\n self.ser.parity = serial.PARITY_NONE\n self.ser.stopbits = serial.STOPBITS_ONE\n self.ser.timeout = 0 # Non-Block reading\n self.ser.xonxoff = False # Disable Software Flow Control\n self.ser.rtscts = False # Disable (RTS/CTS) flow Control\n self.ser.dsrdtr = False # Disable (DSR/DTR) flow Control\n self.ser.writeTimeout = 2\n\n def close(self):\n self.ser.close()\n\n", "You do not actually have to use any special module to read from TTY.\nOption O_NOCTTY solved my problems with CDCACM example MCU app.\nI'm sure it will work for you (as you work on Linux too).\n#!/usr/bin/env python3\n\nimport io, os\n\ntty = io.TextIOWrapper(\n io.FileIO(\n os.open(\n \"/dev/ttyACM1\",\n os.O_NOCTTY | os.O_RDWR),\n \"r+\"))\n\nfor line in iter(tty.readline, None):\n print(line.strip())\n\n", "Stumbled on this while looking into pty/tty usage in python.\nI think the original code did not work because echo will add a newline and the python os.write will not.\nThis is shown in your self answer here self.ser.write(cmd_str + \"\\n\")\nSo the original code may have worked if it were os.write(tty, \"++ver\\n\")\n" ]
[ 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] = None phase_type: Optional[str] = None software_product_version_name: Optional[str] = None product_name: Optional[str] = None software_product_version_id: Optional[int] = None product_id: int and my function like this: @app.get( "/products/", summary="Query all evergreen products", response_description="Successful Query", tags=[Tags.items] ) def get_product_evergreen(product_id: Optional[int] = None,days_ago: Optional[int] = None ,session: Session = Depends(get_session)) -> list: query = select(Evergreen,Mapping.product_alias).where(Evergreen.product_id == Mapping.eim_product_id) if product_id: query = query.where(Mapping.eim_product_id == product_id) if days_ago: margin = date.today() - timedelta(days_ago) query = query.where(date.today() >= Evergreen.phase_end - margin) return session.exec(query).fetchall() Evergreen.phase_end has DATE type in oracle which is my database on the backend. I get the following error: sqlalchemy.exc.DatabaseError: (cx_Oracle.DatabaseError) ORA-00932: inconsistent datatypes: expected NUMBER got DATE [SQL: SELECT evergreen.id_seq, evergreen.phase_end, evergreen.phase_start, evergreen.phase_type, evergreen.software_product_version_name, evergreen.product_name, evergreen.software_product_version_id, evergreen.product_id, mapping.product_alias FROM evergreen, mapping WHERE evergreen.product_id = mapping.eim_product_id AND evergreen.phase_end - :phase_end_1 <= :param_1] [parameters: {'phase_end_1': datetime.date(2022, 10, 26), 'param_1': datetime.date(2022, 11, 25)}] (Background on this error at: https://sqlalche.me/e/14/4xp6) I don't understand why the database is expecting a number. A: It seems like your query typing is wrong. Try this, if days_ago: margin = date.today() - timedelta(days_ago) query = query.where(Evergreen.phase_end =< date.today() + margin)
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 software_product_version_name: Optional[str] = None product_name: Optional[str] = None software_product_version_id: Optional[int] = None product_id: int and my function like this: @app.get( "/products/", summary="Query all evergreen products", response_description="Successful Query", tags=[Tags.items] ) def get_product_evergreen(product_id: Optional[int] = None,days_ago: Optional[int] = None ,session: Session = Depends(get_session)) -> list: query = select(Evergreen,Mapping.product_alias).where(Evergreen.product_id == Mapping.eim_product_id) if product_id: query = query.where(Mapping.eim_product_id == product_id) if days_ago: margin = date.today() - timedelta(days_ago) query = query.where(date.today() >= Evergreen.phase_end - margin) return session.exec(query).fetchall() Evergreen.phase_end has DATE type in oracle which is my database on the backend. I get the following error: sqlalchemy.exc.DatabaseError: (cx_Oracle.DatabaseError) ORA-00932: inconsistent datatypes: expected NUMBER got DATE [SQL: SELECT evergreen.id_seq, evergreen.phase_end, evergreen.phase_start, evergreen.phase_type, evergreen.software_product_version_name, evergreen.product_name, evergreen.software_product_version_id, evergreen.product_id, mapping.product_alias FROM evergreen, mapping WHERE evergreen.product_id = mapping.eim_product_id AND evergreen.phase_end - :phase_end_1 <= :param_1] [parameters: {'phase_end_1': datetime.date(2022, 10, 26), 'param_1': datetime.date(2022, 11, 25)}] (Background on this error at: https://sqlalche.me/e/14/4xp6) I don't understand why the database is expecting a number.
[ "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_3 = ['boolean', 'uint8', 'uint8', 'void', 'boolean', 'void', 'void'] So my desired output would look like this: print(result[0], result[1]) # Output inline static boolean, static uint8 I tried using: Joining two lists list_type_12 = [i + j for i in list_type_1 for j in list_type_2] print(list_type_12) list_type_123 = [i + j for i in list_type_12 for j in list_type_3] print(list_type_123) But the output is a total mess, it creates every possible combination of those words. I know that it should be simple task to do, but I just can't do it properly. Please help me with solving this problem. A: If you are sure that all lists have the same number of elements, something simple as this will work : output = [] for i in range(len(list_1)): output.append(f'{list_1[index]} {list_2[index]} {list_3[index]}') If you do not know what the f before the string means, it will replace everything in curly brackets with the value of the expression. You could also do something like this, which will scale better if you have more than 3 lists : output = [] for elements in zip(list_1, list_2, list_3): # add more lists if necessary output.append(' '.join(elements)) This can of course be reduced to a one-liner (the first code can as well) : output = [' '.join(elements) for elements in zip(list_1, list_2, list_3)]
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'] So my desired output would look like this: print(result[0], result[1]) # Output inline static boolean, static uint8 I tried using: Joining two lists list_type_12 = [i + j for i in list_type_1 for j in list_type_2] print(list_type_12) list_type_123 = [i + j for i in list_type_12 for j in list_type_3] print(list_type_123) But the output is a total mess, it creates every possible combination of those words. I know that it should be simple task to do, but I just can't do it properly. Please help me with solving this problem.
[ "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 brackets with the value of the expression.\nYou could also do something like this, which will scale better if you have more than 3 lists :\noutput = []\nfor elements in zip(list_1, list_2, list_3): # add more lists if necessary\n output.append(' '.join(elements))\n\nThis can of course be reduced to a one-liner (the first code can as well) :\noutput = [' '.join(elements) for elements in zip(list_1, list_2, list_3)]\n\n" ]
[ 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 the end? **The file is significantly larger <?xml version="1.0" encoding="UTF-8"?> <stu:StudentBreakdown> <stu:Studentdata> <stu:StudentScreening> <st:name>Sam Davies</st:name> <st:age>15</st:age> <st:hair>Black</st:hair> <st:eyes>Blue</st:eyes> <st:grade>10</st:grade> <st:teacher>Draco Malfoy</st:teacher> <st:dorm>Innovation Hall</st:dorm> <st:name>Master Splinter</st:name> </stu:StudentScreening> <stu:StudentScreening> <st:name>Cassie Stone</st:name> <st:age>14</st:age> <st:hair>Science</st:hair> <st:grade>9</st:grade> <st:teacher>Luna Lovegood</st:teacher> <st:name>Kelly Clarkson</st:name> </stu:StudentScreening> <stu:StudentScreening> <st:name>Derek Brandon</st:name> <st:age>17</st:age> <st:eyes>green</st:eyes> <st:teacher>Ron Weasley</st:teacher> <st:dorm>Hogtie Manor</st:dorm> <st:name>Miley Cyrus</st:name> </stu:StudentScreening> </stu:Studentdata> </stu:StudentBreakdown> Each tag should be unique for each Student Screening and I want to make them unique by adding a number on the end, see below for desired ouput: <?xml version="1.0" encoding="UTF-8"?> <stu:StudentBreakdown> <stu:Studentdata> <stu:StudentScreening> <st:name0>Sam Davies</st:name0> <st:age>15</st:age> <st:hair>Black</st:hair> <st:eyes>Blue</st:eyes> <st:grade>10</st:grade> <st:teacher>Draco Malfoy</st:teacher> <st:dorm>Innovation Hall</st:dorm> <st:name1>Master Splinter</st:name1> <st:name2>Peter Griffin</st:name2> <st:name3>Louis Griffin</st:name3> </stu:StudentScreening> <stu:StudentScreening> <st:name0>Cassie Stone</st:name0> <st:age>14</st:age> <st:hair>Science</st:hair> <st:grade>9</st:grade> <st:teacher>Luna Lovegood</st:teacher> <st:name1>Kelly Clarkson</st:name1> <st:name2>Stewie Griffin</st:name2> </stu:StudentScreening> <stu:StudentScreening> <st:name0>Derek Brandon</st:name0> <st:age>17</st:age> <st:eyes>green</st:eyes> <st:teacher>Ron Weasley</st:teacher> <st:dorm>Hogtie Manor</st:dorm> <st:name1>Miley Cyrus</st:name1> </stu:StudentScreening> </stu:Studentdata> </stu:StudentBreakdown> A: 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. (I pasted your first xml snippet to xmlStr.) xSoup = BeautifulSoup(xmlStr, 'lxml') ## do NOT use 'xml' parser here unless you want to lose namespaces enumTags = ['st:name', 'stu:studentscreening'] for d in [c for c in xSoup.descendants if c.name]: for name in enumTags: for i, t in enumerate(d.find_all(name, recursive=False)): t.name = f'{t.name}{i}' (You didn't number studentscreening in your question, but I wanted to give an example with multiple tags to number; and, setting recursive=False reduces redundancies as it restricts find to direct children only.) Now, print(xSoup) will give the output <?xml version="1.0" encoding="UTF-8"?><html><body><stu:studentbreakdown> <stu:studentdata> <stu:studentscreening0> <st:name0>Sam Davies</st:name0> <st:age>15</st:age> <st:hair>Black</st:hair> <st:eyes>Blue</st:eyes> <st:grade>10</st:grade> <st:teacher>Draco Malfoy</st:teacher> <st:dorm>Innovation Hall</st:dorm> <st:name1>Master Splinter</st:name1> </stu:studentscreening0> <stu:studentscreening1> <st:name0>Cassie Stone</st:name0> <st:age>14</st:age> <st:hair>Science</st:hair> <st:grade>9</st:grade> <st:teacher>Luna Lovegood</st:teacher> <st:name1>Kelly Clarkson</st:name1> </stu:studentscreening1> <stu:studentscreening2> <st:name0>Derek Brandon</st:name0> <st:age>17</st:age> <st:eyes>green</st:eyes> <st:teacher>Ron Weasley</st:teacher> <st:dorm>Hogtie Manor</st:dorm> <st:name1>Miley Cyrus</st:name1> </stu:studentscreening2> </stu:studentdata> </stu:studentbreakdown> </body></html> (You can also save it [to 'x.xml' for example] with with open('x.xml', 'wb') as f: f.write(xSoup.prettify('utf-8'))) A: Well, I guess Harry Potter has got his magic. The key idea is to use XSLT. Python code using lxml lib, import lxml.etree as ET XSL = ''' <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:stu="https://www.example.com/harrypotter" xmlns:st="https://www.example.com/harrypotter"> <xsl:template match="@*|node()"> <xsl:copy> <xsl:apply-templates select="@*|node()" /> </xsl:copy> </xsl:template> <xsl:template match="stu:StudentScreening/st:name"> <xsl:element name="st:name{count(preceding-sibling::st:name)}"><xsl:apply-templates select="@*|node()" /></xsl:element> </xsl:template> </xsl:stylesheet> ''' dom = ET.parse('students.xml') transform = ET.XSLT(ET.fromstring(XSL)) newdom = transform(dom) print(ET.tostring(newdom)) newdom.write("out.xml", pretty_print=True) Your input xml file named students.xml, which must include namespaces, <?xml version="1.0" encoding="UTF-8"?> <stu:StudentBreakdown xmlns:stu="https://www.example.com/harrypotter" xmlns:st="https://www.example.com/harrypotter"> <stu:Studentdata> <stu:StudentScreening> <st:name>Sam Davies</st:name> <st:age>15</st:age> <st:hair>Black</st:hair> <st:eyes>Blue</st:eyes> <st:grade>10</st:grade> <st:teacher>Draco Malfoy</st:teacher> <st:dorm>Innovation Hall</st:dorm> <st:name>Master Splinter</st:name> <st:name>Peter Griffin</st:name> <st:name>Louis Griffin</st:name> </stu:StudentScreening> <stu:StudentScreening> <st:name>Cassie Stone</st:name> <st:age>14</st:age> <st:hair>Science</st:hair> <st:grade>9</st:grade> <st:teacher>Luna Lovegood</st:teacher> <st:name>Kelly Clarkson</st:name> <st:name>Stewie Griffin</st:name> </stu:StudentScreening> <stu:StudentScreening> <st:name>Derek Brandon</st:name> <st:age>17</st:age> <st:eyes>green</st:eyes> <st:teacher>Ron Weasley</st:teacher> <st:dorm>Hogtie Manor</st:dorm> <st:name>Miley Cyrus</st:name> </stu:StudentScreening> </stu:Studentdata> </stu:StudentBreakdown> Run the Python code, and you should get a file named out.xml.
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> <stu:StudentScreening> <st:name>Sam Davies</st:name> <st:age>15</st:age> <st:hair>Black</st:hair> <st:eyes>Blue</st:eyes> <st:grade>10</st:grade> <st:teacher>Draco Malfoy</st:teacher> <st:dorm>Innovation Hall</st:dorm> <st:name>Master Splinter</st:name> </stu:StudentScreening> <stu:StudentScreening> <st:name>Cassie Stone</st:name> <st:age>14</st:age> <st:hair>Science</st:hair> <st:grade>9</st:grade> <st:teacher>Luna Lovegood</st:teacher> <st:name>Kelly Clarkson</st:name> </stu:StudentScreening> <stu:StudentScreening> <st:name>Derek Brandon</st:name> <st:age>17</st:age> <st:eyes>green</st:eyes> <st:teacher>Ron Weasley</st:teacher> <st:dorm>Hogtie Manor</st:dorm> <st:name>Miley Cyrus</st:name> </stu:StudentScreening> </stu:Studentdata> </stu:StudentBreakdown> Each tag should be unique for each Student Screening and I want to make them unique by adding a number on the end, see below for desired ouput: <?xml version="1.0" encoding="UTF-8"?> <stu:StudentBreakdown> <stu:Studentdata> <stu:StudentScreening> <st:name0>Sam Davies</st:name0> <st:age>15</st:age> <st:hair>Black</st:hair> <st:eyes>Blue</st:eyes> <st:grade>10</st:grade> <st:teacher>Draco Malfoy</st:teacher> <st:dorm>Innovation Hall</st:dorm> <st:name1>Master Splinter</st:name1> <st:name2>Peter Griffin</st:name2> <st:name3>Louis Griffin</st:name3> </stu:StudentScreening> <stu:StudentScreening> <st:name0>Cassie Stone</st:name0> <st:age>14</st:age> <st:hair>Science</st:hair> <st:grade>9</st:grade> <st:teacher>Luna Lovegood</st:teacher> <st:name1>Kelly Clarkson</st:name1> <st:name2>Stewie Griffin</st:name2> </stu:StudentScreening> <stu:StudentScreening> <st:name0>Derek Brandon</st:name0> <st:age>17</st:age> <st:eyes>green</st:eyes> <st:teacher>Ron Weasley</st:teacher> <st:dorm>Hogtie Manor</st:dorm> <st:name1>Miley Cyrus</st:name1> </stu:StudentScreening> </stu:Studentdata> </stu:StudentBreakdown>
[ "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:studentscreening']\nfor d in [c for c in xSoup.descendants if c.name]:\n for name in enumTags:\n for i, t in enumerate(d.find_all(name, recursive=False)):\n t.name = f'{t.name}{i}'\n\n(You didn't number studentscreening in your question, but I wanted to give an example with multiple tags to number; and, setting recursive=False reduces redundancies as it restricts find to direct children only.)\nNow, print(xSoup) will give the output\n<?xml version=\"1.0\" encoding=\"UTF-8\"?><html><body><stu:studentbreakdown>\n<stu:studentdata>\n<stu:studentscreening0>\n<st:name0>Sam Davies</st:name0>\n<st:age>15</st:age>\n<st:hair>Black</st:hair>\n<st:eyes>Blue</st:eyes>\n<st:grade>10</st:grade>\n<st:teacher>Draco Malfoy</st:teacher>\n<st:dorm>Innovation Hall</st:dorm>\n<st:name1>Master Splinter</st:name1>\n</stu:studentscreening0>\n<stu:studentscreening1>\n<st:name0>Cassie Stone</st:name0>\n<st:age>14</st:age>\n<st:hair>Science</st:hair>\n<st:grade>9</st:grade>\n<st:teacher>Luna Lovegood</st:teacher>\n<st:name1>Kelly Clarkson</st:name1>\n</stu:studentscreening1>\n<stu:studentscreening2>\n<st:name0>Derek Brandon</st:name0>\n<st:age>17</st:age>\n<st:eyes>green</st:eyes>\n<st:teacher>Ron Weasley</st:teacher>\n<st:dorm>Hogtie Manor</st:dorm>\n<st:name1>Miley Cyrus</st:name1>\n</stu:studentscreening2>\n</stu:studentdata>\n</stu:studentbreakdown>\n</body></html>\n\n(You can also save it [to 'x.xml' for example] with with open('x.xml', 'wb') as f: f.write(xSoup.prettify('utf-8')))\n", "Well, I guess Harry Potter has got his magic.\nThe key idea is to use XSLT.\nPython code using lxml lib,\nimport lxml.etree as ET\n\nXSL = '''\n<xsl:stylesheet version=\"1.0\" xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\" xmlns:stu=\"https://www.example.com/harrypotter\" xmlns:st=\"https://www.example.com/harrypotter\">\n <xsl:template match=\"@*|node()\">\n <xsl:copy>\n <xsl:apply-templates select=\"@*|node()\" />\n </xsl:copy>\n </xsl:template>\n <xsl:template match=\"stu:StudentScreening/st:name\">\n <xsl:element name=\"st:name{count(preceding-sibling::st:name)}\"><xsl:apply-templates select=\"@*|node()\" /></xsl:element>\n </xsl:template>\n</xsl:stylesheet>\n'''\n\ndom = ET.parse('students.xml')\ntransform = ET.XSLT(ET.fromstring(XSL))\nnewdom = transform(dom)\nprint(ET.tostring(newdom))\n\nnewdom.write(\"out.xml\", pretty_print=True)\n\nYour input xml file named students.xml, which must include namespaces,\n<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<stu:StudentBreakdown xmlns:stu=\"https://www.example.com/harrypotter\" xmlns:st=\"https://www.example.com/harrypotter\">\n<stu:Studentdata>\n <stu:StudentScreening>\n <st:name>Sam Davies</st:name>\n <st:age>15</st:age>\n <st:hair>Black</st:hair>\n <st:eyes>Blue</st:eyes>\n <st:grade>10</st:grade>\n <st:teacher>Draco Malfoy</st:teacher>\n <st:dorm>Innovation Hall</st:dorm>\n <st:name>Master Splinter</st:name>\n <st:name>Peter Griffin</st:name>\n <st:name>Louis Griffin</st:name>\n </stu:StudentScreening>\n <stu:StudentScreening>\n <st:name>Cassie Stone</st:name>\n <st:age>14</st:age>\n <st:hair>Science</st:hair>\n <st:grade>9</st:grade>\n <st:teacher>Luna Lovegood</st:teacher>\n <st:name>Kelly Clarkson</st:name>\n <st:name>Stewie Griffin</st:name>\n </stu:StudentScreening>\n <stu:StudentScreening>\n <st:name>Derek Brandon</st:name>\n <st:age>17</st:age>\n <st:eyes>green</st:eyes>\n <st:teacher>Ron Weasley</st:teacher>\n <st:dorm>Hogtie Manor</st:dorm>\n <st:name>Miley Cyrus</st:name>\n </stu:StudentScreening>\n</stu:Studentdata>\n</stu:StudentBreakdown>\n\nRun the Python code, and you should get a file named out.xml.\n" ]
[ 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...!") print("line 01") print("line 02") print("line 03") print("Before capture") def main(): sys.stdout= open("test.txt", 'w') print_test() sys.stdout.close() main() print("After capture") with open('test.txt', 'r') as f: lines= f.readlines() for i in lines: print(i) if "line 01" in lines: print("Found line 01") A: I did not know this, but after doing sys.stdout.close() it seems you cannot open other files. However 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 : def print_test(f): print("Printing testing print...!", file=f) print("line 01", file=f) print("line 02", file=f) print("line 03", file=f) print("Before capture") def main(): f = open("test.txt", 'w') print_test(f) f.close() main() A: The error is caused by this line: sys.stdout.close() Effectively you are closing the stdout stream for all following print calls in your program, if you omit to pass a file object to the file parameter. See definition of print's file keyword argument: The file argument must be an object with a write(string) method; if it is not present or None, sys.stdout will be used. After main is finished all following print calls try accessing the re-assigned sys.stdout which now is closed. Thus giving you a ValueError. Create a local copy of sys.stdout that you can re-assign after your call to print_test to circumvent this: def main(): stdout = sys.stdout # create local copy of stdout sys.stdout = open("test.txt", 'w') # change stdout print_test() sys.stdout.close() sys.stdout = stdout # reassign standard output stream to sys.stdout The other way would be to pass the file object directly to print using the file keyword myoutput = open("test.txt", "w") print("Print to file", file=myoutput) # pass file object to function def my_print(file): print("function call to print", file=file)
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 capture") def main(): sys.stdout= open("test.txt", 'w') print_test() sys.stdout.close() main() print("After capture") with open('test.txt', 'r') as f: lines= f.readlines() for i in lines: print(i) if "line 01" in lines: print("Found line 01")
[ "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)\n print(\"line 01\", file=f)\n print(\"line 02\", file=f)\n print(\"line 03\", file=f)\n\n\nprint(\"Before capture\")\n\ndef main():\n f = open(\"test.txt\", 'w')\n print_test(f)\n f.close()\nmain()\n\n", "The error is caused by this line:\nsys.stdout.close()\n\nEffectively you are closing the stdout stream for all following print calls in your program, if you omit to pass a file object to the file parameter.\nSee definition of print's file keyword argument:\n\nThe file argument must be an object with a write(string) method; if it is not present or None, sys.stdout will be used.\n\nAfter main is finished all following print calls try accessing the re-assigned sys.stdout which now is closed. Thus giving you a ValueError.\nCreate a local copy of sys.stdout that you can re-assign after your call to print_test to circumvent this:\ndef main():\n stdout = sys.stdout # create local copy of stdout\n sys.stdout = open(\"test.txt\", 'w') # change stdout\n print_test()\n sys.stdout.close()\n sys.stdout = stdout # reassign standard output stream to sys.stdout\n\nThe other way would be to pass the file object directly to print using the file keyword\nmyoutput = open(\"test.txt\", \"w\")\nprint(\"Print to file\", file=myoutput)\n\n# pass file object to function\ndef my_print(file):\n print(\"function call to print\", file=file)\n\n" ]
[ 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 pivot_tables/dataframes of each but Im somehow don't get them to merge into one. So I've tried this approach so far: import numpy as np import pandas as pd array_CinA = np.array([0,125,250,500,1000]) array_Aceto = np.array([0,100,200,400,800]) vol_cina = [0, 5, 10, 20, 40] vol_as = [0, 2, 4,8,16] array = np.array(np.meshgrid(array_CinA,array_Aceto)).T.reshape(-1,2) df = pd.DataFrame({"CinnamonicAcid":array_CinA, "Acetosyringone":array_Aceto, "VolCinA": vol_cina, "VolAS": vol_as}) pivtab = df.pivot_table(index="CinnamonicAcid", columns="Acetosyringone", values=["VolCinA", "VolAS"]) #pivtab.to_excel print(pivtab) Which gives me the following output: VolAS VolCinA Acetosyringone 0 100 200 400 800 0 100 200 400 800 CinnamonicAcid 0 0.0 NaN NaN NaN NaN 0.0 NaN NaN NaN NaN 125 NaN 2.0 NaN NaN NaN NaN 5.0 NaN NaN NaN 250 NaN NaN 4.0 NaN NaN NaN NaN 10.0 NaN NaN 500 NaN NaN NaN 8.0 NaN NaN NaN NaN 20.0 NaN 1000 NaN NaN NaN NaN 16.0 NaN NaN NaN NaN 40.0 My desired output would be something like this: A: Use numpy.broadcast_to for new 2d arrays and divide them, then pass to DataFrame constructor: array_CinA = np.array([0,125,250,500,1000]) array_Aceto = np.array([0,100,200,400,800]) vol_cina = [0, 5, 10, 20, 40] vol_as = [0, 2, 4,8,16] shape = (len(array_Aceto), len(array_CinA)) arr = np.core.defchararray.add(np.array(vol_cina).astype(str), '/')[:, None] a1 = np.broadcast_to(arr, shape) a2 = np.broadcast_to(np.array(vol_as).astype(str), shape) df = (pd.DataFrame(np.core.defchararray.add(a1, a2), index=array_CinA, columns=array_Aceto)) print (df) 0 100 200 400 800 0 0/0 0/2 0/4 0/8 0/16 125 5/0 5/2 5/4 5/8 5/16 250 10/0 10/2 10/4 10/8 10/16 500 20/0 20/2 20/4 20/8 20/16 1000 40/0 40/2 40/4 40/8 40/16 A: The below code should be what you are after. I am using product function from intertools library to create the full data. Then I am just converting to string type so that numpy doesn't get confused and I reshape it. Finally I am producing a dataframe providing index names and column names. import numpy as np import pandas as pd from itertools import product array_CinA = np.array([0, 125, 250, 500, 1000]) array_Aceto = np.array([0, 100, 200, 400, 800]) vol_cina = [0, 5, 10, 20, 40] vol_as = [0, 2, 4, 8, 16] # creating full data my_product = list(product(vol_cina, vol_as)) # converting to str my_product_str = [str(a) for a in my_product] # converting to np array my_product_str_np = np.array(my_product_str) # reshaping my_product_str_np = my_product_str_np.reshape(len(vol_cina), len(vol_as)) # producing final data df = pd.DataFrame(my_product_str_np, index=array_CinA, columns=array_Aceto) df.index.name="CinnamonicAcid" df.columns.name="Acetosyringone" print(df)
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 them to merge into one. So I've tried this approach so far: import numpy as np import pandas as pd array_CinA = np.array([0,125,250,500,1000]) array_Aceto = np.array([0,100,200,400,800]) vol_cina = [0, 5, 10, 20, 40] vol_as = [0, 2, 4,8,16] array = np.array(np.meshgrid(array_CinA,array_Aceto)).T.reshape(-1,2) df = pd.DataFrame({"CinnamonicAcid":array_CinA, "Acetosyringone":array_Aceto, "VolCinA": vol_cina, "VolAS": vol_as}) pivtab = df.pivot_table(index="CinnamonicAcid", columns="Acetosyringone", values=["VolCinA", "VolAS"]) #pivtab.to_excel print(pivtab) Which gives me the following output: VolAS VolCinA Acetosyringone 0 100 200 400 800 0 100 200 400 800 CinnamonicAcid 0 0.0 NaN NaN NaN NaN 0.0 NaN NaN NaN NaN 125 NaN 2.0 NaN NaN NaN NaN 5.0 NaN NaN NaN 250 NaN NaN 4.0 NaN NaN NaN NaN 10.0 NaN NaN 500 NaN NaN NaN 8.0 NaN NaN NaN NaN 20.0 NaN 1000 NaN NaN NaN NaN 16.0 NaN NaN NaN NaN 40.0 My desired output would be something like this:
[ "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.defchararray.add(np.array(vol_cina).astype(str), '/')[:, None]\n\na1 = np.broadcast_to(arr, shape)\na2 = np.broadcast_to(np.array(vol_as).astype(str), shape)\n\ndf = (pd.DataFrame(np.core.defchararray.add(a1, a2), index=array_CinA, columns=array_Aceto))\nprint (df)\n 0 100 200 400 800\n0 0/0 0/2 0/4 0/8 0/16\n125 5/0 5/2 5/4 5/8 5/16\n250 10/0 10/2 10/4 10/8 10/16\n500 20/0 20/2 20/4 20/8 20/16\n1000 40/0 40/2 40/4 40/8 40/16\n\n", "The below code should be what you are after.\nI am using product function from intertools library to create the full data. Then I am just converting to string type so that numpy doesn't get confused and I reshape it. Finally I am producing a dataframe providing index names and column names.\nimport numpy as np\nimport pandas as pd\nfrom itertools import product\n\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\n\n# creating full data\nmy_product = list(product(vol_cina, vol_as))\n# converting to str\nmy_product_str = [str(a) for a in my_product]\n# converting to np array\nmy_product_str_np = np.array(my_product_str)\n# reshaping\nmy_product_str_np = my_product_str_np.reshape(len(vol_cina), len(vol_as))\n# producing final data\ndf = pd.DataFrame(my_product_str_np, index=array_CinA, columns=array_Aceto)\ndf.index.name=\"CinnamonicAcid\"\ndf.columns.name=\"Acetosyringone\"\nprint(df)\n\n" ]
[ 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. James loves his food. You not so much right ? Doc3. Yeah he is alright. I also have a list of 100 words as follows - list = [food, you, ....] Now, I need to extract the top N rows with most frequent occurences of each word from the list in the "Content" column. For the given sample of data, "food" occurs twice in Doc2 and once in Doc1. "you" occurs twice in Doc 1 and once in Doc 2. Hence, desired output is : [food:[doc2, doc1], you:[doc1, doc2], .....] where N = 2 ( top 2 rows having the most frequent occurence of each word ) I have tried something as follows but unsure how to move further - list = [food, you, ....] result = [] for word in list: result.append(df.Content.apply(lambda row: sum([row.count(word)]))) How can I implement an efficient solution to the above requirement in Python ? A: Second attempt (initially I misunderstood your requirements): With df your dataframe you could try something like: words = ["food", "you"] n = 2 # Number of top docs res = ( df .assign(Content=df["Content"].str.casefold().str.findall(r"\w+")) .explode("Content") .loc[lambda df: df["Content"].isin(set(words))] .groupby("DocName").value_counts().rename("Counts") .sort_values(ascending=False).reset_index(level=0) .assign(DocName=lambda df: df["DocName"] + "_" + df["Counts"].astype("str")) .groupby(level=0).agg({"DocName": list}) .assign(DocName=lambda df: df["DocName"].str[:n]) .to_dict()["DocName"] ) The first 3 lines in the pipeline extract the relevant words, one per row. For the sample that looks like: DocName Content 0 Doc1 you 0 Doc1 you 0 Doc1 food 1 Doc2 food 1 Doc2 food 1 Doc2 you The next 2 lines count the words per doc (.groupby and .value_counts), and sort the result by the counts in descending order (.sort_values), and add the count to the doc-strings. For the sample: DocName Counts Content you Doc1_2 2 food Doc2_2 2 food Doc1_1 1 you Doc2_1 1 Then .groupby the words (index) and put the respective docs in a list via .agg, and restrict the list to the n first items (.str[:n]). For the sample: DocName Content food [Doc2_2, Doc1_1] you [Doc1_2, Doc2_1] Finally dumping the result in a dictionary. Result for the sample dataframe DocName Content 0 Doc1 Hi how you are doing ? Hope you are well. I hear the food is great! 1 Doc2 The food is great. James loves his food. You not so much right ? 2 Doc3 Yeah he is alright. is {'food': ['Doc2_2', 'Doc1_1'], 'you': ['Doc1_2', 'Doc2_1']} A: It seems like this problem can be broken down into two sub-problems: Get the frequency of words per "Content" cell For each word in the list, extract the top N rows Luckily, the first sub-problem has many neat approaches, as shown here. TLDR use the Collections library to do a frequency count; or, if you aren't allowed to import libraries, call ".split()" and count in a loop. But again, there are many potential solutions The second sub-problem is a bit trickier. From our first solution, what we have now is a dictionary of frequency counts, per row. To get to our desired answer, the naive method would be to "query" every dictionary for the word in question. E.g run doc1.dict["food"] doc2.dict["food"] ... and compare the results in order. There should be enough to get going, and also opportunity to find more streamlined/elegant solutions. Best of luck!
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 100 words as follows - list = [food, you, ....] Now, I need to extract the top N rows with most frequent occurences of each word from the list in the "Content" column. For the given sample of data, "food" occurs twice in Doc2 and once in Doc1. "you" occurs twice in Doc 1 and once in Doc 2. Hence, desired output is : [food:[doc2, doc1], you:[doc1, doc2], .....] where N = 2 ( top 2 rows having the most frequent occurence of each word ) I have tried something as follows but unsure how to move further - list = [food, you, ....] result = [] for word in list: result.append(df.Content.apply(lambda row: sum([row.count(word)]))) How can I implement an efficient solution to the above requirement in Python ?
[ "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: df[\"Content\"].isin(set(words))]\n .groupby(\"DocName\").value_counts().rename(\"Counts\")\n .sort_values(ascending=False).reset_index(level=0)\n .assign(DocName=lambda df: df[\"DocName\"] + \"_\" + df[\"Counts\"].astype(\"str\"))\n .groupby(level=0).agg({\"DocName\": list})\n .assign(DocName=lambda df: df[\"DocName\"].str[:n])\n .to_dict()[\"DocName\"]\n)\n\n\nThe first 3 lines in the pipeline extract the relevant words, one per row. For the sample that looks like:\n DocName Content\n0 Doc1 you\n0 Doc1 you\n0 Doc1 food\n1 Doc2 food\n1 Doc2 food\n1 Doc2 you\n\n\nThe next 2 lines count the words per doc (.groupby and .value_counts), and sort the result by the counts in descending order (.sort_values), and add the count to the doc-strings. For the sample:\n DocName Counts\nContent \nyou Doc1_2 2\nfood Doc2_2 2\nfood Doc1_1 1\nyou Doc2_1 1\n\n\nThen .groupby the words (index) and put the respective docs in a list via .agg, and restrict the list to the n first items (.str[:n]). For the sample:\n DocName\nContent \nfood [Doc2_2, Doc1_1]\nyou [Doc1_2, Doc2_1]\n\n\nFinally dumping the result in a dictionary.\n\n\nResult for the sample dataframe\n DocName Content\n0 Doc1 Hi how you are doing ? Hope you are well. I hear the food is great!\n1 Doc2 The food is great. James loves his food. You not so much right ?\n2 Doc3 Yeah he is alright.\n\nis\n{'food': ['Doc2_2', 'Doc1_1'], 'you': ['Doc1_2', 'Doc2_1']}\n\n", "It seems like this problem can be broken down into two sub-problems:\n\nGet the frequency of words per \"Content\" cell\nFor each word in the list, extract the top N rows\n\nLuckily, the first sub-problem has many neat approaches, as shown here. TLDR use the Collections library to do a frequency count; or, if you aren't allowed to import libraries, call \".split()\" and count in a loop. But again, there are many potential solutions\nThe second sub-problem is a bit trickier. From our first solution, what we have now is a dictionary of frequency counts, per row. To get to our desired answer, the naive method would be to \"query\" every dictionary for the word in question.\nE.g run\ndoc1.dict[\"food\"]\ndoc2.dict[\"food\"]\n...\n\nand compare the results in order.\nThere should be enough to get going, and also opportunity to find more streamlined/elegant solutions. Best of luck!\n" ]
[ 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 == 0: print(i) Numbers until 100 that can be divided by 7 are: ---------------------------------------------------------------------------------------------------- 0 7 14 21 28 35 42 49 56 63 70 77 84 91 98 Before submitting though, I checked other replies online and saw users in this post use another approach, perhaps more complex. When I then tried to use their approach, the code failed to give me the correct results: print("Numbers until 100 that can be divided by 7 are: ") print("-" * 100) for i in range(101): if i % 7 == 0 or i % 10 == 7 or i // 10 == 7: print(i) C:\Users\user\PycharmProjects\blocks\ranges.py Numbers until 100 that can be divided by 7 are: ---------------------------------------------------------------------------------------------------- 0 7 14 17 21 27 28 35 37 42 47 49 56 57 63 67 70 71 72 73 74 75 76 77 78 79 84 87 91 97 98 I checked the commenters' ideas and they were quite logical about the construction of their code. I even tried to debug it and see what could be going wrong, and noticed nothing more than if I would have done otherwise. Their code just seems to think, for example, that 72 is divisible by 7. I can't get to that level of code understanding just yet, could anybody point out what's going wrong? I tried to run the code, and got a right result for my code. When I tried other people's code, which I assumed was more logical, it went wrong. A: i // 10 == 7 is the first mistake. // gives you the quotient but there may be a remainder 71 // 10 gives you 7 but it remains 1 !!! (so it's not divisible by 7) And i % 10 == 7 is the second mistake : Because % gives you the remainder. So 37 % 10 gives you 7 (because 37/10 = 3.7).. So it's not divisible by 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 are: ---------------------------------------------------------------------------------------------------- 0 7 14 21 28 35 42 49 56 63 70 77 84 91 98 Before submitting though, I checked other replies online and saw users in this post use another approach, perhaps more complex. When I then tried to use their approach, the code failed to give me the correct results: print("Numbers until 100 that can be divided by 7 are: ") print("-" * 100) for i in range(101): if i % 7 == 0 or i % 10 == 7 or i // 10 == 7: print(i) C:\Users\user\PycharmProjects\blocks\ranges.py Numbers until 100 that can be divided by 7 are: ---------------------------------------------------------------------------------------------------- 0 7 14 17 21 27 28 35 37 42 47 49 56 57 63 67 70 71 72 73 74 75 76 77 78 79 84 87 91 97 98 I checked the commenters' ideas and they were quite logical about the construction of their code. I even tried to debug it and see what could be going wrong, and noticed nothing more than if I would have done otherwise. Their code just seems to think, for example, that 72 is divisible by 7. I can't get to that level of code understanding just yet, could anybody point out what's going wrong? I tried to run the code, and got a right result for my code. When I tried other people's code, which I assumed was more logical, it went wrong.
[ "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\n" ]
[ 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 <NUM>. Q <NUM> <Q.NUM.> <NUM> Question <NUM> <Example> Problem <NUM> Problem: <Alphabet><Number>. <EXAMPLE> Example <NUM> Someone suggested the below regex: try the demo ((Q|Question|Problem:?|Example|EXAMPLE)\.? ?\d+\.? ?|(Question|Problem:?|Example|EXAMPLE) ?) but it captures patterns in the middle which is problematic for me because I can have Q. , Example. 2 in the middle of the string too and is not capturing <NUM>. This list is based on priority so what I could come up with is building these many expressions and running a loop based on the priority for example: QUESTIONS = [ re.compile("\n\d+\."), re.compile("\nQ.\s*\d+\."), re.compile("\nExample.\s*\d+\.") ] but it is very inefficient. How can I club these in one expression? HERE IS THE TEST STRING: 'TEStlabZ\nEDULABZ\nINTERNATIONAL\nLOGARITHMS AND INDICES\n\nQ.1. (A) Convert each of the following to logarithmic form.\n(i) \\( 5^{2}=25 \\)\n(ii) \\( 3^{-3}=\\frac{1}{27} \\)\n(iii) \\( (64)^{\\frac{1}{3}}=4 \\)\n(iv) \\( 6^{0}=1 \\)\n(v) \\( 10^{-2}=0.01 \\) (vi) \\( 4^{-1}=\\frac{1}{4} \\)\nAns. We know that \\( a^{b}=x \\Rightarrow b=\\log _{a} x \\)\n(i) \\( 5^{2}=25 \\quad \\therefore \\log _{5} 25=2 \\)\n(ii) \\( 3^{-3}=\\frac{1}{27} \\therefore \\log _{3}\\left(\\frac{1}{27}\\right)=-3 \\)\n(iii) \\( (64)^{\\frac{1}{3}}=4 \\therefore \\log _{64} 4=\\frac{1}{3} \\)\n(iv) \\( 6^{0}=1 \\quad \\therefore \\log _{6} 1=0 \\)\n(v) \\( 10^{-2}=0.01 \\therefore \\log _{10}(0.01)=-2 \\)\n(vi) \\( 4^{-1}=\\frac{1}{4} \\therefore \\log _{4}\\left(\\frac{1}{4}\\right)=-1 \\)\nQ.1. (B) Convert each of the following to exponential form.\n(i) \\( \\log _{3} 81=4 \\)\n(ii) \\( \\log _{8} 4=\\frac{2}{3} \\)\n(iii) \\( \\log _{2} \\frac{1}{8}=-3 \\)\n(iv) \\( \\log _{10}(0.01)=-2 \\)\n(v) \\( \\log _{5}\\left(\\frac{1}{5}\\right)=-1 \\) (vi) \\( \\log _{a} 1=0 \\)\nAns.\n(i) \\( \\log _{3} 81=4 \\quad \\therefore 3^{4}=81 \\)\n(ii) \\( \\log _{8} 4=\\frac{2}{3} \\quad \\therefore 8^{\\frac{2}{3}}=4 \\)\n(iii) \\( \\log _{2} \\frac{1}{8}=-3 \\quad \\therefore \\quad 2^{-3}=\\frac{1}{8} \\)\n(iv) \\( \\log _{10}(0.01)=-2 \\quad \\therefore \\quad 10^{-2}=0.01 \\)\n(v) \\( \\log _{5}\\left(\\frac{1}{5}\\right)=-1 \\quad \\therefore \\quad 5^{-1}=\\frac{1}{5} \\)\n(vi) \\( \\log _{a} 1=0 \\)\n\\( \\therefore a^{0}=1 \\)\nMath Class IX\n1\nQuestion Bank' A: You can use (?m)^(?!$)(?:((?i:Question|Problem:?|Example)|[A-Z])[. ]?)?(\d+[. ]?)?(?=\s) See the regex demo. Details: (?m)^ - start of a line (m allows ^ to match any line start position) (?!$) - no end of line allowed at the same location (i.e. no empty line match allowed) (?:((?i:Question|Problem:?|Example)|[A-Z])[. ]?)? - an optional sequence of ((?i:Question|Problem:?|Example)|[A-Z]) - Group 1: Question, Problem, Problem: or Example case insensitively, or an uppercase letter [. ]? - a space or . (\d+[. ]?)? - an optional capturing group with ID 2 matching one or more digits and then an optional . or space (?=\s) - a positive lookahead that requires a whitespace char immediately to the right of the current location. A: No shame in just doing the dumb solution: ^(\d+\.|Q \d+\.|Q \d+|Q\.\d+\.|\d+|Question \d+|Example( \d+)?|Problem \d+|Problem:|[A-Z]\d\.|EXAMPLE)\s+
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><Number>. <EXAMPLE> Example <NUM> Someone suggested the below regex: try the demo ((Q|Question|Problem:?|Example|EXAMPLE)\.? ?\d+\.? ?|(Question|Problem:?|Example|EXAMPLE) ?) but it captures patterns in the middle which is problematic for me because I can have Q. , Example. 2 in the middle of the string too and is not capturing <NUM>. This list is based on priority so what I could come up with is building these many expressions and running a loop based on the priority for example: QUESTIONS = [ re.compile("\n\d+\."), re.compile("\nQ.\s*\d+\."), re.compile("\nExample.\s*\d+\.") ] but it is very inefficient. How can I club these in one expression? HERE IS THE TEST STRING: 'TEStlabZ\nEDULABZ\nINTERNATIONAL\nLOGARITHMS AND INDICES\n\nQ.1. (A) Convert each of the following to logarithmic form.\n(i) \\( 5^{2}=25 \\)\n(ii) \\( 3^{-3}=\\frac{1}{27} \\)\n(iii) \\( (64)^{\\frac{1}{3}}=4 \\)\n(iv) \\( 6^{0}=1 \\)\n(v) \\( 10^{-2}=0.01 \\) (vi) \\( 4^{-1}=\\frac{1}{4} \\)\nAns. We know that \\( a^{b}=x \\Rightarrow b=\\log _{a} x \\)\n(i) \\( 5^{2}=25 \\quad \\therefore \\log _{5} 25=2 \\)\n(ii) \\( 3^{-3}=\\frac{1}{27} \\therefore \\log _{3}\\left(\\frac{1}{27}\\right)=-3 \\)\n(iii) \\( (64)^{\\frac{1}{3}}=4 \\therefore \\log _{64} 4=\\frac{1}{3} \\)\n(iv) \\( 6^{0}=1 \\quad \\therefore \\log _{6} 1=0 \\)\n(v) \\( 10^{-2}=0.01 \\therefore \\log _{10}(0.01)=-2 \\)\n(vi) \\( 4^{-1}=\\frac{1}{4} \\therefore \\log _{4}\\left(\\frac{1}{4}\\right)=-1 \\)\nQ.1. (B) Convert each of the following to exponential form.\n(i) \\( \\log _{3} 81=4 \\)\n(ii) \\( \\log _{8} 4=\\frac{2}{3} \\)\n(iii) \\( \\log _{2} \\frac{1}{8}=-3 \\)\n(iv) \\( \\log _{10}(0.01)=-2 \\)\n(v) \\( \\log _{5}\\left(\\frac{1}{5}\\right)=-1 \\) (vi) \\( \\log _{a} 1=0 \\)\nAns.\n(i) \\( \\log _{3} 81=4 \\quad \\therefore 3^{4}=81 \\)\n(ii) \\( \\log _{8} 4=\\frac{2}{3} \\quad \\therefore 8^{\\frac{2}{3}}=4 \\)\n(iii) \\( \\log _{2} \\frac{1}{8}=-3 \\quad \\therefore \\quad 2^{-3}=\\frac{1}{8} \\)\n(iv) \\( \\log _{10}(0.01)=-2 \\quad \\therefore \\quad 10^{-2}=0.01 \\)\n(v) \\( \\log _{5}\\left(\\frac{1}{5}\\right)=-1 \\quad \\therefore \\quad 5^{-1}=\\frac{1}{5} \\)\n(vi) \\( \\log _{a} 1=0 \\)\n\\( \\therefore a^{0}=1 \\)\nMath Class IX\n1\nQuestion Bank'
[ "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:?|Example)|[A-Z])[. ]?)? - an optional sequence of\n\n((?i:Question|Problem:?|Example)|[A-Z]) - Group 1: Question, Problem, Problem: or Example case insensitively, or an uppercase letter\n[. ]? - a space or .\n\n\n(\\d+[. ]?)? - an optional capturing group with ID 2 matching one or more digits and then an optional . or space\n(?=\\s) - a positive lookahead that requires a whitespace char immediately to the right of the current location.\n\n", "No shame in just doing the dumb solution:\n^(\\d+\\.|Q \\d+\\.|Q \\d+|Q\\.\\d+\\.|\\d+|Question \\d+|Example( \\d+)?|Problem \\d+|Problem:|[A-Z]\\d\\.|EXAMPLE)\\s+\n" ]
[ 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 multiprocessing import Pool import timeit as ti def foo(n): return -np.sort(-np.arange(n))[-1] def par(reps, bigNum, pool): for i in range(bigNum, bigNum+reps): pool.apply_async(foo, args=(i,)) def ser(reps, bigNum): for i in range(bigNum, bigNum+reps): foo(i) if __name__ == '__main__': bigNum = 9_000_000 reps = 6 fun = f'par(reps, bigNum, pool)' t = 1000 * np.array(ti.repeat(stmt=fun, setup='pool=Pool(reps);'+fun, globals=globals(), number=1, repeat=10)) print(f'{fun}: {np.amin(t):6.3f}ms {np.median(t):6.3f}ms') fun = f'ser(reps, bigNum)' t = 1000 * np.array(ti.repeat(stmt=fun, setup=fun, globals=globals(), number=1, repeat=10)) print(f'{fun}: {np.amin(t):6.3f}ms {np.median(t):6.3f}ms') Right now, par function only shows the time to spin the worker processes. What do I need to change in function par, in order to make it wait for all worker processes to complete before returning? Note that I would like to reuse the process pool between calls. A: you need to get the result from apply_async to wait for it. def par(reps, bigNum, pool): jobs = [] for i in range(bigNum, bigNum+reps): jobs.append(pool.apply_async(foo, args=(i,))) for job in jobs: job.get() for long loops you should be using map or imap or imap_unordered instead of apply_async as it has less overhead and you get to control the chunksize for faster serialization of small objects, and you can pass generators to them to save memory or allow infinite generators (with imap). def par(reps, bigNum, pool): pool.map(foo, range(bigNum,bigNum+reps), chunksize=1) note: python PEP8 indentation is 4 spaces, not 2.
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] def par(reps, bigNum, pool): for i in range(bigNum, bigNum+reps): pool.apply_async(foo, args=(i,)) def ser(reps, bigNum): for i in range(bigNum, bigNum+reps): foo(i) if __name__ == '__main__': bigNum = 9_000_000 reps = 6 fun = f'par(reps, bigNum, pool)' t = 1000 * np.array(ti.repeat(stmt=fun, setup='pool=Pool(reps);'+fun, globals=globals(), number=1, repeat=10)) print(f'{fun}: {np.amin(t):6.3f}ms {np.median(t):6.3f}ms') fun = f'ser(reps, bigNum)' t = 1000 * np.array(ti.repeat(stmt=fun, setup=fun, globals=globals(), number=1, repeat=10)) print(f'{fun}: {np.amin(t):6.3f}ms {np.median(t):6.3f}ms') Right now, par function only shows the time to spin the worker processes. What do I need to change in function par, in order to make it wait for all worker processes to complete before returning? Note that I would like to reuse the process pool between calls.
[ "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_async as it has less overhead and you get to control the chunksize for faster serialization of small objects, and you can pass generators to them to save memory or allow infinite generators (with imap).\ndef par(reps, bigNum, pool):\n pool.map(foo, range(bigNum,bigNum+reps), chunksize=1)\n\nnote: python PEP8 indentation is 4 spaces, not 2.\n" ]
[ 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 that is: There is no warning in python -c "import numpy as np; print(np.sum([-np.Inf, -np.Inf]))" nor in python -c "import numpy as np; print(np.sum([+np.Inf, +np.Inf]))" so it can't be the Infs. There is no warning in python -c "import numpy as np; print(np.sum([np.nan, np.nan]))" so it can't be the NaN result. What is it, then, and how can I avoid it? I actually like getting NaN as a result, I just want to avoid the warning. A: The warning is fine, because Inf - Inf is mathematically undefined. What result would you expect? If you want to avoid the warning, use a filter as follows: import warnings with warnings.catch_warnings(): warnings.simplefilter("ignore", category=RuntimeWarning) res = np.sum([-np.Inf, np.Inf]) A: It turns out the answer by @CarlosHorn is pretty close, although hidden deep inside the IEEE standard 754 (I checked the 2008 version). Section 7.2 (Default exception handling > Invalid operation) writes The invalid operation exception is signaled if and only if there is no usefully definable result. I wouldn't know what a "usefully definable result" might be, considering that some people may not find Inf useful; I, by contrast, find even NaN pretty useful. Anyay, the section gives a comprehensive list of examples, which includes (in d) the "magnitude subtraction of infinities", explaining why and form of Inf - Inf should be considered invalid. It does also include (in a) "any [...] operation on a signaling NaN", but does not include operations on a quiet NaN. This important distinction explains why NaN + NaN usually does not signal, as np.nan is quiet. For completeness, section 6.1 explains why Inf + Inf should not be considered invalid. Two things left to says: It is unclear (yet irrelevant) to me why np.inf - np.inf does not raise an exception. with np.errstate(invalid="ignore"): ... is probably the cleanest way to suppress the warning. More resources: https://github.com/numpy/numpy/issues/22661#issuecomment-1326168983 https://en.wikipedia.org/wiki/IEEE_754#Exception_handling
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, -np.Inf]))" nor in python -c "import numpy as np; print(np.sum([+np.Inf, +np.Inf]))" so it can't be the Infs. There is no warning in python -c "import numpy as np; print(np.sum([np.nan, np.nan]))" so it can't be the NaN result. What is it, then, and how can I avoid it? I actually like getting NaN as a result, I just want to avoid the warning.
[ "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", "It turns out the answer by @CarlosHorn is pretty close, although hidden deep inside the IEEE standard 754 (I checked the 2008 version).\nSection 7.2 (Default exception handling > Invalid operation) writes\n\nThe invalid operation exception is signaled if and only if there is no usefully definable result.\n\nI wouldn't know what a \"usefully definable result\" might be, considering that some people may not find Inf useful; I, by contrast, find even NaN pretty useful. Anyay, the section gives a comprehensive list of examples, which includes (in d) the \"magnitude subtraction of infinities\", explaining why and form of Inf - Inf should be considered invalid. It does also include (in a) \"any [...] operation on a signaling NaN\", but does not include operations on a quiet NaN. This important distinction explains why NaN + NaN usually does not signal, as np.nan is quiet.\nFor completeness, section 6.1 explains why Inf + Inf should not be considered invalid.\nTwo things left to says:\n\nIt is unclear (yet irrelevant) to me why np.inf - np.inf does not raise an exception.\nwith np.errstate(invalid=\"ignore\"): ... is probably the cleanest way to suppress the warning.\n\nMore resources:\n\nhttps://github.com/numpy/numpy/issues/22661#issuecomment-1326168983\nhttps://en.wikipedia.org/wiki/IEEE_754#Exception_handling\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 both sides, but on the server when I am trying to display the message I am having some problems, until now I could already display the sent message, however, each time I send a message from the client a new GUI on the server is being created by my code, and I do understand why this is happening, but I don't know how to solve it, the server side GUI should display only 1 GUI and the message sent by the client should be updated on this latter GUI, without displaying several GUIs, does somebody know how to solve it? I would appreciate it... I am attaching my code for client and server: CLIENT: from tkinter import * import socket HOST = '127.0.0.1' PORT = 6005 cli = socket.socket(socket.AF_INET, socket.SOCK_STREAM) root = Tk() root.title("client") root.geometry("300x200") e = Entry(root, width=50, bg="white", fg="black") e.pack() cli.connect((HOST, PORT)) def button_click(): x =e.get() message = str(x) cli.send(message.encode('utf-8')) count.config(text=message) OTP = Button(root, text="Send Transfer", padx=20, pady=10, command=button_click) OTP.pack() count = Label(root) count.pack() root.mainloop() SERVER: import socket import threading import tkinter import tkinter.scrolledtext from tkinter import simpledialog host='127.0.0.1' port=6005 server= socket.socket(socket.AF_INET, socket.SOCK_STREAM) server.bind((host, port)) server.listen() balance=0 def handler(client): while True: try: message = client.recv(1024) if not message: break message=message.decode('utf-8') thread = threading.Thread(target=gui, args=(message,)) thread.start() except: break server.close() def gui(message): global balance balance=balance+int(message) print(balance) root = tkinter.Tk() root.title("Server") root.geometry("300x200") myLabel=tkinter.Label(root) myLabel.config(text=f"You current balance is: {balance}") myLabel.pack() root.mainloop() def receive(): while True: try: client, address = server.accept() print(f"connected with {str(address)}") thread = threading.Thread(target=handler, args=(client,)) thread.start() except: break receive() A: You should create the server GUI only once in main thread (not in child thread) and run the socket server in child thread instead. Below is the modified code on server side: import socket import threading import tkinter from tkinter.scrolledtext import ScrolledText # client handler def handler(client): while True: try: message = client.recv(1024) if not message: break message = message.decode('utf-8') update_balance(int(message)) # or float(message)? except Exception as ex: print("Client handler exception:", ex) break client.close() # socket server function def server(): host = '127.0.0.1' port = 6005 server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server.bind((host, port)) server.listen() while True: try: client, address = server.accept() print(f"connected with {address}") thread = threading.Thread(target=handler, args=(client,), daemon=True) thread.start() except Exception as ex: print("Server exception:", ex) break server.close() # function to show the update balance in the text box def update_balance(amount=0): global balance balance += amount # avoid updating tkinter widget in a thread root.after(1, lambda: logbox.insert("end", f"Your current balance is {balance}\n")) balance = 0 root = tkinter.Tk() root.title("Server") #root.geometry("300x200") logbox = ScrolledText(root, width=60, height=20) logbox.pack() update_balance() # show the initial balance # create thread for socket server threading.Thread(target=server, daemon=True).start() root.mainloop()
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 could already display the sent message, however, each time I send a message from the client a new GUI on the server is being created by my code, and I do understand why this is happening, but I don't know how to solve it, the server side GUI should display only 1 GUI and the message sent by the client should be updated on this latter GUI, without displaying several GUIs, does somebody know how to solve it? I would appreciate it... I am attaching my code for client and server: CLIENT: from tkinter import * import socket HOST = '127.0.0.1' PORT = 6005 cli = socket.socket(socket.AF_INET, socket.SOCK_STREAM) root = Tk() root.title("client") root.geometry("300x200") e = Entry(root, width=50, bg="white", fg="black") e.pack() cli.connect((HOST, PORT)) def button_click(): x =e.get() message = str(x) cli.send(message.encode('utf-8')) count.config(text=message) OTP = Button(root, text="Send Transfer", padx=20, pady=10, command=button_click) OTP.pack() count = Label(root) count.pack() root.mainloop() SERVER: import socket import threading import tkinter import tkinter.scrolledtext from tkinter import simpledialog host='127.0.0.1' port=6005 server= socket.socket(socket.AF_INET, socket.SOCK_STREAM) server.bind((host, port)) server.listen() balance=0 def handler(client): while True: try: message = client.recv(1024) if not message: break message=message.decode('utf-8') thread = threading.Thread(target=gui, args=(message,)) thread.start() except: break server.close() def gui(message): global balance balance=balance+int(message) print(balance) root = tkinter.Tk() root.title("Server") root.geometry("300x200") myLabel=tkinter.Label(root) myLabel.config(text=f"You current balance is: {balance}") myLabel.pack() root.mainloop() def receive(): while True: try: client, address = server.accept() print(f"connected with {str(address)}") thread = threading.Thread(target=handler, args=(client,)) thread.start() except: break receive()
[ "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 while True:\n try:\n message = client.recv(1024)\n if not message: break\n message = message.decode('utf-8')\n update_balance(int(message)) # or float(message)?\n except Exception as ex:\n print(\"Client handler exception:\", ex)\n break\n client.close()\n\n# socket server function\ndef server():\n host = '127.0.0.1'\n port = 6005\n server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n server.bind((host, port))\n server.listen()\n\n while True:\n try:\n client, address = server.accept()\n print(f\"connected with {address}\")\n thread = threading.Thread(target=handler, args=(client,), daemon=True)\n thread.start()\n except Exception as ex:\n print(\"Server exception:\", ex)\n break\n\n server.close()\n\n# function to show the update balance in the text box\ndef update_balance(amount=0):\n global balance\n balance += amount\n # avoid updating tkinter widget in a thread\n root.after(1, lambda: logbox.insert(\"end\", f\"Your current balance is {balance}\\n\"))\n\nbalance = 0\n\nroot = tkinter.Tk()\nroot.title(\"Server\")\n#root.geometry(\"300x200\")\n\nlogbox = ScrolledText(root, width=60, height=20)\nlogbox.pack()\nupdate_balance() # show the initial balance\n\n# create thread for socket server\nthreading.Thread(target=server, daemon=True).start()\n\nroot.mainloop() \n\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 instead of one link at a time. This is currently how I'm trying. links = [ 'first link', 'second link', 'third link', ] def get_links(link): while True: res = requests.get(link,headers=headers) soup = BeautifulSoup(res.text,"html.parser") for item in soup.select("[data-testid='serp-ia-card'] [class*='businessName'] a[href^='/biz/'][name]"): shop_name = item.get_text(strip=True) shop_link = item.get('href') yield shop_name,shop_link next_page = soup.select_one("a.next-link[aria-label='Next']") if not next_page: return link = next_page.get("href") def get_content(shop_name,shop_link): res = requests.get(shop_link,headers=headers) soup = BeautifulSoup(res.text,"html.parser") try: phone = soup.select_one("p:-soup-contains('Phone number') + p").get_text(strip=True) except (AttributeError,TypeError): phone = "" return shop_name,shop_link,phone if __name__ == '__main__': with concurrent.futures.ThreadPoolExecutor(max_workers=6) as executor: """ would like to supply the list of links to the "future_to_url" block instead of one link at a time """ for link in links: future_to_url = {executor.submit(get_content, *elem): elem for elem in get_links(link)} for future in concurrent.futures.as_completed(future_to_url): shop_name,shop_link,phone = future.result()[0],future.result()[1],future.result()[2] print(shop_name,shop_link,phone) A: I think what you need is executor.map where you can pass an iterable. I've simplified your code since you're not providing the links, but that should give you the general idea. Here's how: import concurrent.futures from itertools import chain import requests from bs4 import BeautifulSoup links = [ 'https://stackoverflow.com/questions/tagged/beautifulsoup?sort=Newest&filters=NoAnswers&uqlId=30134', 'https://stackoverflow.com/questions/tagged/python-3.x+web-scraping?sort=Newest&filters=NoAnswers&uqlId=27838', ] headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36', } def get_links(source_url: str) -> list: soup = BeautifulSoup(s.get(source_url, headers=headers).text, "html.parser") return [ (a.getText(), f"https://stackoverflow.com{a['href']}") for a in soup.select(".s-post-summary--content .s-post-summary--content-title a") ] def get_content(content_data: tuple) -> str: question, url = content_data user = ( BeautifulSoup(s.get(url, headers=headers).text, "html.parser") .select_one(".user-info .user-details a") ) return f"{question}\n{url}\nAsked by: {user.getText()}" if __name__ == '__main__': with requests.Session() as s: with concurrent.futures.ThreadPoolExecutor(max_workers=6) as executor: results = executor.map( get_content, chain.from_iterable(executor.map(get_links, links)), ) for result in results: print(result) This prints all question titles and who asked it. For the sake of the example I'm visiting the question page to get the user name. Can't use find after find_all while making a loop for parsing https://stackoverflow.com/questions/74570141/cant-use-find-after-find-all-while-making-a-loop-for-parsing Asked by: wasdy The results are different from the VS code when using AWS lambda.(selenium,BeautifulSoup) https://stackoverflow.com/questions/74557551/the-results-are-different-from-the-vs-code-when-using-aws-lambda-selenium-beaut Asked by: user20588340 Beautiful on Python not as expected https://stackoverflow.com/questions/74554271/beautiful-on-python-not-as-expected Asked by: Woody1193 Selenium bypass login https://stackoverflow.com/questions/74551814/selenium-bypass-login Asked by: Python12492 Tags not found with BeautifulSoup parsing https://stackoverflow.com/questions/74551202/tags-not-found-with-beautifulsoup-parsing Asked by: Reem Aljunaid When I parse a large XML sitemap on Beautifulsoup in Python, it only parses part of the file https://stackoverflow.com/questions/74543726/when-i-parse-a-large-xml-sitemap-on-beautifulsoup-in-python-it-only-parses-part Asked by: JS0NBOURNE How can I solve Http Error 308: Permanent Redirect in Data Crawling? https://stackoverflow.com/questions/74541173/how-can-i-solve-http-error-308-permanent-redirect-in-data-crawling Asked by: Illubith and more ...
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 link', 'second link', 'third link', ] def get_links(link): while True: res = requests.get(link,headers=headers) soup = BeautifulSoup(res.text,"html.parser") for item in soup.select("[data-testid='serp-ia-card'] [class*='businessName'] a[href^='/biz/'][name]"): shop_name = item.get_text(strip=True) shop_link = item.get('href') yield shop_name,shop_link next_page = soup.select_one("a.next-link[aria-label='Next']") if not next_page: return link = next_page.get("href") def get_content(shop_name,shop_link): res = requests.get(shop_link,headers=headers) soup = BeautifulSoup(res.text,"html.parser") try: phone = soup.select_one("p:-soup-contains('Phone number') + p").get_text(strip=True) except (AttributeError,TypeError): phone = "" return shop_name,shop_link,phone if __name__ == '__main__': with concurrent.futures.ThreadPoolExecutor(max_workers=6) as executor: """ would like to supply the list of links to the "future_to_url" block instead of one link at a time """ for link in links: future_to_url = {executor.submit(get_content, *elem): elem for elem in get_links(link)} for future in concurrent.futures.as_completed(future_to_url): shop_name,shop_link,phone = future.result()[0],future.result()[1],future.result()[2] print(shop_name,shop_link,phone)
[ "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 'https://stackoverflow.com/questions/tagged/beautifulsoup?sort=Newest&filters=NoAnswers&uqlId=30134',\n 'https://stackoverflow.com/questions/tagged/python-3.x+web-scraping?sort=Newest&filters=NoAnswers&uqlId=27838',\n]\n\nheaders = {\n 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36',\n}\n\n\ndef get_links(source_url: str) -> list:\n soup = BeautifulSoup(s.get(source_url, headers=headers).text, \"html.parser\")\n return [\n (a.getText(), f\"https://stackoverflow.com{a['href']}\") for a\n in soup.select(\".s-post-summary--content .s-post-summary--content-title a\")\n ]\n\n\ndef get_content(content_data: tuple) -> str:\n question, url = content_data\n user = (\n BeautifulSoup(s.get(url, headers=headers).text, \"html.parser\")\n .select_one(\".user-info .user-details a\")\n )\n return f\"{question}\\n{url}\\nAsked by: {user.getText()}\"\n\n\nif __name__ == '__main__':\n with requests.Session() as s:\n with concurrent.futures.ThreadPoolExecutor(max_workers=6) as executor:\n results = executor.map(\n get_content,\n chain.from_iterable(executor.map(get_links, links)),\n )\n for result in results:\n print(result)\n\nThis prints all question titles and who asked it. For the sake of the example I'm visiting the question page to get the user name.\nCan't use find after find_all while making a loop for parsing\nhttps://stackoverflow.com/questions/74570141/cant-use-find-after-find-all-while-making-a-loop-for-parsing\nAsked by: wasdy\nThe results are different from the VS code when using AWS lambda.(selenium,BeautifulSoup)\nhttps://stackoverflow.com/questions/74557551/the-results-are-different-from-the-vs-code-when-using-aws-lambda-selenium-beaut\nAsked by: user20588340\nBeautiful on Python not as expected\nhttps://stackoverflow.com/questions/74554271/beautiful-on-python-not-as-expected\nAsked by: Woody1193\nSelenium bypass login\nhttps://stackoverflow.com/questions/74551814/selenium-bypass-login\nAsked by: Python12492\nTags not found with BeautifulSoup parsing\nhttps://stackoverflow.com/questions/74551202/tags-not-found-with-beautifulsoup-parsing\nAsked by: Reem Aljunaid\nWhen I parse a large XML sitemap on Beautifulsoup in Python, it only parses part of the file\nhttps://stackoverflow.com/questions/74543726/when-i-parse-a-large-xml-sitemap-on-beautifulsoup-in-python-it-only-parses-part\nAsked by: JS0NBOURNE\nHow can I solve Http Error 308: Permanent Redirect in Data Crawling?\nhttps://stackoverflow.com/questions/74541173/how-can-i-solve-http-error-308-permanent-redirect-in-data-crawling\nAsked by: Illubith\n\nand more ...\n\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 attribute to your crontab call. Your code has to be like: crontab(hour="14-9", minute=0)
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? Here is an example of my class: class Foo(BaseModel): a: int b: Optional[str] c: Optional[float] And when I init the class, I need to pass keyword arguments: So, I cannot initialize the class like this: Foo(1,2,2.5) # instead, I should init it like this: Foo(a=1,b=2,c=2.5) So, I need to be able to pass positional keywords to the class. Is it possible? A: Pydantic objects can't be init with positional arguments. import json from pydantic import BaseModel from typing import Optional class Foo(BaseModel): a: int b: Optional[str] c: Optional[float] You have to give Pydantic every key you want to init your model with (what you did): Foo(a=1,b="2",c=2.5) Or you can use a json: json_raw = '{"a": 1, "b": "2", "c": 3}' some_dict = json.loads(json_raw) my_foo = Foo(**some_dict) mix of both: json_raw = '{"a": 1, "b": "2"}' some_dict = json.loads(json_raw) my_foo = Foo(**some_dict, c=3) Why is that ? Here are some reasons: when you have lot of fields - it would be very easy to add another field into a model and suddenly all code which assumes fields have a given position breaks silently annotation only fields mean the order of pydantic model fields different from that in code. A: Example of override __init__ method with type hint which works in pycharm class Foo(BaseModel): a: int b: Optional[str] c: Optional[float] def __init__(self, a: int, b: Optional[str] = None, c: Optional[float] = None, **kwargs) -> None: super(Foo, self).__init__(a=a, b=b, c=c, **kwargs)
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): a: int b: Optional[str] c: Optional[float] And when I init the class, I need to pass keyword arguments: So, I cannot initialize the class like this: Foo(1,2,2.5) # instead, I should init it like this: Foo(a=1,b=2,c=2.5) So, I need to be able to pass positional keywords to the class. Is it possible?
[ "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\",c=2.5)\n\nOr you can use a json:\njson_raw = '{\"a\": 1, \"b\": \"2\", \"c\": 3}'\nsome_dict = json.loads(json_raw)\nmy_foo = Foo(**some_dict)\n\nmix of both:\njson_raw = '{\"a\": 1, \"b\": \"2\"}'\nsome_dict = json.loads(json_raw)\nmy_foo = Foo(**some_dict, c=3)\n\nWhy is that ? Here are some reasons:\n\nwhen you have lot of fields - it would be very easy to add another field into a model and suddenly all code which assumes fields have a given position breaks silently\nannotation only fields mean the order of pydantic model fields different from that in code.\n\n", "Example of override __init__ method with type hint which works in pycharm\nclass Foo(BaseModel):\n a: int\n b: Optional[str]\n c: Optional[float]\n \n def __init__(self, a: int,\n b: Optional[str] = None,\n c: Optional[float] = None,\n **kwargs) -> None:\n super(Foo, self).__init__(a=a, b=b, c=c, **kwargs)\n\n" ]
[ 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 index set as a list on a new data frame, which is output. output = [] output [sls1, sls2] [sls3] [sls4, sls5] The first row is sls1, sls2 because the number of values from both indices is equal to 10, while the second row of sls3 only because the value of column c1 in index sls3 is 7 where if added up with the next index values will amount to more than 10. And so on Thank You A: There is no vectorized way to compute a cumulated sum with restart on a threshold, you'll have to use a loop. Then combine this with groupby.agg: def group(s, thresh=10): out = [] g = 0 curr_sum = 0 for v in s: curr_sum += v if curr_sum > thresh: g += 1 curr_sum = v out.append(g) return pd.Series(out, index=s.index) out = df.groupby(group(df['c1']))['Index'].agg(list) Output: 0 [sls1, sls2] 1 [sls3] 2 [sls4, sls5] Name: Index, dtype: object
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. output = [] output [sls1, sls2] [sls3] [sls4, sls5] The first row is sls1, sls2 because the number of values from both indices is equal to 10, while the second row of sls3 only because the value of column c1 in index sls3 is 7 where if added up with the next index values will amount to more than 10. And so on Thank You
[ "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 curr_sum = v\n out.append(g)\n return pd.Series(out, index=s.index)\n\nout = df.groupby(group(df['c1']))['Index'].agg(list)\n\nOutput:\n0 [sls1, sls2]\n1 [sls3]\n2 [sls4, sls5]\nName: Index, dtype: object\n\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. Does anybody know, where to switch on again this check for Python/Django? HTML and JavaScript files are working fine, but for Python files it was broken. A: This was related to some extensions you installed which were conflict with each other. I think the easiest way is to reinstall vscode.
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 Python/Django? HTML and JavaScript files are working fine, but for Python files it was broken.
[ "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 each one in the new file. I already have a function to do that, but if 2 or more dates are equal they should be put in the same line, and I don't know how to do it :'( Dates come with their IDs and are returned from another function like this: l = [(ID1, date1), (ID2, date2), (ID3, date3)] This should be the final result: if l == [(ID1, 20160101), (ID2, 20180101), (ID3, 20160101)]: Line 1: 20160101 - ID1, ID3 Line 2: 20180101 - ID2 What's the best way to achive this? This is what I've written so far (this creates a new row whether dates are equal or not): def gestRid(fimport, fimpianto): for i in range(2, fimport.max_row + 1): if dateRid(fimpianto, i): for tupla in dateRid(fimpianto, i): cod, data = tupla ultima_riga = fimport.max_row + 1 ultima_riga == last_row for j in range(1, fimport.max_column + 1): #Copies row at the end of worksheet fimport.cell(row = ultima_riga, column = j).value = fimport.cell(row = i, column = j).value fimport.cell(row = ultima_riga, column = 101).value = fimport.cell(row = i, column = 101).value + 1 fimport.cell(row = ultima_riga, column = 1).value = fimport.cell(row = ultima_riga - 1, column = 1).value + 1 fimport.cell(row = i, column = 46).value = (datetime.strptime(str(data), '%Y%m%d').date() - timedelta(days = 1)).strftime('%d/%m/%Y') fimport.cell(row = ultima_riga, column = 45).value = datetime.strptime(str(data), '%Y%m%d').strftime('%d/%m/%Y') fimport.cell(row = ultima_riga, column = 48).value = fimport.cell(row = ultima_riga, column = 45).value[6:] #Copies id in the first free cell if not fimport.cell(row = ultima_riga, column = 78).value: fimport.cell(row = ultima_riga, column = 78).value = cod elif not fimport.cell(row = ultima_riga, column = 82).value: fimport.cell(row = ultima_riga, column = 82).value = cod else: fimport.cell(row = ultima_riga, column = 86).value = cod A: One way to aggregate is using collections.defaultdict(list) and then print out the values from the defaultdict - from collections import defaultdict d = defaultdict(list) l = [("ID1", 20160101), ("ID2", 20180101), ("ID3", 20160101)] for idx, dt in l: d[dt].append(idx) for key, val in d.items(): print(f'{key} - {", ".join(val)}') Output 20160101 - ID1, ID3 20180101 - ID2
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 that, but if 2 or more dates are equal they should be put in the same line, and I don't know how to do it :'( Dates come with their IDs and are returned from another function like this: l = [(ID1, date1), (ID2, date2), (ID3, date3)] This should be the final result: if l == [(ID1, 20160101), (ID2, 20180101), (ID3, 20160101)]: Line 1: 20160101 - ID1, ID3 Line 2: 20180101 - ID2 What's the best way to achive this? This is what I've written so far (this creates a new row whether dates are equal or not): def gestRid(fimport, fimpianto): for i in range(2, fimport.max_row + 1): if dateRid(fimpianto, i): for tupla in dateRid(fimpianto, i): cod, data = tupla ultima_riga = fimport.max_row + 1 ultima_riga == last_row for j in range(1, fimport.max_column + 1): #Copies row at the end of worksheet fimport.cell(row = ultima_riga, column = j).value = fimport.cell(row = i, column = j).value fimport.cell(row = ultima_riga, column = 101).value = fimport.cell(row = i, column = 101).value + 1 fimport.cell(row = ultima_riga, column = 1).value = fimport.cell(row = ultima_riga - 1, column = 1).value + 1 fimport.cell(row = i, column = 46).value = (datetime.strptime(str(data), '%Y%m%d').date() - timedelta(days = 1)).strftime('%d/%m/%Y') fimport.cell(row = ultima_riga, column = 45).value = datetime.strptime(str(data), '%Y%m%d').strftime('%d/%m/%Y') fimport.cell(row = ultima_riga, column = 48).value = fimport.cell(row = ultima_riga, column = 45).value[6:] #Copies id in the first free cell if not fimport.cell(row = ultima_riga, column = 78).value: fimport.cell(row = ultima_riga, column = 78).value = cod elif not fimport.cell(row = ultima_riga, column = 82).value: fimport.cell(row = ultima_riga, column = 82).value = cod else: fimport.cell(row = ultima_riga, column = 86).value = cod
[ "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():\n print(f'{key} - {\", \".join(val)}')\n\nOutput\n20160101 - ID1, ID3\n20180101 - ID2\n\n" ]
[ 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-install.html Not sure if I can make it work or I need to re-install an older version of python. Thank you I tried pip install Snowflake, but it says I already have it installed. A: 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. This ensures that the connector was tested and works with these versions of Python as well as ensures that your Python installation includes critical security fixes.
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 it work or I need to re-install an older version of python. Thank you I tried pip install Snowflake, but it says I already have it installed.
[ "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 includes critical security fixes.\n" ]
[ 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 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, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71], "YES")], [([0, 1, 2, 3, 4, 5, 6, 7], "NO")] list2 = [[['1'], [43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71]], [['1'], [117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145]], [['2'], [272, 273, 274, 275, 276, 277, 278, 279, 280, 281, 282, 283, 284, 285, 286, 287, 288]]] list1 = [[0, 1, 2, 3, 4, 5, 6, 7], [8, 9, 10, 11, 12, 13], [18, 19, 20, 21, 22, 23], [24, 25, 26, 27, 28, 29, 30, 31], [32, 33, 34, 35, 36], [43, 44, 45, 46, 47, 48], [53, 54, 55, 56, 57, 58], [59, 60, 61, 62, 63, 64, 65, 66], [67, 68, 69, 70, 71], [76, 77, 78, 79, 80, 81, 82, 83], [88, 89, 90, 91, 92], [101, 102, 103, 104, 105, 106, 107, 108, 109], [111, 112, 113, 114, 115, 116], [117, 118, 119, 120, 121, 122], [127, 128, 129, 130, 131, 132], [133, 134, 135, 136, 137, 138, 139, 140], [141, 142, 143, 144, 145], [158, 159, 160, 161, 162, 163], [164, 165, 166, 167, 168, 169], [188, 189, 190, 191, 192, 193, 194, 195], [196, 197, 198, 199, 200, 201, 202, 203, 204, 205], [221, 222, 223, 224, 225], [236, 237, 238, 239, 240, 241, 242], [243, 244, 245, 246, 247, 248], [276, 277, 278, 279, 280, 281, 282], [283, 284, 285, 286, 287, 288], [313, 314, 315, 316, 317], [318, 319, 320, 321, 322, 323]] for ent in list1: for cor in list2: if set(ent).issubset(cor[1]) == True: print(cor[0], ent, cor[1], "YES") else: print("NO") The code above gives me the result 84 times, which is the iteration of 28 and 3 elements of both lists, therefore rises a question: Is it even possible? A: 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. But back to your implementation: you do two time loop and in each scenario you print something, that is expected to have 28 * 3 time. What you need is that in your inner loop you just print after it is finished. for ent in list1: idx = [set(ent).issubset(cor[1]) for cor in list2] if any(idx): i = idx.index(True) print(list2[i][0], ent, list2[i][1], "YES") else: print("NO")
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, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71], "YES")], [([0, 1, 2, 3, 4, 5, 6, 7], "NO")] list2 = [[['1'], [43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71]], [['1'], [117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145]], [['2'], [272, 273, 274, 275, 276, 277, 278, 279, 280, 281, 282, 283, 284, 285, 286, 287, 288]]] list1 = [[0, 1, 2, 3, 4, 5, 6, 7], [8, 9, 10, 11, 12, 13], [18, 19, 20, 21, 22, 23], [24, 25, 26, 27, 28, 29, 30, 31], [32, 33, 34, 35, 36], [43, 44, 45, 46, 47, 48], [53, 54, 55, 56, 57, 58], [59, 60, 61, 62, 63, 64, 65, 66], [67, 68, 69, 70, 71], [76, 77, 78, 79, 80, 81, 82, 83], [88, 89, 90, 91, 92], [101, 102, 103, 104, 105, 106, 107, 108, 109], [111, 112, 113, 114, 115, 116], [117, 118, 119, 120, 121, 122], [127, 128, 129, 130, 131, 132], [133, 134, 135, 136, 137, 138, 139, 140], [141, 142, 143, 144, 145], [158, 159, 160, 161, 162, 163], [164, 165, 166, 167, 168, 169], [188, 189, 190, 191, 192, 193, 194, 195], [196, 197, 198, 199, 200, 201, 202, 203, 204, 205], [221, 222, 223, 224, 225], [236, 237, 238, 239, 240, 241, 242], [243, 244, 245, 246, 247, 248], [276, 277, 278, 279, 280, 281, 282], [283, 284, 285, 286, 287, 288], [313, 314, 315, 316, 317], [318, 319, 320, 321, 322, 323]] for ent in list1: for cor in list2: if set(ent).issubset(cor[1]) == True: print(cor[0], ent, cor[1], "YES") else: print("NO") The code above gives me the result 84 times, which is the iteration of 28 and 3 elements of both lists, therefore rises a question: Is it even possible?
[ "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 scenario you print something, that is expected to have 28 * 3 time.\nWhat you need is that in your inner loop you just print after it is finished.\nfor ent in list1:\n idx = [set(ent).issubset(cor[1]) for cor in list2]\n if any(idx):\n i = idx.index(True)\n print(list2[i][0], ent, list2[i][1], \"YES\")\n else:\n print(\"NO\")\n\n" ]
[ 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', blocks.ProductNameAndUrlBlock()), ], null=True, blank=True, use_json_field=True, ) def save(self, *args, **kwargs): # Here I want to turn the product_details data into a dict print('self.product_details') On print it shows a bunch of HTML code created by StreamField so I could do it the hacky way and turn it into a string, manuiplate it with .replace and then import it into json or JsonResponse but I want to learn the correct way to do this. When I do try to load it with json or JsonResponse I get the error the JSON object must be str, bytes or bytearray, not StreamValue A: 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. You can loop through the array and access all your key/value pairs from there. e.g. <ul> {% for product in self.product_details.raw_data %} <li>{{ product.sku }} - {{ product.name }}</li> {% endfor %} </ul> or pass it into some JS for processing and rendering {{self.product_details.raw_data|json_script:"product_details"}} <script>someJS('product_details')</script>
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()), ], null=True, blank=True, use_json_field=True, ) def save(self, *args, **kwargs): # Here I want to turn the product_details data into a dict print('self.product_details') On print it shows a bunch of HTML code created by StreamField so I could do it the hacky way and turn it into a string, manuiplate it with .replace and then import it into json or JsonResponse but I want to learn the correct way to do this. When I do try to load it with json or JsonResponse I get the error the JSON object must be str, bytes or bytearray, not StreamValue
[ "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 <li>{{ product.sku }} - {{ product.name }}</li>\n {% endfor %}\n</ul>\n\nor pass it into some JS for processing and rendering\n{{self.product_details.raw_data|json_script:\"product_details\"}}\n<script>someJS('product_details')</script>\n\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 data set. I have written the following test program: import tensorflow as tf import numpy as np from kmeanstf import KMeansTF print("GPU Available: ", tf.test.is_gpu_available()) nn=1000 dd=250000 print("{:,d} bytes".format(nn*dd*4)) dic = {} for x in "ABCD": dic[x]=tf.random.normal((nn,dd)) print(x,dic[x][:1,:2]) print("done...") This is a typical output on my system with (ubuntu 18.04 LTS, GTX-1060 6GB). Please note the core dump. python misc/maxmem.py GPU Available: True 1,000,000,000 bytes A tf.Tensor([[-0.23787294 -2.0841186 ]], shape=(1, 2), dtype=float32) B tf.Tensor([[ 0.23762687 -1.1229591 ]], shape=(1, 2), dtype=float32) C tf.Tensor([[-1.2672468 0.92139906]], shape=(1, 2), dtype=float32) 2020-01-02 17:35:05.988473: W tensorflow/core/common_runtime/bfc_allocator.cc:419] Allocator (GPU_0_bfc) ran out of memory trying to allocate 953.67MiB (rounded to 1000000000). Current allocation summary follows. 2020-01-02 17:35:05.988752: W tensorflow/core/common_runtime/bfc_allocator.cc:424] **************************************************************************************************xx 2020-01-02 17:35:05.988835: W tensorflow/core/framework/op_kernel.cc:1622] OP_REQUIRES failed at cwise_ops_common.cc:82 : Resource exhausted: OOM when allocating tensor with shape[1000,250000] and type float on /job:localhost/replica:0/task:0/device:GPU:0 by allocator GPU_0_bfc Segmentation fault (core dumped) Occasionally I do get an error from python instead of a core dump (see below). This would actually be better since I could catch it and thus determine by trial and error the maximum available memory. But it alternates with core dumps: python misc/maxmem.py GPU Available: True 1,000,000,000 bytes A tf.Tensor([[-0.73510283 -0.94611156]], shape=(1, 2), dtype=float32) B tf.Tensor([[-0.8458411 0.552555 ]], shape=(1, 2), dtype=float32) C tf.Tensor([[0.30532074 0.266423 ]], shape=(1, 2), dtype=float32) 2020-01-02 17:35:26.401156: W tensorflow/core/common_runtime/bfc_allocator.cc:419] Allocator (GPU_0_bfc) ran out of memory trying to allocate 953.67MiB (rounded to 1000000000). Current allocation summary follows. 2020-01-02 17:35:26.401486: W tensorflow/core/common_runtime/bfc_allocator.cc:424] **************************************************************************************************xx 2020-01-02 17:35:26.401571: W tensorflow/core/framework/op_kernel.cc:1622] OP_REQUIRES failed at cwise_ops_common.cc:82 : Resource exhausted: OOM when allocating tensor with shape[1000,250000] and type float on /job:localhost/replica:0/task:0/device:GPU:0 by allocator GPU_0_bfc Traceback (most recent call last): File "misc/maxmem.py", line 11, in <module> dic[x]=tf.random.normal((nn,dd)) File "/home/fritzke/miniconda2/envs/tf20b/lib/python3.7/site-packages/tensorflow_core/python/ops/random_ops.py", line 76, in random_normal value = math_ops.add(mul, mean_tensor, name=name) File "/home/fritzke/miniconda2/envs/tf20b/lib/python3.7/site-packages/tensorflow_core/python/ops/gen_math_ops.py", line 391, in add _six.raise_from(_core._status_to_exception(e.code, message), None) File "<string>", line 3, in raise_from tensorflow.python.framework.errors_impl.ResourceExhaustedError: OOM when allocating tensor with shape[1000,250000] and type float on /job:localhost/replica:0/task:0/device:GPU:0 by allocator GPU_0_bfc [Op:Add] name: random_normal/ How could I reliably get this information for whatever system the software is running on? A: I actually found an answer in this old question of mine . To bring some additional benefit to readers I tested the mentioned program import nvidia_smi nvidia_smi.nvmlInit() handle = nvidia_smi.nvmlDeviceGetHandleByIndex(0) # card id 0 hardcoded here, there is also a call to get all available card ids, so we could iterate info = nvidia_smi.nvmlDeviceGetMemoryInfo(handle) print("Total memory:", info.total) print("Free memory:", info.free) print("Used memory:", info.used) nvidia_smi.nvmlShutdown() on colab with the following result: Total memory: 17071734784 Free memory: 17071734784 Used memory: 0 The actual GPU I had there was a Tesla P100 as can be seen from executing !nvidia-smi and observing the output +-----------------------------------------------------------------------------+ | NVIDIA-SMI 440.44 Driver Version: 418.67 CUDA Version: 10.1 | |-------------------------------+----------------------+----------------------+ | GPU Name Persistence-M| Bus-Id Disp.A | Volatile Uncorr. ECC | | Fan Temp Perf Pwr:Usage/Cap| Memory-Usage | GPU-Util Compute M. | |===============================+======================+======================| | 0 Tesla P100-PCIE... Off | 00000000:00:04.0 Off | 0 | | N/A 32C P0 26W / 250W | 0MiB / 16280MiB | 0% Default | +-------------------------------+----------------------+----------------------+ +-----------------------------------------------------------------------------+ | Processes: GPU Memory | | GPU PID Type Process name Usage | |=============================================================================| | No running processes found | +-----------------------------------------------------------------------------+ A: This code will return free GPU memory in MegaBytes for each GPU: import subprocess as sp import os def get_gpu_memory(): command = "nvidia-smi --query-gpu=memory.free --format=csv" memory_free_info = sp.check_output(command.split()).decode('ascii').split('\n')[:-1][1:] memory_free_values = [int(x.split()[0]) for i, x in enumerate(memory_free_info)] return memory_free_values get_gpu_memory() This answer relies on nvidia-smi being installed (which is pretty much always the case for Nvidia GPUs) and therefore is limited to NVidia GPUs. A: If you're using tensorflow-gpu==2.5, you can use tf.config.experimental.get_memory_info('GPU:0') to get the actual consumed GPU memory by TF. Nvidia-smi tells you nothing, as TF allocates everything for itself and leaves nvidia-smi no information to track how much of that pre-allocated memory is actually being used. A: In summary, the best solution that worked well is using: tf.config.experimental.get_memory_info('DEVICE_NAME') This function returns a dictionary with two keys: 'current': The current memory used by the device, in bytes 'peak': The peak memory used by the device across the run of the program, in bytes. The value of these keys is the ACTUAL memory used not the allocated one that is returned by nvidia-smi. In reality, for GPUs, TensorFlow will allocate all the memory by default rendering using nvidia-smi to check for the used memory in your code useless. Even if, tf.config.experimental.set_memory_growth is set to true, Tensorflow will no more allocate the whole available memory but is going to remain in allocating more memory than the one is used and in a discrete manner, i.e. allocates 4589MiB then 8717MiB then 16943MiB then 30651 MiB, etc. A small note concerning the get_memory_info() is that it doesn't return correct values if used in a tf.function() decorated function. Thus, the peak key shall be used after executing tf.function() decorated function to determine the peak memory used. For older versions of Tensorflow, tf.config.experimental.get_memory_usage('DEVICE_NAME') was the only available function and only returned the used memory (no option for determining the peak memory). Final note, you can also consider the Tensorflow Profiler available with Tensorboard to get information regarding your memory usage. Hope this helps :)
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 import numpy as np from kmeanstf import KMeansTF print("GPU Available: ", tf.test.is_gpu_available()) nn=1000 dd=250000 print("{:,d} bytes".format(nn*dd*4)) dic = {} for x in "ABCD": dic[x]=tf.random.normal((nn,dd)) print(x,dic[x][:1,:2]) print("done...") This is a typical output on my system with (ubuntu 18.04 LTS, GTX-1060 6GB). Please note the core dump. python misc/maxmem.py GPU Available: True 1,000,000,000 bytes A tf.Tensor([[-0.23787294 -2.0841186 ]], shape=(1, 2), dtype=float32) B tf.Tensor([[ 0.23762687 -1.1229591 ]], shape=(1, 2), dtype=float32) C tf.Tensor([[-1.2672468 0.92139906]], shape=(1, 2), dtype=float32) 2020-01-02 17:35:05.988473: W tensorflow/core/common_runtime/bfc_allocator.cc:419] Allocator (GPU_0_bfc) ran out of memory trying to allocate 953.67MiB (rounded to 1000000000). Current allocation summary follows. 2020-01-02 17:35:05.988752: W tensorflow/core/common_runtime/bfc_allocator.cc:424] **************************************************************************************************xx 2020-01-02 17:35:05.988835: W tensorflow/core/framework/op_kernel.cc:1622] OP_REQUIRES failed at cwise_ops_common.cc:82 : Resource exhausted: OOM when allocating tensor with shape[1000,250000] and type float on /job:localhost/replica:0/task:0/device:GPU:0 by allocator GPU_0_bfc Segmentation fault (core dumped) Occasionally I do get an error from python instead of a core dump (see below). This would actually be better since I could catch it and thus determine by trial and error the maximum available memory. But it alternates with core dumps: python misc/maxmem.py GPU Available: True 1,000,000,000 bytes A tf.Tensor([[-0.73510283 -0.94611156]], shape=(1, 2), dtype=float32) B tf.Tensor([[-0.8458411 0.552555 ]], shape=(1, 2), dtype=float32) C tf.Tensor([[0.30532074 0.266423 ]], shape=(1, 2), dtype=float32) 2020-01-02 17:35:26.401156: W tensorflow/core/common_runtime/bfc_allocator.cc:419] Allocator (GPU_0_bfc) ran out of memory trying to allocate 953.67MiB (rounded to 1000000000). Current allocation summary follows. 2020-01-02 17:35:26.401486: W tensorflow/core/common_runtime/bfc_allocator.cc:424] **************************************************************************************************xx 2020-01-02 17:35:26.401571: W tensorflow/core/framework/op_kernel.cc:1622] OP_REQUIRES failed at cwise_ops_common.cc:82 : Resource exhausted: OOM when allocating tensor with shape[1000,250000] and type float on /job:localhost/replica:0/task:0/device:GPU:0 by allocator GPU_0_bfc Traceback (most recent call last): File "misc/maxmem.py", line 11, in <module> dic[x]=tf.random.normal((nn,dd)) File "/home/fritzke/miniconda2/envs/tf20b/lib/python3.7/site-packages/tensorflow_core/python/ops/random_ops.py", line 76, in random_normal value = math_ops.add(mul, mean_tensor, name=name) File "/home/fritzke/miniconda2/envs/tf20b/lib/python3.7/site-packages/tensorflow_core/python/ops/gen_math_ops.py", line 391, in add _six.raise_from(_core._status_to_exception(e.code, message), None) File "<string>", line 3, in raise_from tensorflow.python.framework.errors_impl.ResourceExhaustedError: OOM when allocating tensor with shape[1000,250000] and type float on /job:localhost/replica:0/task:0/device:GPU:0 by allocator GPU_0_bfc [Op:Add] name: random_normal/ How could I reliably get this information for whatever system the software is running on?
[ "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 we could iterate\n\ninfo = nvidia_smi.nvmlDeviceGetMemoryInfo(handle)\n\nprint(\"Total memory:\", info.total)\nprint(\"Free memory:\", info.free)\nprint(\"Used memory:\", info.used)\n\nnvidia_smi.nvmlShutdown()\n\non colab with the following result:\nTotal memory: 17071734784\nFree memory: 17071734784\nUsed memory: 0\n\nThe actual GPU I had there was a Tesla P100 as can be seen from executing \n!nvidia-smi\n\nand observing the output\n+-----------------------------------------------------------------------------+\n| NVIDIA-SMI 440.44 Driver Version: 418.67 CUDA Version: 10.1 |\n|-------------------------------+----------------------+----------------------+\n| GPU Name Persistence-M| Bus-Id Disp.A | Volatile Uncorr. ECC |\n| Fan Temp Perf Pwr:Usage/Cap| Memory-Usage | GPU-Util Compute M. |\n|===============================+======================+======================|\n| 0 Tesla P100-PCIE... Off | 00000000:00:04.0 Off | 0 |\n| N/A 32C P0 26W / 250W | 0MiB / 16280MiB | 0% Default |\n+-------------------------------+----------------------+----------------------+\n\n+-----------------------------------------------------------------------------+\n| Processes: GPU Memory |\n| GPU PID Type Process name Usage |\n|=============================================================================|\n| No running processes found |\n+-----------------------------------------------------------------------------+\n\n", "This code will return free GPU memory in MegaBytes for each GPU:\nimport subprocess as sp\nimport os\n\ndef get_gpu_memory():\n command = \"nvidia-smi --query-gpu=memory.free --format=csv\"\n memory_free_info = sp.check_output(command.split()).decode('ascii').split('\\n')[:-1][1:]\n memory_free_values = [int(x.split()[0]) for i, x in enumerate(memory_free_info)]\n return memory_free_values\n\nget_gpu_memory()\n\nThis answer relies on nvidia-smi being installed (which is pretty much always the case for Nvidia GPUs) and therefore is limited to NVidia GPUs.\n", "If you're using tensorflow-gpu==2.5, you can use\ntf.config.experimental.get_memory_info('GPU:0')\n\nto get the actual consumed GPU memory by TF. Nvidia-smi tells you nothing, as TF allocates everything for itself and leaves nvidia-smi no information to track how much of that pre-allocated memory is actually being used.\n", "In summary, the best solution that worked well is using: tf.config.experimental.get_memory_info('DEVICE_NAME')\nThis function returns a dictionary with two keys:\n\n'current': The current memory used by the device, in bytes\n'peak': The peak memory used by the device across the run of the program, in bytes.\n\nThe value of these keys is the ACTUAL memory used not the allocated one that is returned by nvidia-smi.\nIn reality, for GPUs, TensorFlow will allocate all the memory by default rendering using nvidia-smi to check for the used memory in your code useless.\nEven if, tf.config.experimental.set_memory_growth is set to true, Tensorflow will no more allocate the whole available memory but is going to remain in allocating more memory than the one is used and in a discrete manner,\ni.e. allocates 4589MiB then 8717MiB then 16943MiB then 30651 MiB, etc.\nA small note concerning the get_memory_info() is that it doesn't return correct values if used in a tf.function() decorated function. Thus, the peak key shall be used after executing tf.function() decorated function\nto determine the peak memory used.\nFor older versions of Tensorflow, tf.config.experimental.get_memory_usage('DEVICE_NAME') was the only available function and only returned the used memory (no option for determining the peak memory).\nFinal note, you can also consider the Tensorflow Profiler available with Tensorboard to get information regarding your memory usage.\nHope this helps :)\n" ]
[ 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 apply it to the masked array, it also changes the color... How to perform the shuffling alongside only the non-color axes? from PIL import Image import requests from io import BytesIO import numpy as np response = requests.get("https://www.4dface.io/wp-content/uploads/2018/10/4DFM_sample2.jpg") img = Image.open(BytesIO(response.content)) img.show() def _shuffle_2D(x): return _shuffled(_shuffled(x.swapaxes(0, 1)).swapaxes(0, 1)) def _shuffled(x): """Return a shuffled array. Because python does it in-place.""" np.random.shuffle(x) return x array = np.array(img) PIL.Image.fromarray(_shuffle_2D(array)) Below, the same is applied to a masked array: as one can see, it also shuffles the colors... # Get mask mask = np.array(img.convert("L")) != 255 array[mask] = _shuffle_2D(array[mask]) PIL.Image.fromarray(array) Any pointer is welcome! 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 won't get separated from their little friends. You can do this extremely quickly with np.dot() like this: # Make a single 24-bit number for each pixel, instead of 3x 8-bit numbers u32 = np.dot(RGBarray.astype(np.uint32),[1,256,65536]) So here's what I am suggesting in concrete terms: #!/usr/bin/env python3 from PIL import Image import requests from io import BytesIO import numpy as np def _shuffled(x): """Return a shuffled array. Because python does it in-place.""" np.random.shuffle(x) return x response = requests.get("https://www.4dface.io/wp-content/uploads/2018/10/4DFM_sample2.jpg") img = Image.open(BytesIO(response.content)) array = np.array(img) # Get mask of non-white pixels mask = np.array(img.convert("L")) != 255 # Combine RGB888 pixels into a single 24-bit entity u32 = np.dot(array.astype(np.uint32),[1,256,65536]) u32[mask] = _shuffled(u32[mask]) # Now split 24-bit entities back into RGB888 r = u32 & 0xff g = (u32 >> 8 ) & 0xff b = (u32 >> 16 ) & 0xff array = np.dstack((r,g,b)).astype(np.uint8) res = Image.fromarray(array) res.save('result.png')
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 alongside only the non-color axes? from PIL import Image import requests from io import BytesIO import numpy as np response = requests.get("https://www.4dface.io/wp-content/uploads/2018/10/4DFM_sample2.jpg") img = Image.open(BytesIO(response.content)) img.show() def _shuffle_2D(x): return _shuffled(_shuffled(x.swapaxes(0, 1)).swapaxes(0, 1)) def _shuffled(x): """Return a shuffled array. Because python does it in-place.""" np.random.shuffle(x) return x array = np.array(img) PIL.Image.fromarray(_shuffle_2D(array)) Below, the same is applied to a masked array: as one can see, it also shuffles the colors... # Get mask mask = np.array(img.convert("L")) != 255 array[mask] = _shuffle_2D(array[mask]) PIL.Image.fromarray(array) Any pointer is welcome!
[ "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 won't get separated from their little friends.\nYou can do this extremely quickly with np.dot() like this:\n# Make a single 24-bit number for each pixel, instead of 3x 8-bit numbers\nu32 = np.dot(RGBarray.astype(np.uint32),[1,256,65536])\n\nSo here's what I am suggesting in concrete terms:\n#!/usr/bin/env python3\n\nfrom PIL import Image\nimport requests\nfrom io import BytesIO\nimport numpy as np \n\ndef _shuffled(x):\n \"\"\"Return a shuffled array. Because python does it in-place.\"\"\"\n np.random.shuffle(x)\n return x\n\nresponse = requests.get(\"https://www.4dface.io/wp-content/uploads/2018/10/4DFM_sample2.jpg\")\nimg = Image.open(BytesIO(response.content))\narray = np.array(img)\n\n# Get mask of non-white pixels\nmask = np.array(img.convert(\"L\")) != 255\n\n# Combine RGB888 pixels into a single 24-bit entity\nu32 = np.dot(array.astype(np.uint32),[1,256,65536])\nu32[mask] = _shuffled(u32[mask])\n\n# Now split 24-bit entities back into RGB888\nr = u32 & 0xff\ng = (u32 >> 8 ) & 0xff\nb = (u32 >> 16 ) & 0xff\narray = np.dstack((r,g,b)).astype(np.uint8)\nres = Image.fromarray(array)\nres.save('result.png')\n\n\n" ]
[ 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,2,3,3,5] from itertools import groupby seen = set() duplicates = set() for k, _ in groupby(l): if k in seen: print(f'{k} is duplicated') duplicates.add(k) seen.add(k) Output: 5 is duplicated content of duplicates: {5}
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\n\ncontent of duplicates:\n{5}\n\n" ]
[ 0 ]
[]
[]
[ "arraylist", "python" ]
stackoverflow_0074570586_arraylist_python.txt