http://stackoverflow.com/comment/91019356
type: Comment
type: QuestionComment
score: 0
has text: Thanks for comment, i added how the data look like
comment on: http://stackoverflow.com/q/52034043

http://stackoverflow.com/comment/93563889
comment on: http://stackoverflow.com/a/52086299
score: 0
type: AnswerComment
has text: Yes, the results will be the same, the question is about the structure of the results.
type: Comment

http://stackoverflow.com/q/52020472
tagged with: user-interface
has body: So I have two python files that each contain two tkinter windows. One is a Root Tk instance and the other is a Toplevel Tk instance. I am trying to get two string variables in the Toplevel instance from the Root instance, called self.taskhours, and self.taskminutes in the Root instance, once the Toplevel instance is opened. I am fairly certain that I am not passing the Root instance to the Toplevel instance properly. Can anyone assist? Here is the first file, named "timex.py": import tkinter as tk from tkinter import ttk class TimeX(tk.Frame): def __init__(self,master): # INIT WINDOW import datetime tk.Frame.__init__(self,master=master) self.pack() self.master.title("TimeX") # Add title to main window # TOP MENU # self.master.menu = tk.Menu(master) # TOP MENU # FILE MENU # self.master.filemenu = tk.Menu(self.master.menu) self.master.menu.add_cascade(label="File",menu=self.master.filemenu) self.master.menu.add_command(label="New File",command=self.new_file) self.frames = [ tk.Frame(self), # TASKITEM tk.Frame(self), # TIME INPUT tk.Frame(self), # INIT BUTTON # tk.Frame(self), # SHOWS 00:00:00 until INIT BUTTON PRESSED ] # START FRAME 0 frame = self.frames[0] self.taskitem = tk.StringVar(self,"TaskItem") # Entry # self.taskplan = tk.StringVar(self) # Listbox # self.taskdesc = tk.StringVar(self) # Textbox frame.entries = [ tk.Entry(frame,textvariable=self.taskitem), ] for i,entry in enumerate(frame.entries): entry.grid(row=0,column=i) frame = self.frames[1] # THE REAL # self.taskhours = tk.StringVar(self,"Hours") # self.taskminutes = tk.StringVar(self,"Minutes") # THE FOO self.taskhours = tk.StringVar(self,"1") self.taskminutes = tk.StringVar(self,"30") frame.labels = [ tk.Label(frame,text="Estimated Duration") ] frame.entries = [ tk.Entry(frame,textvariable=self.taskhours), tk.Entry(frame,textvariable=self.taskminutes) ] # frame.menubuttons = [ # tk.Menubutton(frame,text="Hour(s)",textvariable=self.taskhours), # tk.Menubutton(frame,text="Minute(s)",textvariable=self.ta…
tagged with: python
favorite count: 0
has answer: http://stackoverflow.com/a/52020724
tagged with: tkinter
type: UnansweredQuestion
downvote count: 1
tagged with: tk-toolkit
score: -1
type: Question
has title: Tkinter: Passing StringVar from one window to another
has comment: http://stackoverflow.com/comment/90992177
upvote count: 0
answer count: 1

http://stackoverflow.com/comment/91161814
comment on: http://stackoverflow.com/q/52105332
score: 0
type: Comment
type: QuestionComment
has text: https://learn.adafruit.com/adafruit-gemma-m0/circuitpython-uart-serial-2

http://stackoverflow.com/comment/91070325
comment on: http://stackoverflow.com/q/52059974
score: 1
has text: Have you tried `label.master.destroy`? Getting rid of the label itself would still leave the anonymous window containing it. (And relying on this anonymous window, rather than explicitly calling `Tk()` so that you have a direct reference to it, strike me as weird - why are you doing things this way?)
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52037352
has body: I have two NumPy arrays with unique elements of when i do np.unique(array_1) i get array([0, 1, 2, 4, 5, 6], dtype=int8) when i do np.unique(array_2) i get array([0, 1, 2, 4, 5, 6], dtype=int8) What i want is to fuse these arrays, by which i mean if i do np.unique() i should get array([0, 2, 4, 10, 12]),dtype=int8) I tried np.concatenate([array_1, array_2]) but unique elements do not change ,i get [0 1 2 4 5 6] as the unique elements. Any suggestions on what i may try would be helpful, Thanks in advance.
has comment: http://stackoverflow.com/comment/91025159
tagged with: numpy
has comment: http://stackoverflow.com/comment/91025077
score: 0
has comment: http://stackoverflow.com/comment/91025353
accepted answer: http://stackoverflow.com/a/52037583
has comment: http://stackoverflow.com/comment/91024875
answer count: 1
has comment: http://stackoverflow.com/comment/91024908
favorite count: 0
has comment: http://stackoverflow.com/comment/91024931
tagged with: python
has comment: http://stackoverflow.com/comment/91024979
has comment: http://stackoverflow.com/comment/91025054
has comment: http://stackoverflow.com/comment/91024929
has comment: http://stackoverflow.com/comment/91025349
has comment: http://stackoverflow.com/comment/91025357
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52037583
has title: Fuse two arrays
upvote count: 1
downvote count: 1
type: Question

euclidean-distance
type: Tag
tags question: http://stackoverflow.com/q/51986758
tag name: euclidean-distance

http://stackoverflow.com/q/52052561
tagged with: python
has comment: http://stackoverflow.com/comment/91055761
tagged with: list
downvote count: 0
score: 1
tagged with: loops
has comment: http://stackoverflow.com/comment/91055727
type: Question
has comment: http://stackoverflow.com/comment/91055671
has body: I would like to rename the file according to several examples. My idea is by using a list such as(example): a = [1,2,3,4,5,6,7,8,10, 100, 200] Then loop into this list and rename based on each of the element within the list. My code is as follow (This is an example of the code and not the full version, I just want to get to know a way to input these element into the "**" and replace it with value such as "1", "2" or "100"): class man: ... def function(a): ... def output1(myfile): with open("text_**.txt","w+") as outfile: outfile.write() def output2(myfile2): with open("text_**.txt","w+") as outfile: outfile.write() def total(a,b): with open("text_**.txt","w+") as outfile: outfile.write() if __name__ == "__main__": file = function("**.txt") ... output1(myfile) output2(myfile2) total("**.txt", "**.txt") For example, I would like my output to be like this: class man: ... def function(a): ... def output1(myfile): with open("text_1.txt","w+") as outfile: outfile.write() def output2(myfile2): with open("text_1.txt","w+") as outfile: outfile.write() def total(a,b): with open("text_1.txt","w+") as outfile: outfile.write() if __name__ == "__main__": file = function("1.txt") ... output1(myfile) output2(myfile2) total("1.txt", "1.txt") My goal is the "**" will be replace with all the elements within the list from 1 to 200. If possible to make it this way then I wouldnt need to keep changing the value in my program everytime I want to load new name for it.
has comment: http://stackoverflow.com/comment/91055892
has comment: http://stackoverflow.com/comment/91055692
upvote count: 1
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/52052917
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91055540
has title: rename the final according to my list input

http://stackoverflow.com/q/52093695
has answer: http://stackoverflow.com/a/52167159
type: Question
has answer: http://stackoverflow.com/a/52176473
downvote count: 0
answer count: 3
score: 14
has comment: http://stackoverflow.com/comment/91137573
has answer: http://stackoverflow.com/a/52273403
tagged with: python
favorite count: 0
has title: Increasing cost for linear regression
upvote count: 14
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91139224
tagged with: machine-learning
has comment: http://stackoverflow.com/comment/91284726
tagged with: linear-regression
has body: I implemented, for training purpose, a linear regression in python. The problem is that the cost is increasing instead of decreasing. For the data I use the Airfoil Self-Noise Data Set. Data can be found here I import data as follow : import pandas as pd def features(): features = pd.read_csv("data/airfoil_self_noise/airfoil_self_noise.dat.txt", sep="\t", header=None) X = features.iloc[:, 0:5] Y = features.iloc[:, 5] return X.values, Y.values.reshape(Y.shape[0], 1) My code for the linear regression is the following : import numpy as np import random class linearRegression(): def __init__(self, learning_rate=0.01, max_iter=20): """ Initialize the hyperparameters of the linear regression. :param learning_rate: the learning rate :param max_iter: the max numer of iteration to perform """ self.lr = learning_rate self.max_iter = max_iter self.m = None self.weights = None self.bias = None def fit(self, X, Y): """ Run gradient descent algorithm :param X: the inputs :param Y: the outputs :return: """ self.m = X.shape[0] self.weights = np.random.normal(0, 0.1, (X.shape[1], 1)) self.bias = random.normalvariate(0, 0.1) for iter in range(0, self.max_iter): A = self.__forward(X) dw, db = self.__backward(A, X, Y) J = (1/(2 * self.m)) * np.sum(np.power((A - Y), 2)) print("at iteration %s cost is %s" % (iter, J)) self.weights = self.weights - self.lr * dw self.bias = self.bias - self.lr * db def predict(self, X): """ Make prediction on the inputs :param X: the inputs :return: """ Y_pred = self.__forward(X) return Y_pred def __forward(self, X): """ Compute the linear function on the inputs :param X: the inputs :return: A: the activation """ A = np.dot(X, self.weights) + self.bias return A def __backward(self, A, X, Y): """ :param A: the activation :param X: the inputs :param Y: the outputs :return: dw: the gradient for the weights db: the gradient for the bias """ dw = (1 / self.m) * np.dot(X.T, (A - Y)) db = (1 / self.m) * np.sum(A - Y) return dw, db Then I instantiate the linearReg…
has comment: http://stackoverflow.com/comment/91285853

http://stackoverflow.com/q/52024880
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/52036266
type: Question
has comment: http://stackoverflow.com/comment/91181515
has title: LabelEncoding DataFrame string columns
answer count: 1
tagged with: scikit-learn
has comment: http://stackoverflow.com/comment/91353817
linked to: http://stackoverflow.com/q/24458645
score: 0
tagged with: sklearn-pandas
has body: I've got a DataFrame with floats, strings, and strings that can be interpreted as dates. Label encoding across multiple columns in scikit-learn from sklearn.base import BaseEstimator, TransformerMixin class DataFrameSelector(BaseException, TransformerMixin): def __init__(self, attribute_names): self.attribute_names = attribute_names def fit(self, X, y=None): return self def transform(self, X): return X[self.attribute_names].values class MultiColumnLabelEncoder: def __init__(self,columns = None): self.columns = columns # array of column names to encode def fit(self,X,y=None): return self # not relevant here def transform(self,X): ''' Transforms columns of X specified in self.columns using LabelEncoder(). If no columns specified, transforms all columns in X. ''' output = X.copy() if self.columns is not None: for col in self.columns: output[col] = LabelEncoder().fit_transform(output[col]) else: for colname,col in output.iteritems(): output[colname] = LabelEncoder().fit_transform(col) return output def fit_transform(self,X,y=None): return self.fit(X,y).transform(X) num_attributes = ["a", "b", "c"] num_attributes = list(df_num_median) str_attributes = list(df_str_only) from sklearn.pipeline import Pipeline from sklearn.preprocessing import StandardScaler num_pipeline = Pipeline([ ('selector', DataFrameSelector(num_attributes)), # transforming the Pandas DataFrame into a NumPy array ('imputer', Imputer(strategy="median")), # replacing missing values with the median ('std_scalar', StandardScaler()), # scaling the features using standardization (subtract mean value, divide by variance) ]) from sklearn.preprocessing import LabelEncoder str_pipeline = Pipeline([ ('selector', DataFrameSelector(str_attributes)), # transforming the Pandas DataFrame into a NumPy array ('encoding', MultiColumnLabelEncoder(str_attributes)) ]) from sklearn.pipeline import FeatureUnion full_pipeline = FeatureUnion(transformer_list=[ ("num_pipeline", num_pipeline), #("str_pipeline", str_pipeline) # re…

http://stackoverflow.com/comment/91037510
has text: have you tried `SELECT word, sum(counter) FROM baseline GROUP BY word`?
comment on: http://stackoverflow.com/q/52043323
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/90938721
type: QuestionComment
comment on: http://stackoverflow.com/q/51990390
has text: I am not familiar with how Windows does things but you should be aware that you don't always receive exactly what you ask for with sockets, sometimes the data are split by switches and routers, so you normally have to keep receiving in a loop and adding whatever you receive to whatever you received before until you get all that you want or need. Just because you ask for 1024 bytes does not mean you will get 1024, you may get 53 and have to do another receive, or another 7 receives.
score: 0
type: Comment

http://stackoverflow.com/q/52043153
linked to: http://stackoverflow.com/q/20250771
has comment: http://stackoverflow.com/comment/91040334
has comment: http://stackoverflow.com/comment/91037197
answer count: 0
downvote count: 0
type: UnansweredQuestion
score: 1
has body: I want to rename the elements in my pandas dataframe column named Casa Code. I can do it the following way, see below, but it requires stating Casa Code as index. How can I do a simple renaming of the elements in Casa Code without having to state a column as index beforehand? #Rename Casa Code df = df.set_index('Casa Code') df = df.rename(index={'TT01':'1100', 'CP01':'1101', 'CP02':'1102', })
has comment: http://stackoverflow.com/comment/91041485
tagged with: pandas
has comment: http://stackoverflow.com/comment/91037339
favorite count: 0
has comment: http://stackoverflow.com/comment/91041433
has comment: http://stackoverflow.com/comment/91037277
type: Question
has comment: http://stackoverflow.com/comment/91037346
upvote count: 1
tagged with: python
has title: Python/Pandas: Renaming elements in DataFrame column
has comment: http://stackoverflow.com/comment/91037295

http://stackoverflow.com/q/52097264
downvote count: 2
linked to: http://stackoverflow.com/q/5598181
linked to: http://stackoverflow.com/q/37625208
has comment: http://stackoverflow.com/comment/91144822
has answer: http://stackoverflow.com/a/52097312
accepted answer: http://stackoverflow.com/a/52097312
favorite count: 0
answer count: 5
has title: How to print list elements in one line?
has answer: http://stackoverflow.com/a/67652943
tagged with: python
has answer: http://stackoverflow.com/a/52097417
upvote count: 12
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/123043525
has answer: http://stackoverflow.com/a/52097315
has comment: http://stackoverflow.com/comment/91144789
has answer: http://stackoverflow.com/a/59802650
type: Question
possible better answer: http://stackoverflow.com/a/52097315
has body: I need to print the sorted list of integers, but it should be in a line and without the list square brackets and without any '\n' in the end... import random n = int(input("")) l=[] for i in range(n): x = int(input()) l.append(x) not_sorted = True while not_sorted: x = random.randint(0,n-1) y = random.randint(0,n-1) while x==y: y = random.randint(0,n-1) if x&gt;y: if l[x]&lt;l[y]: (l[x],l[y])=(l[y],l[x]) if x&lt;y: if l[x]&gt;l[y]: (l[x],l[y])=(l[y],l[x]) for i in range(0,n-1): if l[i]&gt;l[i+1]: break else: not_sorted = False for i in range(n): print(l[i]) output should be like this::: 1 2 3 4 5 and not like this :::: [1,2,3,4,5]
score: 10
has comment: http://stackoverflow.com/comment/91144830

http://stackoverflow.com/a/51981559
accepted answer of: http://stackoverflow.com/q/51981090
answers question: http://stackoverflow.com/q/51981090
type: Answer
downvote count: 0
score: 1
upvote count: 1
type: AcceptedAnswer
has body: Using dataframes for "everything" is often not the best solution. Code can become unreadable, and constructing many small dataframes can also be very slow. My solution uses plain Python containers to solve your issue: import pandas as pd wishlist_result = [ {"userId": 19814, "entityIds": [40, 45, 54, 322]}, {"userId": 19814, "entityIds": [12, 22]}, ] def flatten(data): flattened = [] for entry in data: user_id = entry["userId"] entity_ids = entry["entityIds"] for entity_id in entity_ids: row = dict(user_id=user_id, entity_id=entity_id) flattened.append(row) return flattened rows = flatten(wishlist_result) df = pd.DataFrame(rows, columns=["user_id", "entity_id"]) print(df) outputs user_id entity_id 0 19814 40 1 19814 45 2 19814 54 3 19814 322 4 19814 12 5 19814 22 I benchmarked my approach with a list of length 60000 duplicating your wishlist_result examples. Runtime of the snippet is ~800 ms on my old Mac. In case you want it shorter, a nested list comprehension also works, runtime does not change significantly: rows = [ {"user_id": entry["userId"], "entity_id": entity_id} for entry in wishlist_result for entity_id in entry["entityIds"] ] I often avoid list comprehensions with nested for loops, as team mates who want to read or reuse my code might not know the order of execution. But here the order is quite clear by the variables involved.

http://stackoverflow.com/a/61777470
downvote count: 0
has body: I use this to see if tunnel is open: server.skip_tunnel_checkup = False server.start() server.check_tunnels() print(server.tunnel_is_up, flush=True) And in the log you will see : {('0.0.0.0', 44004): True} # this tunnel is up {('0.0.0.0', 44004): False} # this tunnel is not up
answers question: http://stackoverflow.com/q/52070456
upvote count: 2
type: Answer
score: 2

http://stackoverflow.com/q/52096704
has body: The UWSGI is connected to the flask app per UNIX-Socket: NGINX (LISTEN TO PORT 80) <-> UWSGI (LISTER PER UNIX-SOCKER) <-> FLASK-APP I have initalized a uwsgi cache to handle global data. I want to handle the cache with python package flask-caching. I am trying to init the Cache-instance with the correct cache address. There seems to be something wrong. I think, that the parameters for app.run() are not relevant for uwsgi. If I am setting a cache entry, it return always None: app.route("/") def test(): cache.set("test", "OK", timeout=0) a = cache.get("test") return a main.py from flask import Flask from flask_caching import Cache app = Flask(__name__) # Check Configuring Flask-Caching section for more details cache = Cache(app, config={'CACHE_TYPE': 'uwsgi', 'CACHE_UWSGI_NAME':'mycache@localhost'}) if __name__ == "__main__": app.run(host="0.0.0.0", port=5000) uwsgi.ini [uwsgi] module = main callable = app cache2 = name=mycache,items=100 nginx.conf server { listen 80; location / { try_files $uri @app; } location @app { include uwsgi_params; uwsgi_pass unix:///tmp/uwsgi.sock; } location /static { alias /app/testapp/static; } } I am working with the docker build from https://github.com/tiangolo/uwsgi-nginx-flask-docker. The app is working, expect the cache.
type: Question
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/101794947
has answer: http://stackoverflow.com/a/74666973
tagged with: nginx
score: 7
tagged with: uwsgi
has comment: http://stackoverflow.com/comment/122047770
tagged with: flask-caching
downvote count: 0
answer count: 1
favorite count: 0
accepted answer: http://stackoverflow.com/a/74666973
tagged with: flask-cache
tagged with: python
has comment: http://stackoverflow.com/comment/122211740
has title: Flask-Caching use UWSGI cache with NGINX
upvote count: 7

http://stackoverflow.com/comment/90971419
has text: also we are already using Jenkins
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/52010060
type: Comment

http://stackoverflow.com/comment/91062669
comment on: http://stackoverflow.com/q/52055264
type: Comment
has text: @Msquare good point. You could try: `df.isna().idxmax() * np.where(df.isna().any(), 1, np.nan)` 0 should now mean NaN at index 0 - NaN means no NaN values
score: 0
type: QuestionComment

http://stackoverflow.com/q/52075263
has answer: http://stackoverflow.com/a/66066773
type: Question
upvote count: 2
downvote count: 1
has answer: http://stackoverflow.com/a/52075485
has body: list1=['Usha', 'Das', 'Anas', 'Chand', 'Tokyo', 'Milkha Singh', 'Gurbachan Singh Randhawa', 'PT Usha', 'KM Beenamol', 'Hima Das', 'under-20', 'Muhammed Anas', 'Dutee Chand', 'the Asian Games', 'Asian Games', 'Olympic Games'] From the above list you can see that Das and Hima Das are repeating.I want only full names that is Hima Das. Similarly with Usha and PT Usha. o/p what I need ['Tokyo', 'Milkha Singh', 'Gurbachan Singh Randhawa', 'PT Usha', 'KM Beenamol', 'Hima Das', 'under-20', 'Muhammed Anas', 'Dutee Chand', 'Asian Games', 'Olympic Games']
favorite count: 0
has answer: http://stackoverflow.com/a/52075426
has answer: http://stackoverflow.com/a/52075427
has title: How to remove similar words from a list of words?
answer count: 5
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/52075303
tagged with: list
score: 1
tagged with: duplicates

http://stackoverflow.com/comment/102192892
type: AnswerComment
score: 0
has text: Is it possible to find a string contains strike for a single word?
type: Comment
comment on: http://stackoverflow.com/a/52112925

http://stackoverflow.com/comment/91066086
type: Comment
comment on: http://stackoverflow.com/q/52056772
score: 0
type: QuestionComment
has text: @IljaEverilä you're definitely right, fixing to use primary and secondary joins indeed gives the proper behavior! Cheers :)

http://stackoverflow.com/a/64698263
answers question: http://stackoverflow.com/q/52068066
upvote count: 36
downvote count: 0
score: 36
type: Answer
has comment: http://stackoverflow.com/comment/114807775
has body: Same as other answer, but with a short snippet with a simple while loop. response = client.list_accounts() results = response["Accounts"] while "NextToken" in response: response = client.list_accounts(NextToken=response["NextToken"]) results.extend(response["Accounts"])

http://stackoverflow.com/a/52110433
has comment: http://stackoverflow.com/comment/91224687
has comment: http://stackoverflow.com/comment/91220733
score: 4
has comment: http://stackoverflow.com/comment/91221470
has comment: http://stackoverflow.com/comment/91194339
has comment: http://stackoverflow.com/comment/91258703
answers question: http://stackoverflow.com/q/52104679
has comment: http://stackoverflow.com/comment/91222648
has comment: http://stackoverflow.com/comment/91200622
has comment: http://stackoverflow.com/comment/91194071
has comment: http://stackoverflow.com/comment/91233683
has comment: http://stackoverflow.com/comment/91187960
has body: try this in you /app/wsgi.py module, import os from raven.contrib.django.raven_compat.middleware.wsgi import Sentry from django.core.wsgi import get_wsgi_application from django.utils.deprecation import MiddlewareMixin class CustomSentry(MiddlewareMixin, Sentry): pass os.environ.setdefault("DJANGO_SETTINGS_MODULE", "settings") application = CustomSentry(get_wsgi_application()) References 1. object() takes no parameters in django 1.10 2. Django exception middleware: TypeError: object() takes no parameters
type: Answer
upvote count: 4
has comment: http://stackoverflow.com/comment/91230585
has comment: http://stackoverflow.com/comment/91221392
has comment: http://stackoverflow.com/comment/91193930
downvote count: 0

http://stackoverflow.com/q/52004133
tagged with: python
score: 21
tagged with: ocr
favorite count: 0
upvote count: 25
has comment: http://stackoverflow.com/comment/90958359
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90958195
has answer: http://stackoverflow.com/a/52006700
type: Question
has body: I am making an OCR which reads ID cards. After getting region of interest by using YOLO, I am giving that cropped region to Tesseract to read it. As those cropped images are very small and blurry, Tesseract is unable to read them. When it can read them, it gives wrong predictions. I think that by improving image quality of cropped images, these problems can be solved. One of the cropped images: My question is, how would I go about improving such images?
tagged with: image-processing
tagged with: image
answer count: 2
downvote count: 4
has answer: http://stackoverflow.com/a/52004655
has title: How to improve image quality?

http://stackoverflow.com/comment/90933146
score: 1
comment on: http://stackoverflow.com/q/51991414
has text: If you're using Python 3.x, inside `Planet`'s `def __init__(pos,radius,mass,velocity,make_trail):` method definition it would look something like `super().__init__(pos=pos, radius=radius, make_trail=make_trail)`. You'll need to manually save or otherwise deal with the other arguments the method receives (probably following) that call. For example, `self.mass = mass`.
type: Comment
type: QuestionComment

http://stackoverflow.com/a/52107641
answers question: http://stackoverflow.com/q/52107617
type: Answer
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/91166079
has body: You can do with np.where df['NC']=np.where(df.color=='green','Green',df.Type) df Out[1234]: Set Type color NC 0 Z A green Green 1 Z B green Green 2 X B red B 3 Y C red C
downvote count: 0

http://stackoverflow.com/comment/90917674
type: Comment
type: QuestionComment
score: 0
has text: Your output is what is expected. After upgrading numpy from 1.15.0 to 1.15.1 it worked on my machine also.
comment on: http://stackoverflow.com/q/51983258

http://stackoverflow.com/q/52029253
linked to: http://stackoverflow.com/q/27947414
has comment: http://stackoverflow.com/comment/91009305
has comment: http://stackoverflow.com/comment/91009369
downvote count: 1
accepted answer: http://stackoverflow.com/a/52031621
has comment: http://stackoverflow.com/comment/91009960
type: Question
has comment: http://stackoverflow.com/comment/91010501
tagged with: nltk
upvote count: 0
has comment: http://stackoverflow.com/comment/91010190
has comment: http://stackoverflow.com/comment/91008845
score: -1
has body: I am using PyCharm and Anaconda. I have installed NTLK with sudo pip install -U nltk and even to make sure since I'm on Mac OS and I saw this previous SO post to also try pip3 install nltk. However, no matter where I try (PyCharm's terminal, Pycharm's Python, or my own terminal), I cannot get import ntlk to work and always get ModuleNotFoundError: No module named 'ntlk'. The weird thing is that I actually manage to run some code with a simple "Python test.py" that contains: from nltk.tag import StanfordPOSTagger but whenever I try to import ntlk to be able to then nltk.download('punkt') I get the No module named 'ntlk' error. Would you know where that is coming from? Edit: output of python -V: Python 3.7.0 python3 -V: Python 3.7.0 pip -V: pip 18.0 from /Users/.../lib/python3.7/site-packages/pip (python 3.7) pip3 -V: pip 18.0 from /Users/.../lib/python3.7/site-packages/pip (python 3.7) As for python3 -c "import ntlk; print('ntlk available')" it returns: Traceback (most recent call last): File "&lt;string&gt;", line 1, in &lt;module&gt; ModuleNotFoundError: No module named 'ntlk' Edit 2: Output of python -c "import os, sys; print(os.linesep.join(sys.path))" /Users/.../anaconda3/envs/.../lib/python37.zip /Users/.../anaconda3/envs/.../lib/python3.7 /Users/.../anaconda3/envs/.../lib/python3.7/lib-dynload /Users/.../anaconda3/envs/.../lib/python3.7/site-packages
has comment: http://stackoverflow.com/comment/91009685
has comment: http://stackoverflow.com/comment/91011568
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/91009858
has answer: http://stackoverflow.com/a/52031621
has comment: http://stackoverflow.com/comment/91009152
has comment: http://stackoverflow.com/comment/91009909
has comment: http://stackoverflow.com/comment/91009834
tagged with: pip
has title: ModuleNotFoundError: No module named 'ntlk'
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91008793
tagged with: anaconda
has comment: http://stackoverflow.com/comment/91009532

http://stackoverflow.com/q/52081776
answer count: 1
score: 0
tagged with: importerror
tagged with: ethereum
has comment: http://stackoverflow.com/comment/91192429
has answer: http://stackoverflow.com/a/52081824
has comment: http://stackoverflow.com/comment/91113949
type: UnansweredQuestion
tagged with: django
tagged with: python
has title: ImportError: No module named web3 in Django
has body: I'm trying to set up a wallet on Django, but I keep getting this error: ImportError: No module named web3 this is how I call it: from web3 import Web3 (also tried import web3)
has comment: http://stackoverflow.com/comment/91114141
tagged with: web3py
type: Question

http://stackoverflow.com/a/51981124
type: Answer
has comment: http://stackoverflow.com/comment/90922632
score: 2
downvote count: 0
upvote count: 2
has body: Just a list of things to try: install Python from https://www.python.org/downloads/release/python-2715/. Remember the location of the python binary. Set that as CLOUDSDK_PYTHON Show the printout with the variable set. Ensure that the variable is really set. In C:\ (or C:\AndroidSdk, but optimally C:\): Run the gci command in https://superuser.com/questions/237533/find-files-with-non-ascii-characters-in-filenames-in-windows-xp, show the output. Or run the python program from that same question. would be found by 4., but the 13th character seems to be the \. Try to re-create the directory, giving the AndroidSDK a shorter/longer name, see if it still is the 13th character
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/51956657
answers question: http://stackoverflow.com/q/51956657
has comment: http://stackoverflow.com/comment/90916820

http://stackoverflow.com/q/52000490
answer count: 1
downvote count: 0
linked to: http://stackoverflow.com/q/1636136
favorite count: 0
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/90950098
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/90950203
has comment: http://stackoverflow.com/comment/90976579
type: Question
has body: How can i change to root user providing my password in the script? I have this code import os # change to root user # changing to root call this function # example os.sytem('reboot') PS. not only this function but iptables too, so i need to change to root with out typing the password because i want to be automated.
has title: Change to root user in python
has comment: http://stackoverflow.com/comment/90950262
linked to: http://stackoverflow.com/q/5191878
has answer: http://stackoverflow.com/a/52000677

http://stackoverflow.com/comment/90884815
type: Comment
has text: @GhostCat Thank you:)
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/51963174

django-models
tag name: django-models
tags question: http://stackoverflow.com/q/52101717
tags question: http://stackoverflow.com/q/52054246
tags question: http://stackoverflow.com/q/52108303
tags question: http://stackoverflow.com/q/52031799
tags question: http://stackoverflow.com/q/52021136
tags question: http://stackoverflow.com/q/52102284
tags question: http://stackoverflow.com/q/52054905
tags question: http://stackoverflow.com/q/51967671
tags question: http://stackoverflow.com/q/52014056
tags question: http://stackoverflow.com/q/52051802
tags question: http://stackoverflow.com/q/51978965
tags question: http://stackoverflow.com/q/51958718
tags question: http://stackoverflow.com/q/52095333
tags question: http://stackoverflow.com/q/52106750
tags question: http://stackoverflow.com/q/52009318
tags question: http://stackoverflow.com/q/52026815
tags question: http://stackoverflow.com/q/51989857
tags question: http://stackoverflow.com/q/52044222
tags question: http://stackoverflow.com/q/51962003
tags question: http://stackoverflow.com/q/52083931
tags question: http://stackoverflow.com/q/52050605
type: Tag
tags question: http://stackoverflow.com/q/52017758
tags question: http://stackoverflow.com/q/51985722
tags question: http://stackoverflow.com/q/52101896
tags question: http://stackoverflow.com/q/51959209
tags question: http://stackoverflow.com/q/52062206
tags question: http://stackoverflow.com/q/52053538
tags question: http://stackoverflow.com/q/51960796
tags question: http://stackoverflow.com/q/51976534
tags question: http://stackoverflow.com/q/51984689
tags question: http://stackoverflow.com/q/51988218
tags question: http://stackoverflow.com/q/52070462
tags question: http://stackoverflow.com/q/51978195
tags question: http://stackoverflow.com/q/52074398
tags question: http://stackoverflow.com/q/51990546
tags question: http://stackoverflow.com/q/52034812
tags question: http://stackoverflow.com/q/52097741
tags question: http://stackoverflow.com/q/52054446

http://stackoverflow.com/q/51967471
tagged with: python
score: -1
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51971731
has body: I have looked many places for how to set the usage property in jenkins using python. I looked at the create_node but there is no parameter for the usage or that I have found. I also looked at reconfig_node but looking at the current xml I didn't see a usage field in the xml to be updated for usage. So not sure how to update or create nodes where I can set the usage property. I know how to set this manually but I currently have a python script to create the node but the usage is always set to 'Use this node as much as possible'. So I'm looking for a way to set the usage for a node when creating a node or just update after it is created.
has title: Jenkins node property 'usage' and how to update with python
tagged with: jenkins-plugins
downvote count: 1
type: Question
upvote count: 0
accepted answer: http://stackoverflow.com/a/51971731
answer count: 1
favorite count: 0
tagged with: jenkins

http://stackoverflow.com/comment/90971052
type: QuestionComment
comment on: http://stackoverflow.com/q/52009769
score: 0
has text: I recently used freeze to compile my python app and give it to my coworker. This worked great so maybe give freeze a shot.
type: Comment

http://stackoverflow.com/a/52029001
type: Answer
upvote count: 1
answers question: http://stackoverflow.com/q/52028933
has body: If you want to convert a string to a hex representation of its bits, that's not what int(s, 16) does. int(s, 16) tries to treat the characters of s as the base-16 representation of an integer. 'deadbeef' contains only characters that are valid digits in base 16: d = 13 e = 14 a = 10 d = 13 b = 11 e = 14 e = 14 f = 15 deadbeef = 13*16**7 + 14*16**6 + 10*16**5 + 13*16**4 + 11*16**3 + 14*16**2 + 14*16**1 + 15 = 3735928559 None of your other strings have that property. If you want hex digits corresponding to the bits representing a string, first, choose an encoding (UTF8, probably), then use something like binascii.hexlify: &gt;&gt;&gt; import binascii &gt;&gt;&gt; binascii.hexlify('hello world'.encode('utf8')) b'68656c6c6f20776f726c64'
score: 1
downvote count: 0

http://stackoverflow.com/q/51992644
has answer: http://stackoverflow.com/a/51992679
tagged with: multiprocessing
type: Question
type: AnsweredQuestion
has body: This Python 2.7 script running on Windows is not outputting as I would expect it to. from multiprocessing import Pool from multiprocessing.dummy import Pool as ThreadPool def function1(): function1List = ["11" ,'22' , '33'] return function1List def function2(passedList): for item in passedList: print item list = function1() #print list used to verify list if __name__ == '__main__': pool = ThreadPool() pool.map(function2, list) pool.close() pool.join() What I expect 11 22 33 44 What I am actually getting 1 1 2 2 3 3 4 4 What am I missing?
tagged with: threadpool
accepted answer: http://stackoverflow.com/a/51992679
has title: Passing list to pool.map() function in Python returns each character for each item in the list
tagged with: pool
answer count: 1
score: 0
tagged with: python

http://stackoverflow.com/comment/91099906
score: 0
type: AnswerComment
type: Comment
has text: I have deal with that using simple_tag (as you can see in my answer). But thank you for help. :)
comment on: http://stackoverflow.com/a/52048467

http://stackoverflow.com/comment/90979520
type: QuestionComment
has text: @learning_python oh ohk will edit the answer
comment on: http://stackoverflow.com/q/52012798
score: 0
type: Comment

http://stackoverflow.com/q/52033620
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91017654
has title: Python function that accepts a path to an input file
has comment: http://stackoverflow.com/comment/91017692
tagged with: python
has body: I'm trying to write a python function that accepts a path to an input file (just a single file and not a directory) and returns a Hamiltonian matrix. I already have a script that creates the matrix, but i'm a bit unsure how to write the function. I'm running pycharm and python 2.7 Should I go with: f = open('myFile.xyz', 'r') obj.writeTo(f) f.close() or something like def your_function_filename(path): with open(path, 'r') as f: return your_function_filename(f) I'm trying to go with something that has the easiest user interface. EDIT: For example - I have a text.txt file with the following two lines: x=3 y=4 I also have a python script saying: print (x+y) print (x-y) Instead of defining x and y in the python script I was to have another python script that says put text.txt through the python script and output the result in another python script.
answer count: 0
type: Question
tagged with: function
score: 0
has comment: http://stackoverflow.com/comment/91018121
has comment: http://stackoverflow.com/comment/91020536

http://stackoverflow.com/a/52021725
has comment: http://stackoverflow.com/comment/91005400
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/90994087
answers question: http://stackoverflow.com/q/52017596
has comment: http://stackoverflow.com/comment/91029803
has comment: http://stackoverflow.com/comment/91014462
has comment: http://stackoverflow.com/comment/91036146
has comment: http://stackoverflow.com/comment/91032127
has comment: http://stackoverflow.com/comment/91019054
has comment: http://stackoverflow.com/comment/91026081
has comment: http://stackoverflow.com/comment/90995670
upvote count: 1
has comment: http://stackoverflow.com/comment/91032600
has body: Load all sounds and append them to a list. attack_sounds = [] for sound_file in glob.glob("attack/*.wav"): attack_sounds.append(pygame.mixer.Sound(sound_file)) Then call random.choice with this list as the argument to pick a random sound out of the list and play it. if GPIO.input(4): random_sound = random.choice(attack_sounds) random_sound.play()
has comment: http://stackoverflow.com/comment/90994205
has comment: http://stackoverflow.com/comment/91032969
has comment: http://stackoverflow.com/comment/91026177
type: Answer
has comment: http://stackoverflow.com/comment/91019404

http://stackoverflow.com/a/51969415
score: 0
answers question: http://stackoverflow.com/q/51969361
type: Answer
has body: Your code has broken indentation. The try: for example needs to be indented Otherwise the scope of the function will end and return later will seem to be outside a function. def move () : while True: print player = raw_imput ("Pierre = 1 \nPapier = 2\nCiseaux = 3\nQuel est ton choix?: ") try: #^ This try here is on the same level as "def". This means that it is _outside_ the function.

pyqt
type: Tag
tags question: http://stackoverflow.com/q/51961472
tags question: http://stackoverflow.com/q/51976683
tags question: http://stackoverflow.com/q/52076299
tags question: http://stackoverflow.com/q/52004267
tags question: http://stackoverflow.com/q/52029649
tags question: http://stackoverflow.com/q/52046551
tags question: http://stackoverflow.com/q/51989785
tags question: http://stackoverflow.com/q/52085223
tags question: http://stackoverflow.com/q/52112402
tags question: http://stackoverflow.com/q/52102138
tags question: http://stackoverflow.com/q/51997428
tags question: http://stackoverflow.com/q/52026191
tags question: http://stackoverflow.com/q/51969763
tags question: http://stackoverflow.com/q/52035966
tags question: http://stackoverflow.com/q/52038724
tags question: http://stackoverflow.com/q/52106515
tags question: http://stackoverflow.com/q/52100089
tags question: http://stackoverflow.com/q/52109130
tags question: http://stackoverflow.com/q/51989523
tags question: http://stackoverflow.com/q/51962262
tags question: http://stackoverflow.com/q/52087527
tags question: http://stackoverflow.com/q/52073747
tags question: http://stackoverflow.com/q/52100621
tags question: http://stackoverflow.com/q/52084758
tags question: http://stackoverflow.com/q/51960617
tags question: http://stackoverflow.com/q/52111372
tags question: http://stackoverflow.com/q/52102318
tags question: http://stackoverflow.com/q/52098156
tags question: http://stackoverflow.com/q/51961742
tags question: http://stackoverflow.com/q/52071203
tags question: http://stackoverflow.com/q/52066040
tags question: http://stackoverflow.com/q/52010524
tags question: http://stackoverflow.com/q/52049644
tags question: http://stackoverflow.com/q/52044772
tags question: http://stackoverflow.com/q/52109153
tags question: http://stackoverflow.com/q/52087437
tags question: http://stackoverflow.com/q/52046091
tags question: http://stackoverflow.com/q/52015269
tags question: http://stackoverflow.com/q/52108256
tags question: http://stackoverflow.com/q/51993679
tags question: http://stackoverflow.com/q/52043492
tags question: http://stackoverflow.com/q/51989969
tags question: http://stackoverflow.com/q/52089202
tags question: http://stackoverflow.com/q/52036021
tags question: http://stackoverflow.com/q/51975678
tags question: http://stackoverflow.com/q/52040205
tag name: pyqt
tags question: http://stackoverflow.com/q/52004018
tags question: http://stackoverflow.com/q/52040538
tags question: http://stackoverflow.com/q/52031590
tags question: http://stackoverflow.com/q/52020988
tags question: http://stackoverflow.com/q/51989918
tags question: http://stackoverflow.com/q/51981546

http://stackoverflow.com/a/52001249
upvote count: 3
has comment: http://stackoverflow.com/comment/90952478
has comment: http://stackoverflow.com/comment/90952634
accepted answer of: http://stackoverflow.com/q/52000950
has comment: http://stackoverflow.com/comment/90953954
has comment: http://stackoverflow.com/comment/90953714
has comment: http://stackoverflow.com/comment/120905533
answers question: http://stackoverflow.com/q/52000950
has comment: http://stackoverflow.com/comment/90952302
has comment: http://stackoverflow.com/comment/90954100
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/90953251
score: 3
type: Answer
has comment: http://stackoverflow.com/comment/90952852
has body: For example: import wget import os import multiprocessing def run_process(url, output_path): wget.download(url, out=output_path) # TODO: you can write your rename logic at here using os.rename if __name__ == '__main__': cpus = multiprocessing.cpu_count() max_pool_size = 4 pool = multiprocessing.Pool(cpus if cpus &lt; max_pool_size else max_pool_size) base_dir = os.path.dirname(os.path.abspath(__file__)) target = "NEWCODE" prefix_list = ["NWZV1WB", "AWU3JAD", "NW96MRD"] download_list = [] name_list = list(range(1, 23)) name_list.extend(["zoom_side", "zoom_sole", "zoom_side-thumb"]) for prefix in prefix_list: path = os.path.join(base_dir, prefix) if not os.path.exists(path): os.mkdir(path) if not os.path.isdir(path): exit() for name in name_list: download_list.append(['https://img2.tennis-warehouse.com/360/{p}/{n}.jpg'.format(n=name, p=prefix), path]) for url, path in download_list: # change here to download other files print('Beginning file download with wget module {n}'.format(n=url)) pool.apply_async(run_process, args=(url, path, )) # add your code here to download other files pool.close() pool.join() print("finish")

http://stackoverflow.com/q/52045513
has comment: http://stackoverflow.com/comment/91042236
tagged with: python
downvote count: 1
has title: Minimum vertical slice sum
tagged with: algorithm
has answer: http://stackoverflow.com/a/52046559
answer count: 5
upvote count: 4
has answer: http://stackoverflow.com/a/52047312
type: UnansweredQuestion
favorite count: 0
has comment: http://stackoverflow.com/comment/91049925
has answer: http://stackoverflow.com/a/65930343
has answer: http://stackoverflow.com/a/52063317
has answer: http://stackoverflow.com/a/54634656
type: Question
score: 3
has body: I want to input a matrix size N x N and cut a slice such that each element is directly below, left-below or right-below the one above it. And cost is the sum of all elements in the slice. How do I write a program to do this? Eg. matrix is given as list of list [[1,2,3], [4,5,6], [7,8,9]] which has the following slices: (1,4,7), (1,4,8), (1,5,7), (1,5,8), (1,5,9), (2,4,7), (2,4,8), (2,5,7), (2,5,8), (2,5,9), (2,6,8), (2,6,9), (3,5,7), (3,5,8), (3,5,9), (3,6,8), (3,6,9) Then slice of lowest weight is (1,4,7) which has sum 12.

http://stackoverflow.com/comment/91111977
comment on: http://stackoverflow.com/q/52080436
score: 0
type: Comment
type: QuestionComment
has text: Why not use py2exe, or nuitka, or similar to automatically bundle it all (your application and the appropriate version of python) into a single app / bundle?

http://stackoverflow.com/q/52052553
score: 1
favorite count: 0
has answer: http://stackoverflow.com/a/52052690
type: Question
has body: I have the following code in a Django 2 project print(List.objects.filter(user=self.request.user).query) which prints the SQL query which is constructed but the following print(List.objects.filter(user=self.request.user).count().query) throws error print(List.objects.filter(user=self.request.user).count().query) AttributeError: 'int' object has no attribute 'query' I know why it happens, because count() immediately return the count. How do I see the query which it constructed
tagged with: django
upvote count: 1
tagged with: python
answer count: 1
has title: How to see the underlying query which includes count() in it, in django
accepted answer: http://stackoverflow.com/a/52052690
downvote count: 0
type: AnsweredQuestion

http://stackoverflow.com/comment/90899323
type: QuestionComment
has text: b'\xff\x00\xff\xff\xff\' is a syntax error: one backslash too many in the end
comment on: http://stackoverflow.com/q/51974380
score: 0
type: Comment

http://stackoverflow.com/comment/90978236
type: AnswerComment
has text: Thank you! I guess in some cases I have some optional parameters, so use `sys` can be more helpful
comment on: http://stackoverflow.com/a/52009662
type: Comment
score: 0

http://stackoverflow.com/comment/91074233
comment on: http://stackoverflow.com/a/52061367
score: 0
type: AnswerComment
has text: oh I didn't know about the parentheses so just to avoid mistake I used to put all the time :S tks for the tips ;)
type: Comment

http://stackoverflow.com/comment/90961219
comment on: http://stackoverflow.com/q/52005653
has text: Where is `myinnerclassID` coming from?
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/90899755
has text: Yes it is possible.
comment on: http://stackoverflow.com/q/51974595
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51979396
type: Question
upvote count: 2
tagged with: pandas
answer count: 1
has title: Count common columns values between data frames (Python)
has body: I have multiple tables as below. There are 10 df tables with rows ranging from 1000-25,000 rows. These df tables are produced after clustering them. Thus, the difference in number of rows. df = pd.DataFrame({'id': [1,2,3,4,5], 'segments' : ["a,b,c", "c,a", "d,a,b", "e,g", "a,e,d"]}) ref = pd.DataFrame({'id': [1,4], 'segments' : ["a,b,c", "e,g"]}) | id | segments | +----+----+----------+ | 0 | 1 | a,b,c | | 1 | 2 | c,a | | 2 | 3 | d,a,b | | 3 | 4 | e,g | | 4 | 5 | a,e,d | +----+----+----------+ ....total 1500-25,000 rows (10 df tables) | id | segments | +----+----+----------+ | 0 | 1 | a,b,c | | 1 | 4 | e,g | +----+----+----------+.....total 1216 rows My aim is to determine if the ref ID exists in each df table. If yes, I need to check each rows of each df table and count how many segments are the same. My final output will be as followed. | id | segments |ref_1 | ref_2 +----+----+----------+-------+-----+ | 0 | 1 | a,b,c | 3 | 0 | | 1 | 2 | c,a | 2 | 0 | | 2 | 3 | d,a,b | 2 | 0 | | 3 | 4 | e,g | 0 | 2 | | 4 | 5 | a,e,d | 1 | 1 | +----+----+----------+-------+-----+ So far, I've determined how to check if the ref ID is present # get the ref id present in df for index, row in enumerate(df.id): for index2, row2 in enumerate(ref.id): if row == row2: print("ref id present") print(row,index) else: "no ref id" I have tried to use the intersection function. But I got output 0. len(set(df['segments']).intersection(set(ref['segments']))) I did my research but most of the solution involves single column values where it is solved using merge. However, mine has multiple values in 1 column. I'm stuck for 2 days on how to check and count the common values and to put it all in a loop to perform on 10 df tables.
accepted answer: http://stackoverflow.com/a/51979734
favorite count: 0
has comment: http://stackoverflow.com/comment/90909099
tagged with: python
has answer: http://stackoverflow.com/a/51979734
score: 2
type: AnsweredQuestion
downvote count: 0
has comment: http://stackoverflow.com/comment/90908899

python
tags question: http://stackoverflow.com/q/52017598
tags question: http://stackoverflow.com/q/51978080
tags question: http://stackoverflow.com/q/52079399
tags question: http://stackoverflow.com/q/52044772
tags question: http://stackoverflow.com/q/52073395
tags question: http://stackoverflow.com/q/52040392
tags question: http://stackoverflow.com/q/51985455
tags question: http://stackoverflow.com/q/52090045
tags question: http://stackoverflow.com/q/51966541
tags question: http://stackoverflow.com/q/52057486
tags question: http://stackoverflow.com/q/52108946
tags question: http://stackoverflow.com/q/52000882
tags question: http://stackoverflow.com/q/52043378
tags question: http://stackoverflow.com/q/52053685
tags question: http://stackoverflow.com/q/52018812
tags question: http://stackoverflow.com/q/52008593
tags question: http://stackoverflow.com/q/51970251
tags question: http://stackoverflow.com/q/52096279
tags question: http://stackoverflow.com/q/52052553
tags question: http://stackoverflow.com/q/52003978
tags question: http://stackoverflow.com/q/52055062
tags question: http://stackoverflow.com/q/51972853
tags question: http://stackoverflow.com/q/51989384
tags question: http://stackoverflow.com/q/52076168
tags question: http://stackoverflow.com/q/52074398
tags question: http://stackoverflow.com/q/51991164
tags question: http://stackoverflow.com/q/51967450
tags question: http://stackoverflow.com/q/51996545
tags question: http://stackoverflow.com/q/52019658
tags question: http://stackoverflow.com/q/51995926
tags question: http://stackoverflow.com/q/52100801
tags question: http://stackoverflow.com/q/52064324
tags question: http://stackoverflow.com/q/52007065
tags question: http://stackoverflow.com/q/52025871
tags question: http://stackoverflow.com/q/52029918
tags question: http://stackoverflow.com/q/52002357
tags question: http://stackoverflow.com/q/52028942
tags question: http://stackoverflow.com/q/52023758
tags question: http://stackoverflow.com/q/52107808
tags question: http://stackoverflow.com/q/52046307
tags question: http://stackoverflow.com/q/51962106
tags question: http://stackoverflow.com/q/52105332
tags question: http://stackoverflow.com/q/52025597
tags question: http://stackoverflow.com/q/52075814
tags question: http://stackoverflow.com/q/52006745
tags question: http://stackoverflow.com/q/51979903
tags question: http://stackoverflow.com/q/52099920
tags question: http://stackoverflow.com/q/52000077
tags question: http://stackoverflow.com/q/52052192
tags question: http://stackoverflow.com/q/51987744
tags question: http://stackoverflow.com/q/52000103
tags question: http://stackoverflow.com/q/52010786
tags question: http://stackoverflow.com/q/51957188
tags question: http://stackoverflow.com/q/52027715
tags question: http://stackoverflow.com/q/52032908
tags question: http://stackoverflow.com/q/52079185
tags question: http://stackoverflow.com/q/52091336
tags question: http://stackoverflow.com/q/52044633
tags question: http://stackoverflow.com/q/51984056
tags question: http://stackoverflow.com/q/52067450
tags question: http://stackoverflow.com/q/51997982
tags question: http://stackoverflow.com/q/52040290
tags question: http://stackoverflow.com/q/52109130
tags question: http://stackoverflow.com/q/51958574
tags question: http://stackoverflow.com/q/52068188
tags question: http://stackoverflow.com/q/51973034
tags question: http://stackoverflow.com/q/52052834
tags question: http://stackoverflow.com/q/52029531
tags question: http://stackoverflow.com/q/52082538
tags question: http://stackoverflow.com/q/52069144
tags question: http://stackoverflow.com/q/52043323
tags question: http://stackoverflow.com/q/52061933
tags question: http://stackoverflow.com/q/52017169
tags question: http://stackoverflow.com/q/52038410
tags question: http://stackoverflow.com/q/52087391
tags question: http://stackoverflow.com/q/52048562
tags question: http://stackoverflow.com/q/51997022
tags question: http://stackoverflow.com/q/51961477
tags question: http://stackoverflow.com/q/52049009
tags question: http://stackoverflow.com/q/52016690

http://stackoverflow.com/comment/91030991
score: 0
has text: @Kevin Appreciate your help ! I think you're pretty close to solve my puzzle ! Question is where `for old, new in zip(prefix_list, folder_name_list): os.rename(old, new)` would go into my code ? Does it matter the location ?
comment on: http://stackoverflow.com/q/52035338
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51985921
type: Question
accepted answer: http://stackoverflow.com/a/51986006
linked to: http://stackoverflow.com/q/2318529
has title: Triangular heatmap from 3-column dataframe
tagged with: pandas
has answer: http://stackoverflow.com/a/51986006
upvote count: 1
answer count: 1
favorite count: 0
has body: I have a dataframe with two categorical columns and a third with integers: import pandas as pd df1 = pd.DataFrame({ 'First': ['A','A','A','B','B','C'], 'Second': ['B','C','D','C','D','D'], 'Value': [1,2,3,4,5,6]} ) df1 First Second Value 0 A B 1 1 A C 2 2 A D 3 3 B D 4 4 B D 5 5 C D 6 I would like to get the corresponding triangular matrix, as (missing values can be NAs): A B C D 1 2 3 A 4 5 B 6 C and finally, plot it in a triangular heatmap, which I believe I could be able to do with the help of this question, which, however, requires a numpy masked array as input. Other solutions to plot this without using numpy are also very welcome. Any pythonic ideas of how to achieve this? EDIT: I realized the example I gave was too neat. My columns are not organized in the way they are above. So I have something like this: df1 = pd.DataFrame({ 'First': ['D','C','B','A','C','A','B','D','B','C'], 'Second': ['E','E','C','D','D','E','E','B','A','A'], 'Value': [1,2,3,4,5,6,7,8,9,10]} ) First Second Value 0 D E 1 1 C E 2 2 B C 3 3 A D 4 4 C D 5 5 A E 6 6 B E 7 7 D B 8 8 B A 9 9 C A 10 and df1.pivot('First','Second','Value') produces Second A B C D E First A NaN NaN NaN 4.0 6.0 B 9.0 NaN 3.0 NaN 7.0 C 10.0 NaN NaN 5.0 2.0 D NaN 8.0 NaN NaN 1.0 A non-triangular, non-simmetrical matrix. I need to have the same number of rows and columns and to push all these NaNs to the edges to create a triangle. Pivot doesn't seem to be a possible solution EDIT2 The solution and desired output exists and is: A B C D E A NaN 9 10 4 6 B NaN NaN 3 8 7 C NaN NaN NaN 5 2 D NaN NaN NaN NaN 1 E NaN NaN NaN NaN NaN
tagged with: python
tagged with: triangular
tagged with: heatmap
type: AnsweredQuestion
downvote count: 0
score: 1
tagged with: matplotlib

http://stackoverflow.com/q/52054322
has body: Can someone tell me what's wrong with this code? It's based off an old project, I'm trying to implement multiple URLs rather than just one. #!/usr/bin/env python from bs4 import BeautifulSoup from urllib2 import urlopen from datetime import datetime import csv import sys import os import smtplib import config # Craigslist search URL SEARCH_URL = ['http://auburn.craigslist.org/search/sss?query={0}', 'http://bham.craigslist.org/search/sss?query={0}', 'http://dothan.craigslist.org/search/sss?query={0}', 'http://shoals.craigslist.org/search/sss?query={0}', 'http://gadsden.craigslist.org/search/sss?query={0}', 'http://huntsville.craigslist.org/search/sss?query={0}', 'http://auburn.craigslist.org/search/sss?query={0}', 'http://bham.craigslist.org/search/sss?query={0}', 'http://virgin.craigslist.org/search/sss?query={0}'] BASE_URL = "craigslist.org" class Result: """ Creates object from passed in HTML. Should be one row element from base search""" def __init__(self, row): self.url = row.find("a", "result-title")['href'] if row.find("span", "result-price"): self.price = row.find("span", "result-price").get_text() else: self.price = "NA" self.create_date = row.find('time').get('datetime') self.title = row.find('a', 'result-title').get_text() def print_out(self): print "Title: " + self.title print "Price: " + self.price print "Creation Date: " + self.create_date print "URL: " + self.url print def parse_results(search_term): results = [] search_term = search_term.strip().replace(' ', '+') search_url = [url.format(search_term) for url in SEARCH_URL] soup = BeautifulSoup(urlopen(url).read()) rows = soup.find_all("li", "result-row") for row in rows: formattedResult = Result(row) results.append(formattedResult) return results def record_results(results): """ Writes URLs to file so we can keep track of what posts have been seen """ with open('results.csv', 'w') as f: for x in results: f.write(x.url) f.write("\n") def has_new_records(results): current_posts = [x.url for x in results…
downvote count: 1
has answer: http://stackoverflow.com/a/52054366
type: UnansweredQuestion
answer count: 1
favorite count: 0
tagged with: beautifulsoup
type: Question
tagged with: python
has title: Python csv exporting limited to 8KB?
score: 0
upvote count: 1

http://stackoverflow.com/comment/90896304
type: Comment
has text: I get this error now "AttributeError: 'str' object has no attribute 'isalnum()' "
type: AnswerComment
comment on: http://stackoverflow.com/a/51972857
score: 0

http://stackoverflow.com/q/51990490
upvote count: 1
type: Question
tagged with: opencv
has comment: http://stackoverflow.com/comment/90931639
has comment: http://stackoverflow.com/comment/90931756
has comment: http://stackoverflow.com/comment/90932221
answer count: 2
has comment: http://stackoverflow.com/comment/90931588
downvote count: 0
has title: importing opencv version 3.4.2.17 in python 3.7
favorite count: 0
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/60588207
tagged with: jupyter-notebook
has answer: http://stackoverflow.com/a/64820084
score: 1
has body: I have already installed opencv in anaconda prompt by entering the command: pip install opencv-python it installed properly, but I'm unable to import the module in jupyter notebook.I entered the following command in jupyter: import opencv but it's showing ModuleNotFoundError Also, to resolve anaconda environment issues, I entered the following command in anaconda prompt: conda install -c conda-forge opencv this further downloaded and extracted packages: libopencv-3.4.1,opencv-3.4.1,py-opencv3.4.1 but still I'm unable to import opencv or libopencv module in my Jupyter notebook. What should I do to use opencv3.4.2.17 in my python version3.7?

http://stackoverflow.com/a/51985483
has body: As a quick workarround you can use: sudo pip install --ignore-installed twilio
answers question: http://stackoverflow.com/q/51985401
has comment: http://stackoverflow.com/comment/90920318
upvote count: 1
has comment: http://stackoverflow.com/comment/90920426
has comment: http://stackoverflow.com/comment/90920384
type: Answer
has comment: http://stackoverflow.com/comment/90920339
downvote count: 0
score: 1

http://stackoverflow.com/q/51966096
has comment: http://stackoverflow.com/comment/90886403
tagged with: python
has comment: http://stackoverflow.com/comment/90883039
has title: How to speed up data wrangling A LOT in Python + Pandas + sqlAlchemy + MSSQL/T-SQL?
linked to: http://stackoverflow.com/q/17134942
answer count: 0
has comment: http://stackoverflow.com/comment/90883806
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90914258
linked to: http://stackoverflow.com/q/48006551
upvote count: 1
has comment: http://stackoverflow.com/comment/90883119
linked to: http://stackoverflow.com/q/51982306
linked to: http://stackoverflow.com/q/1466000
tagged with: performance
has comment: http://stackoverflow.com/comment/90883209
linked to: http://stackoverflow.com/q/45630095
score: 1
has comment: http://stackoverflow.com/comment/90886313
linked to: http://stackoverflow.com/q/29706278
has comment: http://stackoverflow.com/comment/90913431
tagged with: sqlalchemy
type: Question
has comment: http://stackoverflow.com/comment/90881988
tagged with: pandas
downvote count: 0
has comment: http://stackoverflow.com/comment/90884322
favorite count: 0
has body: (NB I do not consider myself a dev, dba or anything like that, I'm learning by doing - lots of (old) programming experience in general but python and sql are very new to me) I have seen this question but wonder whether 2+ years later things are now different. I have an MSSQL database of ~20M rows, ~10 columns (but I will be adding more columns). The source data was imported from CSV with empty values where there was no change between rows, so I have just used pandas dataframe to read in data, fill forward and write it back. I use dataframe.to_sql to write to a temporary table (replacing if it exists each time), then use SQL to update the main table. Updating 100k rows from the temp table takes &lt;1s but dataframe.to_sql is taking about 3 minutes for 100k rows. It will take about 8hrs to process the whole dB this way, and whilst that's OK for now (I'm learning how to wrangle dataframes, sql etc.) I need a speed up of at least two orders of magnitude. The known speed issues are: T-SQL limits table inserts to 1000 rows dataframe.to_sql has to have a small chunk size (currently 100) if I am to avoid pyodbc errors (including negative number of parameters!) One workaround would be to use dataframe.to_csv with append mode and then re-import the data that has had all the nas filled forward, but that should be a last resort. (It's certainly doable: the source CSV file is 800MB and by the time I have filled in the gaps it will probably be about ~20% bigger) Now, I have to do a lot of "signal processing" on the data as time series, for which Pandas seemed ideal; on the other hand I do also have Mathematica and can do some work there, but I would like to have a simple technology stack if possible. So, given that I will have to be making several passes through the whole db, updating it with results the question is: Is there any hope of getting the desired >100x speedup by one ore more techniques combined with Python + Pandas+ sqlAlchemy with an MSSQL backend... Other Python too…
tagged with: sql-server

parsing
tags question: http://stackoverflow.com/q/51984318
tags question: http://stackoverflow.com/q/52026274
tags question: http://stackoverflow.com/q/52007722
tags question: http://stackoverflow.com/q/51984700
tags question: http://stackoverflow.com/q/52001478
tags question: http://stackoverflow.com/q/51961652
tags question: http://stackoverflow.com/q/51994368
tag name: parsing
tags question: http://stackoverflow.com/q/52069715
tags question: http://stackoverflow.com/q/52034377
tags question: http://stackoverflow.com/q/51956961
tags question: http://stackoverflow.com/q/51981121
tags question: http://stackoverflow.com/q/52053222
tags question: http://stackoverflow.com/q/52100394
type: Tag
tags question: http://stackoverflow.com/q/52072537
tags question: http://stackoverflow.com/q/51975369
tags question: http://stackoverflow.com/q/52054842
tags question: http://stackoverflow.com/q/52010647
tags question: http://stackoverflow.com/q/52021254
tags question: http://stackoverflow.com/q/52095109
tags question: http://stackoverflow.com/q/51966541
tags question: http://stackoverflow.com/q/52008593
tags question: http://stackoverflow.com/q/52012899
tags question: http://stackoverflow.com/q/52053636

http://stackoverflow.com/a/76967542
has comment: http://stackoverflow.com/comment/136332407
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/52001694
has body: The following worked for me, with Quart 0.18.4: import logging logging.getLogger('hypercorn.access').disabled = True (I expected logging.getLogger('hypercorn.access').setLevel(logging.ERROR) to work too, but that strangely didn't do anything.)
downvote count: 0
has comment: http://stackoverflow.com/comment/138353223
type: Answer

http://stackoverflow.com/comment/91075039
type: AnswerComment
has text: You put it in your models.py that contains your user model and your model has the fields first_name and last_name?
comment on: http://stackoverflow.com/a/52046972
type: Comment
score: 0

http://stackoverflow.com/q/52048854
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/91051975
has answer: http://stackoverflow.com/a/52067073
tagged with: dataframe
has body: I'm using an online website that has it's own kernel for practising manipulating dataframes, but occasionally the dataframe is preloaded into the kernel and all I can do is use commands like .head() .info() and all other dataframe oriented commands to manipulate it but I am unable to find a way to copy this dataframe in a way that allows me to use the contents of the dataframe on jupyter notebooks or other IDEs on my system. I thought maybe I could save the dataframe as a CSV but alas I am unable to download files through the online kernel. Any idea's as to how I can bypass this problem?
score: 0
tagged with: pandas
answer count: 1
has title: How to copy a preloaded Pandas Dataframe in Python from an online kernel system, to my main IDE on my Ubuntu System
has comment: http://stackoverflow.com/comment/91084460
has comment: http://stackoverflow.com/comment/91084295
favorite count: 0
type: UnansweredQuestion
tagged with: python
tagged with: kernel
has comment: http://stackoverflow.com/comment/91084012
upvote count: 1

http://stackoverflow.com/comment/90884170
has text: Thanks a lot, I will look into this, I do not mark it as accepted yet because my goal is rather to understand the logic behind the facebook encoding so I can create a simple decoding function without using a whole module which seem overkill in this case (maybe the function i'm looking for is just burried in ftfy code, i'll look for it)
comment on: http://stackoverflow.com/a/51965058
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/a/52137765
upvote count: 3
type: AcceptedAnswer
type: Answer
has body: You could use an intermediate component like a div to save the input from the text field and update that div only on button click. So you would have app = dash.Dash(__name__) app.layout = html.Div([ dcc.Input(id='input-value', value='example', type='text'), html.Div(['example'], id='input-div', style={'display': 'none'}), html.Button('Submit', id="submit-button"), dcc.Graph(id='live-graph', animate=False), dcc.Interval( id='graph-update', interval=1*1000 ), ]) Now you update the div only on button click: @app.callback(Output('input-div', 'children'), [Input('submit-button', 'n_clicks')], state=[State(component_id='input-value', component_property='value')]) def update_div(n_clicks, input_value): return input_value And the Graph always uses the the div content to query your database (either when the interval triggers or the div changes): @app.callback(Output('live-graph', 'figure'), [Input('graph-update', 'interval'), Input('input-div', 'children')]) def update_graph_scatter(n, input_value): ...
downvote count: 0
has comment: http://stackoverflow.com/comment/91229431
score: 3
accepted answer of: http://stackoverflow.com/q/52110089
answers question: http://stackoverflow.com/q/52110089

http://stackoverflow.com/comment/91112474
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52080984
has text: thanks I will try this solution but I am curious to know why the approach was straightforward when using math.atan2 that I just needed to pass the x and y coordinates and compute the degree compared to using this numpy approach?

http://stackoverflow.com/q/52099923
has comment: http://stackoverflow.com/comment/91150555
has answer: http://stackoverflow.com/a/52102149
has comment: http://stackoverflow.com/comment/91151757
tagged with: beautifulsoup
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91151426
tagged with: python
has comment: http://stackoverflow.com/comment/91151698
tagged with: python-requests
has comment: http://stackoverflow.com/comment/91155407
has title: html content changes when using beautifulSoup
has comment: http://stackoverflow.com/comment/91151715
tagged with: web-crawler
has comment: http://stackoverflow.com/comment/91151217
type: Question
has body: I am trying to extract the attribute value of src from a block of html, the html block is : &lt;img class="product-image first-image" src="https://cache.net-a-porter.com/images/products/1083507/1083507_in_pp.jpg"&gt; my code is : import requests import json from bs4 import BeautifulSoup import re headers = {'User-agent': 'Mozilla/5.0'} url = 'https://www.net-a-porter.com/us/en/product/1083507/maje/layered-plaid-twill-and-stretch-cotton-jersey-top' page = requests.get(url, headers=headers) soup = BeautifulSoup(page.content, 'html.parser') if url.find('net-a-porter')!=-1 : i = soup.find_all('img', class_="product-image first-image")[0]["src"] print i the result i get: //cache.net-a-porter.com/images/products/1083507/1083507_in_xs.jpg but i want to get what is exactly in original html, which should be: https://cache.net-aporter.com/images/products/1083507/1083507_in_pp.jpg my result is different from the original src value, the http:is gone, and 1083507_in_pp changes to 1083507_in_xs. I don't know why it happens, does anyone know how to solve this? Thanks!
has comment: http://stackoverflow.com/comment/91151469
score: 0
tagged with: http://stackoverflow.com/tag/html
answer count: 1

http://stackoverflow.com/q/52041035
has answer: http://stackoverflow.com/a/52041079
upvote count: 0
tagged with: del
tagged with: python
linked to: http://stackoverflow.com/q/1207406
type: AnsweredQuestion
tagged with: list
has comment: http://stackoverflow.com/comment/91032897
has title: Python List Del & Reconciliation
has comment: http://stackoverflow.com/comment/91032655
has comment: http://stackoverflow.com/comment/91032948
type: Question
has comment: http://stackoverflow.com/comment/91032688
answer count: 1
score: -1
has body: I'm trying to delete multiple elements from a list. The elements are having their indexes evaluated dynamically, and stored in a list called "dstry". It may look something like this: arr = [1, 2, 2, 3, 5, 6, 7, 8, 9, 2] dstry = [1, 2, 9] However, if I do... for i in dstry: del arr[i] The list begins to shrink, and dstry's target elements are no longer where they should be. Logically, how can I get around this? It'd be nice if the del could resolve all at once and delay the collapse of the array. Should I instead replace the elements with a flag value and then del them wherever they appear later so that index is not a factor? Thanks
accepted answer: http://stackoverflow.com/a/52041079
duplicate of: http://stackoverflow.com/q/1207406
downvote count: 1
favorite count: 0

http://stackoverflow.com/comment/91063414
has text: Lines as an argument gives pool.map something to iterate over. I could've done the same thing with iterating over a list, other than the lines of a text file, but that is irrelevant in this case. The problem is that the "something" variable isn't shared between the main line and the threads. If I define "something" within the process function it works just fine. The question is how can i share the "something" variable with the threads.
type: QuestionComment
comment on: http://stackoverflow.com/q/52054414
score: 0
type: Comment

http://stackoverflow.com/comment/91111299
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52062275
has text: Did you try my answer and see any results?
type: AnswerComment

http://stackoverflow.com/comment/91158074
type: Comment
has text: This wouldn't work because `strip` only removes leading and trailing whitespace
comment on: http://stackoverflow.com/a/52103514
type: AnswerComment
score: 0

http://stackoverflow.com/comment/91075159
score: 1
comment on: http://stackoverflow.com/q/52062162
has text: The `width` and `height` options are only going to reflect the values you configured the Label with, not the actual size of the widget. The number of characters that will actually fit depends on *what those characters are*, anyway, unless you give it a monospaced font. If I'm understanding your requirements correctly, I believe the solution would be to use a Text widget, set to `disabled` or `readonly` mode except when you're changing the contents - this will simply clip any text that doesn't fit, rather than resizing itself as a Label would.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/90955827
comment on: http://stackoverflow.com/q/51982806
score: 0
type: Comment
type: QuestionComment
has text: Just write a command that takes an emoji: `@bot.command() async def getemoji(emoji: discord.Emoji): print(emoji.id)`

http://stackoverflow.com/comment/91040390
has text: "So is this ok to copy the venv folder's library files" – copying virtualenvs is usually a bad idea, it's best to create a new one.
comment on: http://stackoverflow.com/q/52044738
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91091466
score: 0
type: Comment
type: QuestionComment
has text: What is the type of result you're getting, have you tried to loop into result?
comment on: http://stackoverflow.com/q/52070869

http://stackoverflow.com/q/52046123
type: AnsweredQuestion
duplicate of: http://stackoverflow.com/q/1856408
has answer: http://stackoverflow.com/a/52046147
downvote count: 0
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/91044062
accepted answer: http://stackoverflow.com/a/52046147
has comment: http://stackoverflow.com/comment/91043334
tagged with: python
has title: try except not catching the exception
linked to: http://stackoverflow.com/q/20816332
score: 2
tagged with: python-3.x
upvote count: 2
has body: I was taught that an empty except catches all kinds of exceptions, but when I try this block of code it doesn't catch the exception and raise a SyntaxError. What am I doing wrong? try: print "Hello" except: print("Caught!") #output: SyntaxError: Missing parentheses in call to 'print'. Did you mean print("Hello")? even when I specify the kind of exception as SyntaxErrorit still doesn't catch it. try: print "Hello" except SyntaxError: print("Caught!") #output: SyntaxError: Missing parentheses in call to 'print'. Did you mean print("Hello")?
type: Question
tagged with: try-catch

http://stackoverflow.com/q/51981323
upvote count: 2
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90923616
has comment: http://stackoverflow.com/comment/90914206
linked to: http://stackoverflow.com/q/18039057
has comment: http://stackoverflow.com/comment/90924516
linked to: http://stackoverflow.com/q/23934613
has answer: http://stackoverflow.com/a/51982028
has body: I'm trying to download a csv file from an url without the "csv" suffix. The url is: https://www.ishares.com/de/professionelle-anleger/de/produkte/270048/ishares-msci-world-value-factor-ucits-etf/1478358465952.ajax?fileType=csv&amp;fileName=IS3S_holdings&amp;dataType=fund&amp;asOfDate=20180731 Since there is no "csv" suffix I haven't found any solution for this problem. My current code looks like this: link = "https://www.ishares.com/de/professionelle-anleger/de/produkte/270048/ishares-msci-world-value-factor-ucits-etf/1478358465952.ajax?fileType=csv&amp;fileName=IS3S_holdings&amp;dataType=fund&amp;asOfDate=20180731" data = pd.read_csv(link) Any help is really appreciated. Thanks!
type: Question
answer count: 2
tagged with: pandas
has comment: http://stackoverflow.com/comment/90912895
has title: Python Read csv file from URL without “csv” suffix
downvote count: 0
has answer: http://stackoverflow.com/a/51987501
favorite count: 0
has comment: http://stackoverflow.com/comment/90912571
tagged with: python-3.x
tagged with: http://stackoverflow.com/tag/csv
has comment: http://stackoverflow.com/comment/90924962
tagged with: python
score: 2
has comment: http://stackoverflow.com/comment/90914193

http://stackoverflow.com/q/51973529
has body: I am trying to extract model numbers from a very messy string field in pandas. The complication is that these serial numbers are not just numeric but sometimes alphanumeric. What I am trying to accomplish is to create a regex capture group/combo that allows me to capture alpha characters ONLY when they continuously precede,end,or are inside numeric sequences: model_number part b: 101-03-0458B B.2017Z brand name brand - 027xY21 to model_number_stripped 101030458B B2017Z 027xY21 So far I have the following: df['model_number_stripped'] = df['model_number'].str.replace('-','').str.replace('.','').str.replace('\D+','')
score: 1
has comment: http://stackoverflow.com/comment/90898418
type: Question
has comment: http://stackoverflow.com/comment/90898417
has comment: http://stackoverflow.com/comment/90901048
answer count: 1
has answer: http://stackoverflow.com/a/51975370
has comment: http://stackoverflow.com/comment/90900326
tagged with: pandas
has comment: http://stackoverflow.com/comment/90899352
has comment: http://stackoverflow.com/comment/90898015
favorite count: 0
has comment: http://stackoverflow.com/comment/90902506
has comment: http://stackoverflow.com/comment/90900381
upvote count: 2
accepted answer: http://stackoverflow.com/a/51975370
has title: Python Regex-Keep Alpha Characters Continuously Adjacent/Inside Numeric Sequences
tagged with: python
tagged with: regex
has comment: http://stackoverflow.com/comment/90898052
downvote count: 1
type: AnsweredQuestion

http://stackoverflow.com/q/52075175
type: Question
accepted answer: http://stackoverflow.com/a/52075233
tagged with: airflow
upvote count: 6
answer count: 2
possible better answer: http://stackoverflow.com/a/53429265
has answer: http://stackoverflow.com/a/52075233
has answer: http://stackoverflow.com/a/53429265
favorite count: 0
has title: Upgrade to Airflow 1.10 - _mysql_exceptions.OperationalError: (1054, "Unknown column 'task_instance.executor_config' in 'field list'")
score: 6
tagged with: python
has body: I just updated to Airflow 1.10 following the instructions here: https://medium.com/datareply/apache-airflow-1-10-0-released-highlights-6bbe7a37a8e1 When I click on a DAG in the web GUI I get the following error: _mysql_exceptions.OperationalError: (1054, "Unknown column 'task_instance.executor_config' in 'field list'") Seemingly upgrading requires changes to the database. Is there a command to alter existing tables? I didn't find anything on this in the Updating Airflow docs.
type: AnsweredQuestion
downvote count: 0
tagged with: mysql

http://stackoverflow.com/q/52079704
type: Question
linked to: http://stackoverflow.com/q/1132941
tagged with: nonetype
score: -2
tagged with: intersection
has body: I am having trouble with set operation intersection. Assume I have a list A = [0,1,2,3], and an integer B = 0. When I check if B in A:, I am getting of course True. But when A and B are as default equal to None, than I can't do the intersection operation of A and B. I am looking for a way to do following without getting an error: A = None B = None if B in A: raise KeyError('B in A') Normally A is a python List and B is a string. But I need to set them to None as default, while they are arguments in my function; where they have to have a value of None. PS: Getting True or False with the search algo. is not important. I just need to get True or False, so that I can arrange my error-raising.
has comment: http://stackoverflow.com/comment/91109486
answer count: 6
has title: Set Intersection with None
has answer: http://stackoverflow.com/a/52079771
tagged with: operation
has comment: http://stackoverflow.com/comment/91109463
accepted answer: http://stackoverflow.com/a/52079808
has comment: http://stackoverflow.com/comment/91109540
has answer: http://stackoverflow.com/a/52080025
has comment: http://stackoverflow.com/comment/91109611
has answer: http://stackoverflow.com/a/52080002
favorite count: 0
has answer: http://stackoverflow.com/a/52079761
linked to: http://stackoverflow.com/q/38204342
has answer: http://stackoverflow.com/a/52079840
tagged with: python
has comment: http://stackoverflow.com/comment/91109563
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/52079761
has comment: http://stackoverflow.com/comment/91109506
tagged with: set
downvote count: 3
has comment: http://stackoverflow.com/comment/91109512
has answer: http://stackoverflow.com/a/52079808
upvote count: 1

python-module
tags question: http://stackoverflow.com/q/51985669
type: Tag
tags question: http://stackoverflow.com/q/51989110
tag name: python-module
tags question: http://stackoverflow.com/q/51989012
tags question: http://stackoverflow.com/q/52055788

http://stackoverflow.com/a/52106359
type: Answer
answers question: http://stackoverflow.com/q/52105810
has body: I think this is an answer. Or maybe in other way - # lets have some data to process: stamps = pd.date_range('2018-05-19 18:15:05', periods=4, freq='2H') df = pd.DataFrame(stamps) df.apply(lambda e : e + datetime.timedelta(seconds=1)) Shows: 0 0 2018-05-19 18:15:06 1 2018-05-19 20:15:06 2 2018-05-19 22:15:06 3 2018-05-20 00:15:06 And this: df.apply(lambda e : e + datetime.timedelta(seconds=100)) 0 0 2018-05-19 18:16:45 1 2018-05-19 20:16:45 2 2018-05-19 22:16:45 3 2018-05-20 00:16:45 Just to see difference. Tip here is to stick with dates. That way timedelta works. You can use combine to make Datetime from Date, and Time.
score: 0

http://stackoverflow.com/a/52023416
type: AcceptedAnswer
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/52023108
has body: The issue is in this line candidate_military = request.POST["candidate_military"] There is no need for this line. Just remove it and the code should just work fine.
score: 1
accepted answer of: http://stackoverflow.com/q/52023108
upvote count: 1

http://stackoverflow.com/q/52049202
tagged with: python
has title: How to use Docker AND Conda in PyCharm
type: AnsweredQuestion
tagged with: pycharm
score: 7
upvote count: 7
type: Question
accepted answer: http://stackoverflow.com/a/52231615
has comment: http://stackoverflow.com/comment/91049633
tagged with: conda
tagged with: docker
has body: I want to run python in PyCharm by using a Docker image, but also with a Conda environment that is set up in the Docker image. I've been able to set up Docker and (locally) set up Conda in PyCharm independently, but I'm stumped as to how to make all three work together. The problem comes when I try to create a new project interpreter for the Conda environment inside the Docker image. When I try to enter the python interpreter path, it throws an error saying that the directory/path doesn't exist. In short, the question is the same as the title: how can I set up PyCharm to run on a Conda environment inside a Docker image?
answer count: 1
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/52231615
has comment: http://stackoverflow.com/comment/91063701

http://stackoverflow.com/comment/91170337
score: 0
comment on: http://stackoverflow.com/q/52109791
type: Comment
has text: Tested and if both columns names are numeric, it working nice.
type: QuestionComment

http://stackoverflow.com/comment/91125438
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52052589
score: 0
has text: It is not so odd as the MNIST dataset is pretty much filled with numbers that have a particular aspect ratio. If you feed your model with numbers that have a different aspect ratio, it will fail.

http://stackoverflow.com/a/52097960
has body: You can use the function strftime from datetime. Here is an example: from datetime import date import random import pandas as pd from seaborn import boxplot dates = [date.today()]*10 dataSum = [random.randint(1,100) for x in range(10)] d = {'date': dates, 'sum':dataSum} df = pd.DataFrame(data = d) dateData = [x.strftime('%B') for x in df['date']] boxplot(dateData, df['sum']) Resulting Plot
upvote count: 2
type: Answer
score: 2
answers question: http://stackoverflow.com/q/52097045
downvote count: 0

http://stackoverflow.com/comment/91013163
has text: Either works. Doing `end=' '` doesn't require a cast to string whereas `end=''` does to have a space in-between.
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52031298

http://stackoverflow.com/a/58735566
answers question: http://stackoverflow.com/q/52105543
upvote count: 8
type: Answer
has body: This might be a little late, but there is a convient function in Cartopy for this. We can use Cartopy's .circle function (documentation) to generate a ring of points with a specified radius from a particular (longitude &amp; latitude) in the Geodesic coordinate frame and then plot a polygon with those points using Shapely. This would look something like the following circle_points = cartopy.geodesic.Geodesic().circle(lon=lon, lat=lat, radius=radius_in_meters, n_samples=n_points, endpoint=False) geom = shapely.geometry.Polygon(circle_points) ax.add_geometries((geom,), crs=cartopy.crs.PlateCarree(), facecolor='red', edgecolor='none', linewidth=0) Specifying the crs as PlateCarree does not matter and merely avoids a warning with Shapely. You will keep your desired projection. However, if you are plotting directly with the circle center on the pole, you might still have an issue and may need to do some fancy transformations (Haven't tested it recently, but recall from a few months ago it being a little wonky). You could also manually compute these points using the pyproj library Cartopy makes use of, specifically the Geod class. Pick a point with a radius and loop through the azmoths for however fine you want your circle to be with the .inv or .fwd function similar to the suggestion in https://stackoverflow.com/a/57002776/2430454. I don't recommend this method, but used it a long while back to accomplish the same thing.
downvote count: 0
score: 8

http://stackoverflow.com/comment/90865393
type: Comment
comment on: http://stackoverflow.com/q/51957369
type: QuestionComment
has text: @SmitM that's another good point. Alternatively you could use a `global`
score: 0

http://stackoverflow.com/q/51998773
tagged with: python
has title: NameError Using time.sleep in MicroPython
has body: import time from umqtt.simple import MQTTClient from machine import Pin from dht import DHT22 SERVER = 'X.X.X.X' # MQTT Server Address (Change to the IP address of your Pi) CLIENT_ID = 'ESP32_DHT22_Sensor' TOPIC = b'temp_humidity' running = True client = MQTTClient(CLIENT_ID, SERVER) client.connect() # Connect to MQTT broker sensor = DHT22(Pin(15, Pin.IN, Pin.PULL_UP)) # DHT-22 on GPIO 15 (input with internal pull-up resistor) def run(): while running: try: sensor.measure() # Poll sensor t = sensor.temperature() h = sensor.humidity() tm = time.localtime(time.time()) if isinstance(t, float) and isinstance(h, float) and tm[0] &gt; 2000: # Confirm sensor results$ msg = (b'{0:n},{1:n},{2:n},{3:n},{4:n},{5:3.1f},{6:3.1f}'.format(tm[0], tm[1], tm[2]$ client.publish(TOPIC, msg, retain=True) # Publish sensor data to MQTT topic print(str(msg)) print('Sent to ' + SERVER + ' as ' + CLIENT_ID + '. Exiting.') running = False else: print('Invalid sensor readings.') except OSError: print('Failed to read sensor.') time.sleep(1) Apologies for importing the whole script. As it is short, I thought it may be valuable to be able to see all of it. I import time at the top of the script and as far as I can tell, all variables are referenced before they are used. I would like to import this script as dht_publish and then run dht_publish.run(). However, this gives the following error. This is run on the latest MicroPython binary on an ESP32 dev board. Traceback (most recent call last): File &lt;stdin&gt;, line 1, in &lt;module&gt; File dht_publish.py, line 33, in run NameError: local variable referenced before assignment If I comment out the time.sleep(1) line then the error is flagged on the line before which suggests that the error may be elsewhere in the code but I can't see where. Any help on this would be very much appreciated.
downvote count: 1
type: Question
tagged with: esp32
score: 0
tagged with: micropython
has answer: http://stackoverflow.com/a/52021228
answer count: 1
favorite count: 0
type: UnansweredQuestion
upvote count: 1

http://stackoverflow.com/comment/91024444
score: 1
type: QuestionComment
comment on: http://stackoverflow.com/q/52037095
type: Comment
has text: Could you provide an example of your dataframe as well as desired output?

http://stackoverflow.com/q/52063463
upvote count: 2
tagged with: python
type: AnsweredQuestion
tagged with: anaconda
tagged with: gis
type: Question
has answer: http://stackoverflow.com/a/52098091
has body: I just did a fresh install of Anaconda3 and am trying to add GDAL/OGR. I've tried installing with both conda install gdal and conda install -c conda-forge gdal. In both cases, the install completes successfully, but when I import gdal, it raises the error: Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "C:\Users\user\AppData\Local\Continuum\miniconda3\lib\site-packages\osgeo\__init__.py", line 25, in &lt;module&gt; _gdal = swig_import_helper() File "C:\Users\user\AppData\Local\Continuum\miniconda3\lib\site-packages\osgeo\__init__.py", line 21, in swig_import_helper _mod = imp.load_module('_gdal', fp, pathname, description) File "C:\Users\user\AppData\Local\Continuum\miniconda3\lib\imp.py", line 243, in load_module return load_dynamic(name, filename, file) File "C:\Users\user\AppData\Local\Continuum\miniconda3\lib\imp.py", line 343, in load_dynamic return _load(spec) ImportError: DLL load failed: The specified module could not be found.
tagged with: gdal
score: 2
answer count: 1
downvote count: 0
favorite count: 0
accepted answer: http://stackoverflow.com/a/52098091
tagged with: python-3.x
has title: Installing GDAL with Anaconda

http://stackoverflow.com/q/52009831
possible better answer: http://stackoverflow.com/a/52009899
downvote count: 0
has answer: http://stackoverflow.com/a/52009899
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/36901
answer count: 2
accepted answer: http://stackoverflow.com/a/52009859
tagged with: python
score: 4
has body: I'm writing a program to parse through some log files. If an error code is in the line, I need to print the previous 25 lines for analysis. I'd like to be able to repeat this concept with more or less lines depending on the individual error code (instead of 25 lines, 15 or 35). with open(file, 'r') as input: for line in input: if "error code" in line: #print previous 25 lines I know the equivalent command in Bash for what I need is grep "error code" -B 25 Filename | wc -1. I'm still new to python and programming in general, I know I'm going to need a for loop and I've tried using the range function to do this but I haven't had much luck because I don't know how to implement the range into files.`
upvote count: 4
tagged with: fileparsing
tagged with: text-parsing
has title: Print a number of previous lines after matching string found in line in python
has answer: http://stackoverflow.com/a/52009859
type: AnsweredQuestion

http://stackoverflow.com/comment/91109271
score: 5
comment on: http://stackoverflow.com/q/52079641
type: Comment
type: QuestionComment
has text: I think you're missing the first line: `def search(T, num):`?

http://stackoverflow.com/a/52028841
answers question: http://stackoverflow.com/q/52028354
has body: dense In [135]: A.dot(x) Out[135]: matrix([[3., 3.]]) In [136]: np.ones((2,3)).dot(x) Out[136]: array([3., 3.]) np.matrix is a subclass of ndarray that must be 2d, and tries, as much as possible, to return np.matrix (2d) results. Hence Out[135] is 2d (1,2). Out[136] on the other hand is a (2,3) dot (3,) => (2,). But it is worth keeping mind that dot has some special rules when one or other of the inputs is 1d. Pure np.matrix dot: In [161]: A.dot(np.matrix(x).T) # A*np.matrix(x).T Out[161]: matrix([[3.], [3.]]) sparse While sparse matrix is modeled on np.matrix, it is its own class, and behaves differently in many cases. dot of sparse and dense can be tricky. In [152]: B.shape Out[152]: (2, 3) In [153]: B.dot(x) Out[153]: array([3., 3.]) Effectively the B has been turned into an array first: In [154]: B.A.dot(x) # B.toarray() Out[154]: array([3., 3.]) But this is wrong, because it attempts to use np.array(B) instead of the proper B.toarray(): In [155]: np.dot(B,x) Out[155]: array([&lt;2x3 sparse matrix of type '&lt;class 'numpy.float64'&gt;' with 6 stored elements in Compressed Sparse Row format&gt;, &lt;2x3 sparse matrix of type '&lt;class 'numpy.float64'&gt;' with 6 stored elements in Compressed Sparse Row format&gt;, &lt;2x3 sparse matrix of type '&lt;class 'numpy.float64'&gt;' with 6 stored elements in Compressed Sparse Row format&gt;], dtype=object) In [156]: np.array(B) Out[156]: array(&lt;2x3 sparse matrix of type '&lt;class 'numpy.float64'&gt;' with 6 stored elements in Compressed Sparse Row format&gt;, dtype=object) If both variables are sparse, then the result is also sparse. In this case the special dot handling of 1d arrays does not apply. A (2,3) has to multiply a (3,1), producing a (2,1): In [158]: B*sparse.csr_matrix(x).T Out[158]: &lt;2x1 sparse matrix of type '&lt;class 'numpy.float64'&gt;' with 2 stored elements in Compressed Sparse Row format&gt; In [159]: _.A Out[159]: array([[3.], [3.]]) In sum, mixing matrix types can be confusing. It would be c…
accepted answer of: http://stackoverflow.com/q/52028354
type: Answer
has comment: http://stackoverflow.com/comment/91009227
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/91008634
type: AcceptedAnswer
upvote count: 1

http://stackoverflow.com/a/52072458
has body: Possibly related duplicate question: How do I find the duplicates in a list and create another list with them? Simple Answer: &gt;&gt;&gt; l = [1,2,3,4,4,5,5,6,1] &gt;&gt;&gt; set([x for x in l if l.count(x) &gt; 1]) set([1, 4, 5])
downvote count: 0
answers question: http://stackoverflow.com/q/52072381
upvote count: 2
type: Answer
score: 2

http://stackoverflow.com/comment/91151465
type: Comment
score: 1
has text: It's possible that the existence of the deprecated `google-cloud` package is somehow interfering, can you remove it, reinstall `google-cloud-storage` and confirm that it's still not working?
type: AnswerComment
comment on: http://stackoverflow.com/a/52085208

http://stackoverflow.com/a/52114766
score: 0
type: Answer
answers question: http://stackoverflow.com/q/52086416
has body: import os path = './text/' # open this file for writing with open("sw_mac_addr.csv", "w+") as fh: print('Switch Name', 'Port', 'mac addr', 'vlan', sep=",", file=fh) # get data from all files in the path for filename in os.listdir(path): with open(os.path.join(path,filename), "r") as infile: for line in infile: if line.startswith('*') or line.startswith('+'): # if you want to get rid of the * and +, uncomment the following code # line = line.replace("*","").replace("+","") line = ",".join(line.split()) + "\n" fh.write(line) print(line) output (both on console and csv file): *,51,0000.0c9f.f033,static,0,F,F,sup-eth2 *,51,0000.0c9f.f033,static,0,F,F,sup-eth2 *,51,0000.0c9f.f033,static,0,F,F,sup-eth2 output with uncommented line of code (line = line.replace("*";"").replace("+","") 51,0000.0c9f.f033,static,0,F,F,sup-eth2 51,0000.0c9f.f033,static,0,F,F,sup-eth2 51,0000.0c9f.f033,static,0,F,F,sup-eth2

knapsack-problem
type: Tag
tags question: http://stackoverflow.com/q/51995188
tag name: knapsack-problem
tags question: http://stackoverflow.com/q/51981432

http://stackoverflow.com/comment/90866840
type: QuestionComment
comment on: http://stackoverflow.com/q/51958209
score: 3
has text: `map(max, [1,2,3,4])` calls `max(1)`, then `max(2)`, then `max(3)`, then `max(4)`. None of those calls make any sense. What did you _want_ it to call? Just `max([1,2,3,4])` without `map`? Or something different?
type: Comment

http://stackoverflow.com/q/52032825
favorite count: 0
tagged with: python
tagged with: pygame
tagged with: font-family
tagged with: python-3.x
tagged with: fonts
has answer: http://stackoverflow.com/a/52033413
upvote count: 1
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/52033413
score: 1
has body: I installed 'Raleway' a while ago, and can't seem to make it work for pygame. My program seems to only be able to display the regular version of the font, but not bold, italics, etc. Here's what I have: import pygame pygame.init() pygame.font.init() myfont = pygame.font.SysFont('Raleway Bold', 72) screen = pygame.display.set_mode((850, 600)) done = False while not done: for event in pygame.event.get(): if event.type == pygame.QUIT: done = True screen.fill((8, 8, 8)) textsurface = myfont.render('WELCOME', False, (205, 92, 92)) screen.blit(textsurface,(250,200)) And here's the fonts available under the font family: Raleway
type: Question
has title: How do I use font families on pygame?
answer count: 1
downvote count: 0

http://stackoverflow.com/a/52049491
has comment: http://stackoverflow.com/comment/91079765
score: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/91050161
type: Answer
has body: If you just want a single list of players and teams, then this should suffice: import re players_and_teams = [] for i in soup.find_all('td'): if i.find_all('a'): for link in i.find_all('a'): if not re.findall(r'Preview',link.text): players_and_teams.append(link.text)
has comment: http://stackoverflow.com/comment/91216468
has comment: http://stackoverflow.com/comment/91049968
answers question: http://stackoverflow.com/q/52048112
has comment: http://stackoverflow.com/comment/91076424
accepted answer of: http://stackoverflow.com/q/52048112

http://stackoverflow.com/comment/91129440
has text: Update the question with the relevant HTML
comment on: http://stackoverflow.com/q/52089380
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/108762378
score: 0
has text: Been a while since I've connected to a windows server -- the last time I built a full windows setup, I believe, is here: https://github.com/mmckerns/tuthpc. I agree, a full tutorial would be nice. It's been on my todo list for a long time, unfortunately.
type: AnswerComment
comment on: http://stackoverflow.com/a/52043377
type: Comment

http://stackoverflow.com/comment/119320952
score: 0
comment on: http://stackoverflow.com/a/54032131
has text: You made my day ! Perfect , I was just searching all the day to do this!
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/91089538
score: 0
comment on: http://stackoverflow.com/a/52069717
type: Comment
type: AnswerComment
has text: I tested your code, and it worked perfectly!! Thanks a ton for your help. However, by "precompute the mines along rows and cols", did you mean counting the number of x and y-coordinates (equivalent to number of given gold mines) from the given lists `X` and `Y`, and put it into a new list called `rows` and `cols` that have the size `N` and `M`, respectively?

http://stackoverflow.com/a/51973973
has body: There are several problems with the code you posted : negative_trailers = '|'.join(negative_descriptors) should be negative_trailers = '|'.join(negative_trailers ) You should also convert your list keywords to string as you did for your other lists so that it can be passed to a regex There is no use to use 3 times 'r' in your regex After these corrections your code should look like this : negative_descriptors = ['no', 'unlikely', 'no evidence of'] negative_descriptors = '|'.join(negative_descriptors) negative_trailers = ['not present', 'not evident'] negative_trailers = '|'.join(negative_trailers) keywords = ['disc prolapse', 'vertebral osteomyelitis', 'collection'] keywords = '|'.join(keywords) if re.search(r"("+negative_descriptors+").*("+keywords+")", message): neg_desc_present = True if re.search(r"("+keywords+").*("+negative_trailers+")", message): neg_desc_present = True
accepted answer of: http://stackoverflow.com/q/51973450
answers question: http://stackoverflow.com/q/51973450
score: 0
type: AcceptedAnswer
type: Answer

http://stackoverflow.com/comment/90936892
comment on: http://stackoverflow.com/a/51993508
type: Comment
score: 0
has text: good point, thanks. I only need to access the last element of what I am currently returning and then it is the same thing (at least the difference of OPs method with my method then returns zero for a 10x10 random array). Thank you @gboffi!
type: AnswerComment

http://stackoverflow.com/a/52014001
type: Answer
has body: The expression 2/(timeframe+1) is always zero, because the components are all integers and therefore Python 2 uses integer division. Wrapping that result in float() does no good; you just get 0.0 instead of 0. Try 2.0/(timeframe+1) instead.
upvote count: 1
has comment: http://stackoverflow.com/comment/90978529
accepted answer of: http://stackoverflow.com/q/52013949
answers question: http://stackoverflow.com/q/52013949
type: AcceptedAnswer
downvote count: 0
score: 1

http://stackoverflow.com/comment/90999816
comment on: http://stackoverflow.com/a/52024714
type: Comment
has text: When I use the following: matrix('[1, 2; 3, 4]') It says 'list' object is not callable
score: 0
type: AnswerComment

http://stackoverflow.com/q/51990946
tagged with: apache-spark
upvote count: 1
answer count: 1
favorite count: 0
linked to: http://stackoverflow.com/q/49499263
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/90932163
downvote count: 0
score: 1
type: Question
has body: I have a .csv dataset containing Amazon book reviews. I looks like this: B000F83SZQ|[0, 0]|5.0|I enjoy vintage books and movies so I enjoyed reading this book. The plot was unusual. Don't think killing someone in self-defense but leaving the scene and the body without notifying the police or hitting someone in the jaw to knock them out would wash today.Still it was a good read for me.|05 5, 2014|A1F6404F1VG29J|Avidreader|Nice vintage story|1399248000 B000F83SZQ|[2, 2]|4.0|This book is a reissue of an old one the author was born in 1910. It's of the era of, say, Nero Wolfe. The introduction was quite interesting, explaining who the author was and why he's been forgotten I'd never heard of him.The language is a little dated at times, like calling a gun a &amp;#34 heater.&amp;#34 I also made good use of my Fire's dictionary to look up words like &amp;#34 deshabille&amp;#34 and &amp;#34 Canarsie.&amp;#34 Still, it was well worth a look-see.|01 6, 2014|AN0N05A9LIJEQ|critters|Different...|1388966400 B000F83SZQ|[2, 2]|4.0|This was a fairly interesting read. It had old- style terminology.I was glad to get to read a story that doesn't have coarse, crasslanguage. I read for fun and relaxation......I like the free ebooksbecause I can check out a writer and decide if they are intriguing,innovative, and have enough of the command of Englishthat they can convey the story without crude language.|04 4, 2014|A795DMNCJILA6|dot|Oldie|1396569600 B000F83SZQ|[1, 1]|5.0|I'd never read any of the Amy Brewster mysteries until this one.. So I am really hooked on them now.|02 19, 2014|A1FV0SX13TWVXQ|Elaine H. Turley "Montana Songbird"|I really liked it.|1392768000 B000F83SZQ|[0, 1]|4.0|If you like period pieces - clothing, lingo, you will enjoy this mystery. Author had me guessing at least 2/3 of the way through.|03 19, 2014|A3SPTOKDG7WBLN|Father Dowling Fan|Period Mystery|1395187200 B000F83SZQ|[0, 0]|4.0|A beautiful in-depth character description makes it like a fast pacing movie. It is a pi…
tagged with: split
has title: How to split dataframe column in PySpark
tagged with: pyspark
tagged with: dataframe
has answer: http://stackoverflow.com/a/52000674

http://stackoverflow.com/comment/90974977
type: AnswerComment
type: Comment
score: 0
has text: @user2357112 Could you please give an example about that? I think most developer won't bother with `__slots__` when defining a custom class. If so, and they define the subclass by `class Foo(object): ...`, then `Foo` seems to always support weak references in CPython. Not sure about this on different Python implementations.
comment on: http://stackoverflow.com/a/52011601

http://stackoverflow.com/q/51975912
type: Question
upvote count: 15
has comment: http://stackoverflow.com/comment/90950184
has answer: http://stackoverflow.com/a/65781700
has comment: http://stackoverflow.com/comment/90924708
has comment: http://stackoverflow.com/comment/90931473
downvote count: 0
has comment: http://stackoverflow.com/comment/90966912
favorite count: 0
has answer: http://stackoverflow.com/a/78185882
answer count: 5
has comment: http://stackoverflow.com/comment/90913312
has title: Get column names of Excel worksheet with OpenPyXL in readonly mode
has comment: http://stackoverflow.com/comment/90963577
tagged with: python
possible better answer: http://stackoverflow.com/a/51981889
score: 15
has answer: http://stackoverflow.com/a/51999691
has answer: http://stackoverflow.com/a/51981889
tagged with: openpyxl
tagged with: excel
has answer: http://stackoverflow.com/a/68658075
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90929164
has body: How could I retrieve the column names (values of the cells in the first row) in an openpyxl Read-only worksheet? City, Population, Country in the below example worksheet all column names in an openpyxl Read-only workbook? City, Population, Country, frames from worksheet 1 and the other column names from all other worksheets Example Excel worksheet: | City | Population | Country | | -----------|------------ | ------------ | | Madison | 252,551 | USA | | Bengaluru | 10,178,000 | India | | ... | ... | ... | Example code: from openpyxl import load_workbook wb = load_workbook(filename=large_file.xlsx, read_only=True) sheet = wb.worksheets[0] ... (not sure where to go from here) Notes: I have to use readonly because the Excel file has over 1 million rows (don't ask) I'd like the column names so I can eventually infer the column types and import the excel data into a PostgreSQL database
accepted answer: http://stackoverflow.com/a/51999691

http://stackoverflow.com/q/52018811
type: UnansweredQuestion
has title: Get IPs of all devices connected to local network (based on hostname) with python
tagged with: raspberry-pi
tagged with: device
answer count: 0
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/90987994
favorite count: 0
type: Question
tagged with: python
tagged with: hostname
tagged with: local-network
has body: this is definetly not duplicate. I am doing an app and I need to find IPs of my devices. I know their name, and through their name I need to get their IP. Linux should be easy but I need cross platform attitude and so therefore I use python. I already know solution: import socket socket.gethostbyname('pc_name') If I know solution, why I am asking? Well give me moment, because I am not getting stable results. Situation: I need to find IPs of several raspberry pi's that has same hostname - lets say: Raspberry pi device 1: Hostname: 'MyPi', Local IP: 10.0.0.33 Raspberry pi device 2: Hostname: 'MyPi', Local IP: 10.0.0.34 Raspberry pi device 3: Hostname: 'MyPi', Local IP: 10.0.0.35 So according to socket documentation(If I read it correctly), socket.gethostbyname('MyPi') returns only one IP, HOWEVER socket.gethostbyname_ex('MyPi') should return all IPs for the particular hostname. I simulated the situation at home and the results were very unsatisfying. I called my raspberry pi as my Android phone: 'Galaxy-J5-2016'. To make sure I tried to find them by address: &gt;&gt;&gt; socket.gethostbyaddr('10.0.0.33') ('Galaxy-J5-2016', [], ['10.0.0.33']) &gt;&gt;&gt; socket.gethostbyaddr('10.0.0.34') ('Galaxy-J5-2016', [], ['10.0.0.34']) Good , they exist. When I tested it before writing here, I even got one result if I searched socket.gethostbyname('Galaxy-J5-2016') BUT now I dont find anything even if I try socket.gethostbyname_ex('Galaxy-J5-2016') Both above commands simply wait without response and then respond with this: Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; socket.gaierror: [Errno 11001] getaddrinfo failed Another phenomena occured: When I try lastly mentioned command on my work laptop(Even though my work PC doesnt share hostname with any other computer), &gt;&gt;&gt; socket.gethostbyname_ex('WORK_PC.DOM1.DOM2') ('WORK_PC.DOM1.DOM2', [], ['172.xx.xx.1', '10.0.xx.1', '172.xx.xx.241', '192.xx.xx.1', '192.xx.xx.1', **'10.0.0.41'**]) …
upvote count: 1
has comment: http://stackoverflow.com/comment/90990063

http://stackoverflow.com/a/53396910
type: Answer
has comment: http://stackoverflow.com/comment/104480322
upvote count: 9
score: 9
has body: It is better to use fake_useragent here for making things easy. A random user agent sends request via real world browser usage statistic. If you don't need dynamic content, you're almost always better off just requesting the page content over HTTP and parsing it programmatically. import requests from fake_useragent import UserAgent headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36'} ua=UserAgent() hdr = {'User-Agent': ua.random, 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', 'Accept-Charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.3', 'Accept-Encoding': 'none', 'Accept-Language': 'en-US,en;q=0.8', 'Connection': 'keep-alive'} url = "http://www.amazon.com/dp/" + 'B004CNH98C' response = requests.get(url, headers=hdr) print response.content Selenium is used for browser automation and high level web scraping for dynamic contents.
downvote count: 0
answers question: http://stackoverflow.com/q/52068920

http://stackoverflow.com/comment/91134827
has text: I can't test your code so I can only give suggestions. I think you'll be better using an asynchronous library for making requests like [requests-futures](https://github.com/ross/requests-futures). `multiprocessing` is pretty heavy, but in order to make it work like you're trying, you need to reverse your approach. Instead of launching in a `for` loop, you should chunk a list of URLs and send each chunk to an individual process
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52092321
score: 0

http://stackoverflow.com/q/52089195
answer count: 3
tagged with: python-3.x
has answer: http://stackoverflow.com/a/52092390
type: UnansweredQuestion
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/91128512
has title: Open reading and averaging text files python
linked to: http://stackoverflow.com/q/20457038
score: 1
has answer: http://stackoverflow.com/a/52089252
type: Question
has answer: http://stackoverflow.com/a/52089218
has body: Hi so i'm currently trying to write a code that asks for a number of days and then opens multiple text files(temps1.txt etc), reads them, sorts them into dictionarys with an average and then prints it out. However some of the averages have an extreme amount of decimal spots f = {} ans = int(input('How many days of data do you have? ')) #figure out how to open certain files for file_num in range(1, (ans+1)): file_name = "temps" + str(file_num) + ".txt" temps = open(file_name) for line in temps: room, num = line.strip('\n').split(',') num = int(num) #may need to be 4* however many times it appears num = num/(4*ans) f[room] = f.get(room, 0) + num print('Average Temperatures:') for x in f: print (x + ':',f[x]) i have an example for a room called bedroom (all the bedrooms in the text files average) and the average is 26.0 however it prints out as 26.000000000000004 how do i stop it doing this?
has comment: http://stackoverflow.com/comment/91128525
downvote count: 0
linked to: http://stackoverflow.com/q/588004
favorite count: 0

http://stackoverflow.com/comment/90933275
type: QuestionComment
comment on: http://stackoverflow.com/q/51991764
has text: @wim, what is MCVE?
score: 0
type: Comment

http://stackoverflow.com/a/52027930
has comment: http://stackoverflow.com/comment/91014745
upvote count: 3
score: 3
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52022575
type: Answer
answers question: http://stackoverflow.com/q/52022575
has body: My proposal for a MIP model: Introduce binary variables: x(i,t) = 1 if task i is assigned to slot t 0 otherwise y(t) = 1 if slot t has at least one task assigned to it 0 otherwise Furthermore let: N = max number of tasks per slot ok(i,t) = 1 if we are allowed to assign task i to slot t 0 otherwise Then the model can look like: minimize sum(t,y(t)) (minimize used slots) sum(t, ok(i,t)*x(i,t)) = 1 for all i (each task is assigned to exactly one slot) sum(i, ok(i,t)*x(i,t)) &lt;= N for all t (capacity constraint for each slot) y(t) &gt;= x(i,t) for all (i,t) such that ok(i,t)=1 x(i,t),y(t) in {0,1} (binary variables) Using N=3, I get a solution like: ---- 45 VARIABLE x.L assignment s5 s6 s7 s13 task1 1.000 task2 1.000 task3 1.000 task4 1.000 task5 1.000 task6 1.000 task7 1.000 task8 1.000 task9 1.000 task10 1.000 The model is fairly simple and it should not be very difficult to code and solve it using your favorite MIP solver. The one thing you want to make sure is that only variables x(i,t) exist when ok(i,t)=1. In other words, make sure that variables do not appear in the model when ok(i,t)=0. It can help to interpret the assignment constraints as: sum(t | ok(i,t)=1, x(i,t)) = 1 for all i (each task is assigned to exactly one slot) sum(i | ok(i,t)=1, x(i,t)) &lt;= N for all t (capacity constraint for each slot) where | means 'such that' or 'where'. If you do this right, your model should have 50 variables x(i,t) instead of 10 x 17 = 170. Furthermore we can relax y(t) to be continuous between 0 and 1. It will be either 0 or 1 automatically. Depending on the solver that may affect performance. I have no reason to believe this is easier to model as a constraint programming model or that it is easier to solve that way. My rule of thumb is, if it is easy to model as a MIP stick to a MIP. If we need to go through lots of hoops to make it a proper MIP, and a CP formulation makes life easier, then use CP. In many cases this simple rule works quite well.

http://stackoverflow.com/q/52024899
tagged with: numpy
has comment: http://stackoverflow.com/comment/91000063
score: 11
tagged with: pandas
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52025162
has body: With this pd.Timestamp("31.12.1999 23:59:12").value &gt;&gt;946684752000000000 I can get the integer value of a datetime elementary value. How can I get this done for an array of datetime values? df = pd.DataFrame({"a": ["31.12.1999 23:59:12", "31.12.1999 23:59:13", "31.12.1999 23:59:14"], "b": [4, 5, 6]}) df.insert(0, 'date', df.a.apply(lambda x: datetime.datetime.strptime(x, "%d.%m.%Y %H:%M:%S"))) Apparently, this does not work: df.date.values.value &gt;&gt;AttributeError: 'numpy.ndarray' object has no attribute 'value'
downvote count: 0
favorite count: 0
has title: How to convert datetime64 array to int?
type: Question
tagged with: python
upvote count: 11
accepted answer: http://stackoverflow.com/a/52025162
answer count: 1

http://stackoverflow.com/q/52041224
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/91037467
has comment: http://stackoverflow.com/comment/91056758
has comment: http://stackoverflow.com/comment/91054873
has comment: http://stackoverflow.com/comment/91054266
has body: During a NLP process, I transform a corpus of texts using TF-IDF which yields a scipy.sparse.csr.csr_matrix. I then split this data into train and test corpus and resample my train corpus in order to tackle a class imbalance problem. The issue I'm facing is that when I use the resampled index (from the label which is of type pandas.Series) to resample the sparse matrix like this: tfs[Ytr_resample.index] It takes a lot of time, and outputs the error: --------------------------------------------------------------------------- ValueError Traceback (most recent call last) &lt;ipython-input-29-dd1413907d77&gt; in &lt;module&gt;() ----&gt; 1 tfs[Ytr_cat_resample.index] /usr/local/lib/python3.5/dist-packages/scipy/sparse/csr.py in __getitem__(self, key) 348 csr_sample_values(self.shape[0], self.shape[1], 349 self.indptr, self.indices, self.data, --&gt; 350 num_samples, row.ravel(), col.ravel(), val) 351 if row.ndim == 1: 352 # row and col are 1d ValueError: could not convert integer scalar Following this thread I checked that the biggest element in the index wouldn't be bigger than the number of rows in my sparse matrix. The problem seems to come from the fact that the index is coded in np.int64 and not in np.int32. Indeed the following works: Xtr_resample = tfsnp.int32(ind) for ind in Ytr_resample.index Therefore I have two questions: Is the error actually coming from this conversion int32 to int64? Is there a more pythonic way to convert the index type? (Ytr_resample.index.astype(np.int32) does not seem to change the type for some reason) EDIT: Ytr_resample.index is of type pandas.core.indexes.numeric.Int64Index: Int64Index([1484, 753, 1587, 1494, 357, 1484, 84, 823, 424, 424, ... 1558, 1619, 1317, 1635, 537, 1206, 1152, 1635, 1206, 131], dtype='int64', length=4840) I created Ytr_resample by resampling Ytr (which is pandas.Series) such that every category present in Ytr has the same number of elements (by oversampling): n_samples = Ytr.value_counts(dropna = False).ma…
downvote count: 0
has title: ValueError: could not convert integer scalar in scipy indexing
favorite count: 0
tagged with: python
linked to: http://stackoverflow.com/q/29168699
answer count: 0
type: UnansweredQuestion
score: 1
upvote count: 1
tagged with: scipy

http://stackoverflow.com/comment/91008652
comment on: http://stackoverflow.com/a/52021168
score: 0
has text: @JoeIddon Sorry if there's anything vague or confusing in my previous comment. It's 4:35AM here, and I may not be thinking straight. ;)
type: AnswerComment
type: Comment

user-interface
tags question: http://stackoverflow.com/q/52073973
tags question: http://stackoverflow.com/q/52085966
tags question: http://stackoverflow.com/q/52020472
tags question: http://stackoverflow.com/q/52022264
type: Tag
tags question: http://stackoverflow.com/q/52031267
tags question: http://stackoverflow.com/q/51991748
tags question: http://stackoverflow.com/q/52057446
tag name: user-interface
tags question: http://stackoverflow.com/q/52054584

http://stackoverflow.com/a/51987953
has body: number_of_pages seems to have the value of 10. Find another way to find out how many pages there are. You can use a while loop that checks if the "next page" button is available, and if it is, keep going, else- that is the last page. like this: while next_button_element.is_displayed(): // Do the action that is currently in the for loop
type: Answer
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/90925959
has comment: http://stackoverflow.com/comment/90925990
has comment: http://stackoverflow.com/comment/90926342
has comment: http://stackoverflow.com/comment/90925853
upvote count: 1
answers question: http://stackoverflow.com/q/51987761

http://stackoverflow.com/q/52016352
has answer: http://stackoverflow.com/a/52016388
tagged with: python-3.x
type: Question
tagged with: python
has answer: http://stackoverflow.com/a/52016410
has title: creating amazon ec2 instance can't assign to operator error boto3
score: 0
answer count: 2
accepted answer: http://stackoverflow.com/a/52016410
tagged with: boto3
has body: I am trying to create 2 instances of linux on amazon ec2 there is one instance which I am starting in script import sys import boto3 instance_id = "i-03e7f6391a0f523ee" action = 'ON' ec2 = boto3.client('ec2') if action == 'ON': response = ec2.start_instances(InstanceIds=[instance_id], DryRun=False) x2=boto3.resource('ec2') instance=x2.Instance(instance_id) foo=instance.wait_until_running('self',Filters=[{'Name':'instance-state-name','Values':['running']}]) print ("instance is now running") else: response = ec2.stop_instances(InstanceIds=[instance_id], DryRun=False) print(response) ec2 = boto3.resource('ec2', region_name="ap-south-1") ami-ImageId="ami-00b6a8a2bd28daf19" #creating instances ec2.create_instances(ImageId=ami-ImageId,MinCount=1,MaxCount=2,KeyName="datastructutre key",InstanceType="t2.micro") #using filter to retrive instance status instances = ec2.instances.filter(Filters=[{'Name': 'instance-state-name', 'Values': ['running']}]) for instance in instances: print(instance.id, instance.instance_type) #Checking health status of instances for status in ec2.meta.client.describe_instance_status()['InstanceStatuses']: print(status) However this line ami-ImageId="ami-00b6a8a2bd28daf19" is giving me errors instead of double quotes I have also tried single quotes ami-ImageId='ami-00b6a8a2bd28daf19' but in both the cases error is same, the error is Syntax error: can't assign to operator What is the mistake in assigning ami-id in this way? It is normal string being assigned to a variable.
tagged with: amazon-web-services
type: AnsweredQuestion
tagged with: amazon-ec2
possible better answer: http://stackoverflow.com/a/52016388

http://stackoverflow.com/q/52027756
type: Question
tagged with: anaconda
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/91006788
type: UnansweredQuestion
has title: How do I install GeckoDriver if I am using Anaconda Navigator?
tagged with: geckodriver
tagged with: python
has body: I use anaconda navigator, and I am wondering where I put the GeckoDriver.exe file once I have downloaded it. I am using this for selenium. At the moment I have installed GeckoDriver and put it in the Anaconda folder, but I am getting the below error. CODE: from selenium import webdriver ERROR: ImportError: cannot import name 'webdriver'
score: 2
answer count: 0
upvote count: 2

http://stackoverflow.com/comment/90994947
type: QuestionComment
score: 0
has text: Edit your question to include the exact definition of `hint`, and the exact output you get from the print.
type: Comment
comment on: http://stackoverflow.com/q/52022301

http://stackoverflow.com/a/52004683
has comment: http://stackoverflow.com/comment/90979274
accepted answer of: http://stackoverflow.com/q/52004386
type: Answer
answers question: http://stackoverflow.com/q/52004386
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/90962604
has comment: http://stackoverflow.com/comment/90980774
has comment: http://stackoverflow.com/comment/90962561
has body: This is how I would solve it. The key part is sorting the list by length so a department will always come after it's company so we can add companies to the results dict before encountering any of their departments. We can then look through the companies to see if any is the company of our current company (or department) and add it to that entry if it is a department, or add it as a key if it is the company. with open(json_file_name) as f_in: companies_raw_data = json.load(f_in) companies = sorted(set(companies_raw_data), key=len) results = {} for company in companies: for key in results: if company.startswith(key): # is a department results[key].append(company) break else: # no break -- is not a department results[company] = [] It's probably more efficient, but less obvious, if you make the loop this instead: results = {} for company in companies: for i in range(len(company) - 1, 0, -1): key = company[:i] # substring if key in results: results[key].append(company) break else: # no break -- is not a department results[company] = []
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/91012014
comment on: http://stackoverflow.com/a/52030731
type: AnswerComment
score: 0
type: Comment
has text: Yes this won't yield results. I'm not sure what the neatest solution is for a threaded generator, but you could hack something together by splitting your list into batches (of size 2), threading the processing of those batches, and then yielding the results before the next batch is processed. Then you would get 2 out at a time.

http://stackoverflow.com/q/51966962
type: AnsweredQuestion
has title: Getting "Library not loaded: libssl.1.0.0.dylib", "Reason: image not found" with flask_mysqldb
has comment: http://stackoverflow.com/comment/90884765
has comment: http://stackoverflow.com/comment/90886310
upvote count: 5
has answer: http://stackoverflow.com/a/62282761
has body: I'm trying out Python 3 with Flask and I'm stuck with the following error while working with databases. I'm doing this on macOS High Sierra v. 10.13.6 My import code is as follows: from flask import Flask, render_template, flash, redirect, url_for, session, request, logging from data import Articles from flask_mysqldb import MySQL from wtforms import Form, StringField, TextAreaField, PasswordFeild, validators from passlib.hash import sha256_crypt The error I get when trying to run the app, is the following: Traceback (most recent call last): File "app.py", line 3, in &lt;module&gt; from flask_mysqldb import MySQL File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site- packages/flask_mysqldb/__init__.py", line 1, in &lt;module&gt; import MySQLdb File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site- packages/MySQLdb/__init__.py", line 18, in &lt;module&gt; import _mysql ImportError: dlopen(/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site- packages/_mysql.cpython-37m-darwin.so, 2): Library not loaded: libssl.1.0.0.dylib Referenced from: /Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site- packages/_mysql.cpython-37m-darwin.so Reason: image not found I've looked around in multiple other questions related to mine, but couldn't seem to find anything to solve my problem with. Or at least I didn't know how. I really hope someone can help me out.
has comment: http://stackoverflow.com/comment/90886430
has comment: http://stackoverflow.com/comment/90886414
has comment: http://stackoverflow.com/comment/90886739
type: Question
has comment: http://stackoverflow.com/comment/90886744
score: 5
has answer: http://stackoverflow.com/a/56928895
downvote count: 0
answer count: 6
favorite count: 0
has comment: http://stackoverflow.com/comment/90884935
has answer: http://stackoverflow.com/a/63959953
possible better answer: http://stackoverflow.com/a/56928895
has comment: http://stackoverflow.com/comment/90886150
tagged with: mysql-python
tagged with: python
tagged with: macos
has comment: http://stackoverflow.com/comment/90886265
has comment: http://stackoverflow.com/comment/90886256
has comment: http://stackoverflow.com/comment/90886684
has comment: http://stackoverflow.com/comment/90884666
has comment: http://stackoverflow.com/comment/90884863
tagged with: python-3.x
tagged with: flask-mysql
has comment: http://stackoverflow.com/comment/90885934
has answer: http://stackoverflow.com/a/51985026
has comment: http://stackoverflow.com/comment/90886463
has comment: http://stackoverflow.com/comment/90886391
has comment: http://stackoverflow.com/comment/90885998
has answer: http://stackoverflow.com/a/57795454
has answer: http://stackoverflow.com/a/60556593
accepted answer: http://stackoverflow.com/a/51985026
linked to: http://stackoverflow.com/q/6383310

http://stackoverflow.com/comment/90958575
comment on: http://stackoverflow.com/a/52002491
has text: that exactly what it says: look for an error, make changes and learn from your mistakes. you could'nt have phrase it more perfectly!
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/q/52106861
upvote count: 2
answer count: 2
has answer: http://stackoverflow.com/a/77922272
tagged with: sms-verification
has answer: http://stackoverflow.com/a/52124085
favorite count: 0
tagged with: sms
type: UnansweredQuestion
has body: I'm writing a Python script to do some web automation stuff. In order to log in the website, I have to give it my phone number and the website will send out an SMS verification code. Is there a way to get this code so that I can use it in my Python program? Right now what I can think of is that I can write an Android APP and it will be triggered once there are new SMS and it will get the code and invoke an API so that the code will be stored somewhere. Then I can grab the stored code from within my Python program. This is doable but a little bit hard for me as I don't know how to develop a mobile APP. I want to know is there any other methods so that I can get this code? Thanks. BTW, I have to use my own phone number and can't use other phone to receive the verification code. So it may not possible to use some services.
tagged with: python
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/91164670
type: Question
tagged with: automation
has title: How can I get SMS verification code in my Python program?
has comment: http://stackoverflow.com/comment/91164713

http://stackoverflow.com/comment/91660181
score: 0
type: QuestionComment
has text: Sorry for not getting back to you, your response was perfect. Thanks for your help!
type: Comment
comment on: http://stackoverflow.com/q/52058944

http://stackoverflow.com/q/52082682
has answer: http://stackoverflow.com/a/52083120
has title: Is it right to run crontab service and wsgi within a single docker container
type: Question
has body: Currently, I have a Django wsgi to handle web traffic. (I have a nginx as front end to forward traffic to wsgi) Now, I would like to start a crobtab service, to run periodic background job. This is what I had done django\Dockerfile FROM python:3.6.4-alpine3.4 ... RUN chmod +x entrypoint.sh ENTRYPOINT ["sh", "entrypoint.sh"] CMD /usr/local/bin/gunicorn web.wsgi:application -b django:5000 --log-level=info --error-logfile=/var/log/gunicorn3.err.log django\entrypoint.sh #!/bin/sh ... python manage.py crontab add # https://stackoverflow.com/questions/37015624/how-to-run-a-cron-job-inside-a-docker-container # # "crond -help" yields: # # -f Foreground # -b Background (default) # -S Log to syslog (default) # -l N Set log level. Most verbose:0, default:8 # -d N Set log level, log to stderr # -L FILE Log to FILE # -c DIR Cron dir. Default:/var/spool/cron/crontabs # start cron /usr/sbin/crond -f -l 8 exec "$@" docker-compose.yml django: build: context: ./django dockerfile: Dockerfile restart: always depends_on: - pgbouncer expose: - "5000" volumes: - static_data:/app/static If I use the above setup, I notice that. My schedule cron worker is running periodically. But, wsgi unable to serve web traffic. First, I try to change in django\entrypoint.sh # start cron /usr/sbin/crond -f -l 8 to # start cron /usr/sbin/crond -b -l 8 After making above change, My schedule cron worker is no longer running. Not sure why. wsgi can serve web traffic. May I know why is it so? How can I make my django container to serve web traffic, and run cron job at the same time? Or, is it not the right way to do such thing in Docker? I should use 2 containers?
tagged with: docker
score: 0
linked to: http://stackoverflow.com/q/37015624
answer count: 1
type: UnansweredQuestion
tagged with: django
tagged with: python

http://stackoverflow.com/comment/90932768
type: QuestionComment
score: 1
has text: You should create your tables and map your classes only once and make it so that their metadata is not bound directly to the engine. Then it's a simple matter of just swapping the engine.
comment on: http://stackoverflow.com/q/51990714
type: Comment

http://stackoverflow.com/comment/98113748
has text: I have a similar error in Pycharm when trying to import matplotlib.pyplot
score: 0
comment on: http://stackoverflow.com/q/52074241
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52096420
downvote count: 2
has answer: http://stackoverflow.com/a/52096572
type: Question
has comment: http://stackoverflow.com/comment/91143266
tagged with: file-rename
tagged with: rename
upvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/91142970
favorite count: 0
linked to: http://stackoverflow.com/q/225735
has body: I have a list of file like the following 'TRIAL_20134_75690_TOTAL_2018-08-12-17-18.csv' I want to rename them the parte after the last underscore, such as the file will be renamed like: 'TRIAL_20134_75690_TOTAL.csv'
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91143152
tagged with: python
score: -2
has title: Python: how to rename a file in a folder?

http://stackoverflow.com/q/52052295
tagged with: range
has comment: http://stackoverflow.com/comment/91054804
tagged with: python
has title: Convert a sorted list of numbers like [1,2,3,4] to a string specifying range like "1-4" in python
favorite count: 0
has answer: http://stackoverflow.com/a/52052534
has answer: http://stackoverflow.com/a/52052751
downvote count: 2
possible better answer: http://stackoverflow.com/a/52052534
has body: I have a problem in python. I have a sorted list of numbers like [1,2,3,4,5]. I need to get a string specifying the range like "1-5" if the sorted numbers are in series or continuous. Thanks Girish
type: AnsweredQuestion
tagged with: list
accepted answer: http://stackoverflow.com/a/52052431
upvote count: 3
score: 1
type: Question
has comment: http://stackoverflow.com/comment/91054794
has comment: http://stackoverflow.com/comment/91055056
answer count: 3
has answer: http://stackoverflow.com/a/52052431

http://stackoverflow.com/comment/91034452
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52027932
has text: Have the answers on this post been helpful? in that case it would be nice if you could mark the answer as correct, if not i will come back later tonight and see what i can do :)
score: 0

http://stackoverflow.com/comment/91107539
comment on: http://stackoverflow.com/a/52078763
type: Comment
score: 2
has text: or `dict.get(key, default)` though in a long chain like this that will be easier when we have None coalescing operators https://www.python.org/dev/peps/pep-0505/
type: AnswerComment

http://stackoverflow.com/comment/91082353
has text: Yes I mean a simple csv will be like 30GB in the end :-)
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/52046078

http://stackoverflow.com/q/52083373
type: Question
has comment: http://stackoverflow.com/comment/91117115
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/91117076
score: 0
answer count: 1
has title: strange graph while plotting two columns of a DataFrame
has answer: http://stackoverflow.com/a/52083504
tagged with: python
has body: I am relatively new to python. I am trying to plot a line using two columns of a Dataframe using .plot in Matplotlib. Here is the code I used - a = testdata['x_pred'] b = testdata['y'] plt.plot(a,b) The DataFrame testdata has only two columns - x_pred and y. I was expecting a smooth line graph, however the graph I am getting seems to be connecting each point with every other point. Can't understand why. Would appreciate any help to get a simple line graph as my output. Here is the plot I got
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91117179
has comment: http://stackoverflow.com/comment/91117338
accepted answer: http://stackoverflow.com/a/52083504

http://stackoverflow.com/q/52098568
type: Question
has answer: http://stackoverflow.com/a/52098749
tagged with: dataframe
has body: Say I have a dataframe like this: x y z class 1 2 3 0 2 2 3 0 1 4 5 2 3 2 2 1 I would like to assign each class a different color value (RGB). So I need to insert three columns right after column z based on the class: x y z r g b class 1 2 3 255 254 253 0 2 2 3 255 254 253 0 1 4 5 0 255 0 2 3 2 2 0 0 255 1 Currently I am doing it like this: # insert three columns df['r']=0 df['g']=0 df['b']=0 # replace r/g/b values based on `class` def colorit(dataframe): colors = [[255, 254, 253], [0, 0, 255], [0, 255, 0]] for i in range(3): dataframe.loc[dataframe['c']==i, 'r'] = colors[i][0] dataframe.loc[dataframe['c']==i, 'g'] = colors[i][1] dataframe.loc[dataframe['c']==i, 'b'] = colors[i][2] But I think there should be some way to make use of the apply or map method or something like that to have this done more elegantly and efficiently (with less code and no loops).
answer count: 3
tagged with: pandas
score: 2
downvote count: 0
favorite count: 0
accepted answer: http://stackoverflow.com/a/52098749
tagged with: python
has title: Pandas conditional creation of multi columns
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52098706
upvote count: 2
possible better answer: http://stackoverflow.com/a/52098643
has answer: http://stackoverflow.com/a/52098643

http://stackoverflow.com/comment/90932245
has text: There are indeed Python packages for MSYS2 so maybe you should try just using the tools provided by MSYS2 instead of trying to integrate with third-party tools which might have been compiled with incompatible toolchains.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51981570

http://stackoverflow.com/comment/91094187
has text: It's still not working when I push to heroku. Should I make some change based on the following stricpt? remote: File "/tmp/pip-build-t_7e9for/MySQL-python/setup_posix.py", line 2, in <module> remote: from ConfigParser import SafeConfigParser remote: ModuleNotFoundError: No module named 'ConfigParser'
type: Comment
comment on: http://stackoverflow.com/a/52071147
score: 0
type: AnswerComment

http://stackoverflow.com/comment/90871966
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51960790
has text: In list m, [1] and [2] point to the same location as [0], and will change as [0] changes. In list n, they are copies, that change seperate from each other.
score: 0

http://stackoverflow.com/comment/90946712
has text: Does your script log to a file or to stdout/stderr?
score: 0
comment on: http://stackoverflow.com/q/51998753
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52096046
has title: Scaling data (MinMaxScaler and StandardScaler) before passing it into recurrent neural network and its effect on the output
has comment: http://stackoverflow.com/comment/91142674
has comment: http://stackoverflow.com/comment/91142546
downvote count: 0
has comment: http://stackoverflow.com/comment/91142918
score: 1
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion
tagged with: python
answer count: 0
tagged with: recurrent-neural-network
upvote count: 1
has body: I have a time series with values in range &lt;0, 1000> and I made three experiments. in the first one I was passing original values into RNN in the second one I use MinMaxScaler() with default range of 0-1 in the third one i used StandardScaler() I noticed strange anomaly when RNN was to predict series of zeros in my time series. With original data it did it correctly and i expected similar behavior during another experiments but instead,predictions were much worse. Below images representing results of three experiments (red - predicted, black - real): unchanged dataset MinMaxScaler() used StandardScaler() used We can observe huge difference in zero values. I expected similar results not matter if I use scaling or not. Why is it so? Could anyone explain how method of scalling can affect neural network performance? I want to add second channel (with binary values) and I need to scale it somehow. How to deal with it?
has comment: http://stackoverflow.com/comment/91142252
tagged with: tensorflow
type: Question

http://stackoverflow.com/q/52098146
type: Question
has comment: http://stackoverflow.com/comment/91223395
score: 10
tagged with: optimization
has comment: http://stackoverflow.com/comment/120371211
answer count: 2
has comment: http://stackoverflow.com/comment/120417476
favorite count: 0
has body: for my constrained Problem I want to use the Scipy-Trusted-Constr algorithm as I have a multivariable, constraint problem. I dont want /can't calculate the Jacobi/Hessian analytically, and compute it. However, when setting the bounds, the computation of the Jacobian crashes: File "C:\Python27\lib\site-packages\scipy\optimize\_trustregion_constr\tr_interior_point.py", line 56, in __init__ self.jac0 = self._compute_jacobian(jac_eq0, jac_ineq0, s0) File "C:\Python27\lib\site-packages\scipy\optimize\_trustregion_constr\tr_interior_point.py", line 164, in _compute_jacobian [J_ineq, S]])) File "C:\Python27\lib\site-packages\numpy\matrixlib\defmatrix.py", line 1237, in bmat arr_rows.append(concatenate(row, axis=-1)) ValueError: all the input array dimensions except for the concatenation axis must match exactly The error occurs both when using old style bounds and the newest Bounds object. I could reproduce the error with this code: import numpy as np import scipy.optimize as scopt def RosenbrockN(x): result = 0 for i in range(len(x)-1): result += 100*(x[i+1]-x[i]**2)**2+(1-x[i])**2 return result x0 = [0.0, 0.0, 0.0] #bounds = scopt.Bounds([-2.0,-0.5,-2.0],[2.0,0.8,0.7]) bounds = [(-2.0,2.0),(-0.5,0.8),(-2.0,0.7)] Res = scopt.minimize(RosenbrockN, x0, \ method = 'trust-constr', bounds = bounds, \ jac = '2-point', hess = scopt.SR1()) I take it that I just misunderstand how bounds are set, but cant find my mistake. Advice is appreciated. EDIT: I also tried the code example from the documentation which gave the same result. Other methods as SLSQP work well with bounds. SciPy Version 1.1.0, Python Version 2.7.4, OS Win 7 Ent.
has answer: http://stackoverflow.com/a/57634456
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91250415
upvote count: 10
tagged with: python
has comment: http://stackoverflow.com/comment/120416184
downvote count: 0
has answer: http://stackoverflow.com/a/74799041
has title: Scipy: How can I use Bounds with trust-constr?
tagged with: scipy

http://stackoverflow.com/a/52017542
type: Answer
has comment: http://stackoverflow.com/comment/90985165
answers question: http://stackoverflow.com/q/52017434
score: 0
has body: The use of os.path.exists is redundant for your purpose because you can simply catch the FileExistsError exception from os.mkdir instead if the target directory/file does already exist: for hc in list: try: os.mkdir('InputData/'+str(hc)) except FileExistsError: pass It would also help eliminate the possibility of a race condition if you ever run several threads or processes of this code block.

http://stackoverflow.com/q/52020413
has comment: http://stackoverflow.com/comment/90991244
has comment: http://stackoverflow.com/comment/90991189
upvote count: 1
type: Question
possible better answer: http://stackoverflow.com/a/52020614
has answer: http://stackoverflow.com/a/52020614
score: 1
has title: Characters formatting in Python
has comment: http://stackoverflow.com/comment/90991261
has comment: http://stackoverflow.com/comment/90991278
has answer: http://stackoverflow.com/a/52020583
answer count: 2
downvote count: 0
favorite count: 0
tagged with: tuples
tagged with: python
accepted answer: http://stackoverflow.com/a/52020583
type: AnsweredQuestion
tagged with: list
has body: I'm beginner to Python ... I'd like to format the characters in Python using basic concepts and operations of Tuples and Lists as below ... I enter 10 digit number and except last 4 digits remaining all the numbers should be replaced by 'X'. For e.g. number = 1234567890 Expecting output as - number = XXXXXX7890 How to mask entered characters / numbers in Python using Tuples/Lists concept not using by importing any modules or existing high functions. Is it possible ? For e.g. entered some characters , those should be masked using * (asterisk) or # (hashed) while entering. For e.g. password : pa55w0rd Expecting output while entering password as - password : ******** OR password: ########

http://stackoverflow.com/q/52049188
score: 0
has answer: http://stackoverflow.com/a/52049303
accepted answer: http://stackoverflow.com/a/52049303
answer count: 1
tagged with: python
has title: python/dataframe - groupby columns to create a list
type: AnsweredQuestion
has body: I'm trying to use dataframe to transform data: Column 1 | Column 2 | Column 3 | Column 4 -------------------------------- A | B | 1 | # A | B | 2 | $ A | C | 1 | % into Column 1 | Column 2 | Column 5 -------------------------------- A | B | [Column 3: 1, Column 4:#, Column 3:2, Column 4:$] A | C | [Column 3: 1, Column 4:%] Can someone please help?
type: Question
tagged with: apache-spark-sql

http://stackoverflow.com/a/52101527
answers question: http://stackoverflow.com/q/52101264
has comment: http://stackoverflow.com/comment/91154466
upvote count: 2
type: Answer
has comment: http://stackoverflow.com/comment/91154621
score: 2
has body: You can do this using itertools.combinations like so: from itertools import combinations options = { 'Type': ['Breakfast', 'Brunch', 'Lunch', 'Dinner'], 'Cutlery': ['Knife', 'Fork'], 'IsWeekend' : ['True', 'False'], 'FoodTypes' : ['Sausage', 'Bacon', 'Eggs', 'Toast'] } # get a list of all the dictionary's values lst = [j for i in options.values() for j in i] for i in range(len(lst)+1): for s in combinations(lst, i): print(s) Note: This solution computes all 2^12 combinations of the flattened list of dictionary's values and works supposing that the dictionary doesn't contain duplicate items in its values. If there are duplicates, before you enter the for loops you can easily remove them e.g. using sets.
downvote count: 0

http://stackoverflow.com/q/52020221
favorite count: 0
tagged with: django-wsgi
has answer: http://stackoverflow.com/a/52098017
accepted answer: http://stackoverflow.com/a/52098017
tagged with: python
has body: I'm trying to deploy a Django app on CentOS + Apache with mod_wsgi. The app is working fine with Django dev server (manage.py runserver) but not when serving through Apache. This is all I get in logs: [core:error] [pid 10696] [client &lt;IP&gt;:35768] Script timed out before returning headers: wsgi.py Here's my virtual host config for the domain (The same is working fine for my other projects): ServerName subdomain.domain.com ServerAlias another.subdomain.domain.com DocumentRoot /var/www/path/to/root ErrorLog /var/www/path/to/logs/error.log CustomLog /var/www/path/to/logs/requests.log combined WSGIScriptAlias / /var/www/path/to/root/app/wsgi.py WSGIDaemonProcess pname python-path=/var/www/path/to/root python-home=/var/www/path/to/root/venv home=/var/www/path/to/root WSGIPassAuthorization On WSGIProcessGroup pname WSGIApplicationGroup %{GLOBAL} &lt;Directory /var/www/path/to/root/app&gt; &lt;Files wsgi.py&gt; Require all granted &lt;/Files&gt; &lt;/Directory&gt; Any help is appreciated. Can't seem to find out any way to get a more verbose error message either. PS: It might seem like a duplicate question, but it's not. I've looked into all other similar questions but none of the mentioned solutions help.
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90991073
downvote count: 0
tagged with: mod-wsgi
tagged with: django
has comment: http://stackoverflow.com/comment/90991106
type: Question
has title: Django + Apache - [core:error] [pid 10696] [client <IP>:35768] Script timed out before returning headers: wsgi.py
score: 1
upvote count: 1
tagged with: apache
answer count: 1

http://stackoverflow.com/comment/91040359
score: 0
type: Comment
type: QuestionComment
has text: Possible duplicate of [Unescaping HTML with special characters in Python 2.7.3 / Raspberry Pi](https://stackoverflow.com/questions/21342549/unescaping-html-with-special-characters-in-python-2-7-3-raspberry-pi)
comment on: http://stackoverflow.com/q/52034523

http://stackoverflow.com/comment/91105210
score: 0
comment on: http://stackoverflow.com/q/52077632
type: Comment
type: QuestionComment
has text: @MartijnPieters Is that better :) ?

http://stackoverflow.com/comment/90991073
type: QuestionComment
has text: Your django view is too slow.
comment on: http://stackoverflow.com/q/52020221
score: 0
type: Comment

http://stackoverflow.com/a/51966896
type: AcceptedAnswer
score: 4
type: Answer
has comment: http://stackoverflow.com/comment/90884012
downvote count: 0
has comment: http://stackoverflow.com/comment/90884205
upvote count: 4
has body: Depends on what you mean "fails". A possibility would be N=0 while True: N = N+10 try: simulation(N) except SomeError: pass else: break That means call the simulations if it goes wrong (except) go to the next iteration (with pass) if it succeeds (else) stop the loop Take note that else in python can be used with try and for, but has totally different meaning than the if-else which appears in every language.
accepted answer of: http://stackoverflow.com/q/51966845
answers question: http://stackoverflow.com/q/51966845

http://stackoverflow.com/q/52087426
score: 0
answer count: 1
tagged with: excel
has body: I'm new to Python and there is a piece of Python coding that I am having trouble getting to graph. Specifically how to parse data from an Excel spreadsheet in order to generate and plot some basic value comparison graphs. I'm using the Spyder IDE with Python 3.6.3. The file 'foc' location is: C:\Users\Murphy\Desktop\WinPython-64bit-3.6.3.0Qt5\PYWorkFiles\foc.csv I have more than one version of the excel spreadsheet foc file as I have attempted to graph it in more than one format. The two formats it is stored in at present are csv and xlsx The code scraps I have put together at present are: import xlrd workbook = xlrd.open_workbook('foc.xlsx') from csv import reader import matplotlib.pyplot as plt with open('foc.csv', 'r') as f: data = list(reader(f)) taste = [i[6] for i in data] plt.plot(range(len(taste)), taste) plt.show() plt.plot() All these pieces of code generate is two useless graphs (I've attached them below) with only the first one even showing any of the foc spreadsheet data. Can I get any help with this? I have very little knowledge of how to use Python. graph1 graph2
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/52087735
type: Question
has title: plotting/graphing excel file data using python
tagged with: http://stackoverflow.com/tag/csv
tagged with: python

http://stackoverflow.com/comment/91073845
comment on: http://stackoverflow.com/q/52060555
type: QuestionComment
type: Comment
has text: Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/178945/discussion-between-zahra-bokaee-and-jeremy-blain).
score: 0

http://stackoverflow.com/a/52035033
has comment: http://stackoverflow.com/comment/91020328
downvote count: 0
score: 4
upvote count: 4
has comment: http://stackoverflow.com/comment/91020197
has body: Would you want just a way of figuring out what kind of bogus data you have? If so, this is enough. df.index[df.index.str[0].notna()] Index(['a'], dtype='object') Assuming you have string entries, anything that is not a string will show up as NaN. If you want to get rid of invalid data, then try coercing it to float, and get rid of NaN rows. m = pd.to_numeric(df.index, errors='coerce').notna() #.notnull() df[m] a b 0.0 1 4 1.5 2 5
has comment: http://stackoverflow.com/comment/91020479
has comment: http://stackoverflow.com/comment/91020218
type: Answer
answers question: http://stackoverflow.com/q/52034957

http://stackoverflow.com/comment/91037096
has text: Apologies for not making the data list clear @Lorenz
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52042298

http://stackoverflow.com/comment/91154706
has text: So basically `object` is a predefined default base class. None of the info I was reading ever specifically stated that (to me). This question is a duplicate. After specifically searching for "python class object keyword" it came up with: https://stackoverflow.com/questions/4015417/python-class-inherits-object
comment on: http://stackoverflow.com/q/52070098
score: 0
type: Comment
type: QuestionComment

opencv3.0
tags question: http://stackoverflow.com/q/52065142
tags question: http://stackoverflow.com/q/52087533
type: Tag
tags question: http://stackoverflow.com/q/51974632
tags question: http://stackoverflow.com/q/51961068
tags question: http://stackoverflow.com/q/52041888
tag name: opencv3.0
tags question: http://stackoverflow.com/q/52099151

http://stackoverflow.com/q/51994117
type: AnsweredQuestion
has title: Applying transformation and concatenating multiple columns from an existing dataframe to form a new dataframe in Pandas
accepted answer: http://stackoverflow.com/a/51994230
downvote count: 0
score: 1
favorite count: 0
type: Question
tagged with: pandas
answer count: 2
has answer: http://stackoverflow.com/a/51994248
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/51994230
possible better answer: http://stackoverflow.com/a/51994248
has body: Suppose I have a dataframe like below: import pandas as pd df1 = pd.DataFrame({ 'A' : ['foo ', 'b,ar', 'fo...o', 'bar', 'foo', 'bar', 'foo', 'foo'], 'B' : ['one', 'one', 'two', 'three','two', 'two', 'one', 'three'], }) I want to create a new dataframe, df2, that is a concatenated form of column 'A' and 'B' in df1 where each data is uppercased. This is a toy example, and in my use case, I may also have more than the column 'A' and 'B', so I'd like to make the list of columns variable (that is, the names of the column can vary). def tokenize(s): # replaces comma with space; removes non-alphanumeric chars; etc. return re.sub('[^0-9a-zA-Z\s]+', '', re.sub('[,]+', ' ', s)).lower().split() df2 = pd.DataFrame() # create a new dataframe; not sure if I'm doing this right cols_to_concat = ['A','B'] # there can be more than two columns in this list for col in cols_to_concat: df2 = df1[col].apply(tokenize).apply(str.upper) print(df2) # here, I'd like the df2 to have just ONE column whose rows are 'FOOONE', 'BARONE', 'FOOTWO', 'BARTHREE','FOOTWO', 'BARTWO','FOOONE','FOOTHREE',...
tagged with: dataframe

http://stackoverflow.com/a/51966352
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/51966167
upvote count: 1
has body: You can use zip to iterate elements for a and b in pairs, create a 2 element list based on whether a's element or b's element is greater and then sum the result &gt;&gt;&gt; a = [1,2,3] &gt;&gt;&gt; b = [3,2,1] &gt;&gt;&gt; list(map(sum, (zip(*((x&gt;y, y&gt;x) for x,y in zip(a,b)))))) [1, 1]
score: 1

http://stackoverflow.com/comment/91043727
score: 0
has text: Thanks for the quick answer. What would be the best alternative way to write an object that has many different forms with special methods? A "type" variable and then if else?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52046224

http://stackoverflow.com/q/52020785
type: AnsweredQuestion
score: 3
upvote count: 3
type: Question
tagged with: heroku
has body: I am trying to host a bottle app that uses tensorflow to heroku, the app starts and I got the 'server running on port' as well. but the application is not opening and after a minute or so, it showing a the below trace Opening trace saying the server is running successfully, 2018-08-25T19:46:55.651043+00:00 heroku[web.1]: Starting process with command `python ./api.py -p 37040` 2018-08-25T19:47:01.379243+00:00 app[web.1]: Bottle v0.12.13 server starting up (using WSGIRefServer())... 2018-08-25T19:47:01.379274+00:00 app[web.1]: Listening on http://127.0.0.1:8080/ 2018-08-25T19:47:01.379309+00:00 app[web.1]: Hit Ctrl-C to quit. 2018-08-25T19:47:01.379318+00:00 app[web.1]:undefined After few minutes after. error trace. 2018-08-25T19:47:56.239318+00:00 heroku[web.1]: Error R10 (Boot timeout) -&gt; Web process failed to bind to $PORT within 60 seconds of launch 2018-08-25T19:47:56.239392+00:00 heroku[web.1]: Stopping process with SIGKILL 2018-08-25T19:47:56.330436+00:00 heroku[web.1]: Process exited with status 137 2018-08-25T19:47:56.353021+00:00 heroku[web.1]: State changed from starting to crashed 2018-08-25T19:47:59.452460+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=boiling-forest-70642.herokuapp.com request_id=8b62b91c-8f22-4c37-b3c5-cbc7e8415e3d fwd="123.231.104.11" dyno= connect= service= status=503 bytes= protocol=https 2018-08-25T19:47:59.500660+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/robots.txt" host=boiling-forest-70642.herokuapp.com request_id=e8860f29-40fd-46b1-b9f2-96683f53d524 fwd="123.231.104.11" dyno= connect= service= status=503 bytes= protocol=https 2018-08-25T19:48:02.118233+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=boiling-forest-70642.herokuapp.com request_id=1f9aafbe-f410-46ab-84ed-41bbc90857e6 fwd="123.231.104.11" dyno= connect= service= status=503 bytes= protocol=https I don't know what I have done wrong, since I am new…
downvote count: 0
has answer: http://stackoverflow.com/a/52119850
answer count: 1
has title: Heroku: Error R10 (Boot timeout) -> Web process failed to bind to $PORT within 60 seconds of launch - Python
favorite count: 0
accepted answer: http://stackoverflow.com/a/52119850
tagged with: python
tagged with: bottle
tagged with: deployment

http://stackoverflow.com/q/52015855
has answer: http://stackoverflow.com/a/52034462
type: AnsweredQuestion
has body: I am trying to setup my machine learning environment on AWS as follows :- OS: windows server 2012 r2 , 64 bit instance: p2.xlarge GPU : Tesla K80 series CUDA: 9.2.148 Graphis driver: 398.26 (installed by cuda toolkit) python : 3.5 ( tested using 2.7.15 as well) ,64 bit IDE: Pycharm Community 2018.2, 64 bit mxnet librabry: mxnet-cu92 now when I run following code : import mxnet as mx from mxnet import nd mx.random.seed(1) z = nd.ones(shape=(3,3), ctx=mx.cpu()) print(z) it works fine , but when I change ctx=mx.gpu() or ctx=mx.gpu(0) , I get error python stopped working. cuda setup is working fine I compiled and ran deviceQuery , bandwidthTest sample application, these are giving output as expected. EDIT:: python crash details gives me following information : Fault Module Name: ucrtbase.DLL I tried with Cuda Graphis driver: 398.44 (recommended from cuda website for my gpu and os ) still no luck so far. Any idea for resolving this issue?
downvote count: 1
type: Question
accepted answer: http://stackoverflow.com/a/52034462
tagged with: mxnet
score: -1
tagged with: amazon-web-services
has title: Python Stopped Working on switiching to GPU context
upvote count: 0
answer count: 1
favorite count: 0
tagged with: gpu
tagged with: python

http://stackoverflow.com/comment/90937180
has text: Glad I could help! Remember to [upvote posts](https://stackoverflow.com/help/someone-answers) which you find helpful. Thanks!
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/51969877
score: 0

http://stackoverflow.com/q/52020536
has answer: http://stackoverflow.com/a/52052268
tagged with: opencv
has answer: http://stackoverflow.com/a/52052091
answer count: 4
has title: Python OCR: ignore signatures in documents
upvote count: 12
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/52045907
downvote count: 0
has answer: http://stackoverflow.com/a/52053062
tagged with: ocr
favorite count: 0
type: Question
has body: I'm trying to do OCR of a scanned document which has handwritten signatures in it. See the image below. My question is simple, is there a way to still extract the names of the people using OCR while ignoring the signatures? When I run Tesseract OCR it fails to retrieve the names. I tried grayscaling/blurring/thresholding, using the code below, but without luck. Any suggestions? image = cv2.imread(file_path) image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) image = cv2.GaussianBlur(image, (5, 5), 0) image = cv2.threshold(image, 0, 255, cv2.THRESH_BINARY_INV | cv2.THRESH_OTSU)[1]
linked to: http://stackoverflow.com/q/48623615
tagged with: python
score: 12
tagged with: image-processing
tagged with: machine-learning

http://stackoverflow.com/comment/91133202
type: AnswerComment
comment on: http://stackoverflow.com/a/52091498
has text: That unpacks the tuple and passes each element as seperate parameter. That is needed because range expects 3 integer arguments not one tuple containing 3 integers.
type: Comment
score: 1

http://stackoverflow.com/q/51968109
tagged with: python-requests
type: Question
has title: Jupyter requests.get returns incomplete html
has answer: http://stackoverflow.com/a/51968508
answer count: 1
downvote count: 0
tagged with: jupyter
favorite count: 0
tagged with: jupyter-notebook
has body: I run the below python code in Jupyter notebook, but return an incomplete html. import requests if __name__ == '__main__': target = 'http://www.biqukan.com/1_1094/5403177.html' req = requests.get(url=target) print(req.text) Then I run it in VS code, the return is complete html I want to know the reason, and how to return a complete html in Jupyter. Thanks.
has comment: http://stackoverflow.com/comment/90891527
has comment: http://stackoverflow.com/comment/90886437
type: UnansweredQuestion
tagged with: python
score: 1
upvote count: 1

http://stackoverflow.com/comment/91002942
comment on: http://stackoverflow.com/q/52026365
score: 0
type: Comment
has text: @wizzwizz4 sounds good :)
type: QuestionComment

http://stackoverflow.com/q/52086264
has body: First of, I'm aware of this, this and this post about two-dimensional pattern matching, these posts however all don't include wildcard matching. Furthermore, I know there are several papers such as this one that have solved the issue I'm facing. However, I'm only just getting familiar with pattern matching in two dimensional arrays and trying to implement the algorithms in the papers is non-trivial for me at the moment. Thus, the following problem is what I'm facing. Given a two dimensional array: [[1 3 4 5 3 3] [4 1 4 5 5 2] [5 4 3 4 4 2] # pattern [4 5 3 4 1 3] # pattern [3 3 3 4 4 4] # pattern [3 4 3 4 2 5] # pattern [4 5 3 4 1 2] # pattern [5 1 1 2 4 2] [2 1 3 2 1 5] [4 4 1 3 3 1] [1 4 3 4 4 1] [5 2 4 4 4 1]] And the following example pattern (where a ? would indicate the wildcard match): [[? ? 3 4 ? ?] [? ? 3 4 ? ?] [3 3 3 4 4 4] [? ? 3 4 ? ?] [? ? 3 4 ? ?]] How would a function be written that takes in the two dimensional array and the pattern, returning True if the pattern is present in the array or False if it is not? If possible a generalized solution to this problem would be highly appreciated, as there are numerous distinct patterns that I'm trying to match. If required I'm more than willing to provide additional examples.
has title: Two Dimensional Pattern Matching with Wildcards in Numpy Arrays
has comment: http://stackoverflow.com/comment/91125419
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/91136700
answer count: 2
has comment: http://stackoverflow.com/comment/91137193
tagged with: arrays
downvote count: 0
has comment: http://stackoverflow.com/comment/91136848
accepted answer: http://stackoverflow.com/a/52095255
has comment: http://stackoverflow.com/comment/91124487
favorite count: 0
has comment: http://stackoverflow.com/comment/91136004
has comment: http://stackoverflow.com/comment/91124367
has comment: http://stackoverflow.com/comment/91136985
possible better answer: http://stackoverflow.com/a/52094713
tagged with: python
score: 1
has answer: http://stackoverflow.com/a/52094713
linked to: http://stackoverflow.com/q/45960192
linked to: http://stackoverflow.com/q/32531377
upvote count: 1
has comment: http://stackoverflow.com/comment/91134575
has comment: http://stackoverflow.com/comment/91138272
has comment: http://stackoverflow.com/comment/91130467
has comment: http://stackoverflow.com/comment/91138630
has answer: http://stackoverflow.com/a/52095255
has comment: http://stackoverflow.com/comment/91125072
type: AnsweredQuestion

http://stackoverflow.com/a/51973446
answers question: http://stackoverflow.com/q/51973105
score: 0
has body: You can pickle (save into a file) your dictionary before exiting the program and then unpickle it when the program starts: import os.path, pickle SAVED = "mydict.p" if os.path.isfile(SAVED): with open(SAVED, "rb") as infile: mydict = pickle.load(infile) else: mydict = ... # Initialize the dictionary for the first time ... # Possibly change mydict here ... with open(SAVED, "wb") as outfile: pickle.dump(mydict, outfile)
type: Answer

sqlite
tags question: http://stackoverflow.com/q/52020450
tags question: http://stackoverflow.com/q/52018029
tags question: http://stackoverflow.com/q/51990726
tags question: http://stackoverflow.com/q/52015161
tags question: http://stackoverflow.com/q/51962466
tags question: http://stackoverflow.com/q/52041430
tags question: http://stackoverflow.com/q/52003091
type: Tag
tags question: http://stackoverflow.com/q/52085191
tags question: http://stackoverflow.com/q/52031620
tags question: http://stackoverflow.com/q/51970066
tags question: http://stackoverflow.com/q/51960796
tags question: http://stackoverflow.com/q/52008365
tags question: http://stackoverflow.com/q/51989977
tags question: http://stackoverflow.com/q/52085263
tags question: http://stackoverflow.com/q/52055490
tags question: http://stackoverflow.com/q/52043323
tags question: http://stackoverflow.com/q/52102859
tags question: http://stackoverflow.com/q/52032149
tags question: http://stackoverflow.com/q/52054905
tags question: http://stackoverflow.com/q/52049114
tags question: http://stackoverflow.com/q/51973089
tags question: http://stackoverflow.com/q/52075642
tag name: sqlite
tags question: http://stackoverflow.com/q/52074204

http://stackoverflow.com/comment/90902292
score: 0
comment on: http://stackoverflow.com/q/51975512
has text: @AndréC.Andersen I'll add benchmarking comments to each solution.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91158417
has text: Welcome to SO. This is a broad question. Please share the code from your latest attempt(s) so we can take the time to explain the bits where you got stuck. See also [mcve].
comment on: http://stackoverflow.com/q/52103724
type: Comment
score: 1
type: QuestionComment

http://stackoverflow.com/comment/90996350
score: 0
type: QuestionComment
type: Comment
has text: my bad the return is x, its used for a bigger part of code, but my problem lies here, and for the 'users' thing, i made the list outside of function and still get the same result, i can bypass the initial check by inputting the same name after being prompted to enter a new name
comment on: http://stackoverflow.com/q/52023003

http://stackoverflow.com/comment/91118592
comment on: http://stackoverflow.com/q/52084093
score: 0
type: QuestionComment
has text: you can serialize to db, but also have your bot remember the wait times. Serialize to db with a UUID that the bot's function knows, then when the function runs as part of its teardown it deletes the row from the db. When the bot starts as part of its init it should go look at each entry in the reminder table and set up those async calls to run on time.
type: Comment

http://stackoverflow.com/a/53125417
has comment: http://stackoverflow.com/comment/103835739
answers question: http://stackoverflow.com/q/52012010
downvote count: 0
has body: Many image-based machine learning models are trained with fixed-sized inputs. The original image may come with different dimensions, but get resized to a fixed size (e.g. 224x224x3). Therefore, you need to resize the image before feeding the input to the model. It may work well because the fact that the training data are also resized from various sizes. As the comment above already pointed out, cv.resize can do the trick.
type: Answer
score: 1
upvote count: 1

http://stackoverflow.com/comment/91078053
score: 0
type: Comment
type: QuestionComment
has text: Could you possibly reformat the post to display your df's properly? It is hard to follow and it may make it easy for people to help you.
comment on: http://stackoverflow.com/q/52063805

http://stackoverflow.com/comment/91014822
has text: I won't be upset as long as your smiling with me ;)
type: Comment
comment on: http://stackoverflow.com/a/52032207
type: AnswerComment
score: 0

http://stackoverflow.com/q/52048778
tagged with: sentry
downvote count: 0
has comment: http://stackoverflow.com/comment/91048567
linked to: http://stackoverflow.com/q/48184300
favorite count: 0
has answer: http://stackoverflow.com/a/55902135
upvote count: 25
answer count: 5
type: UnansweredQuestion
tagged with: heroku-postgres
has answer: http://stackoverflow.com/a/59814559
tagged with: django
tagged with: python
has title: OperationalError: cursor "_django_curs_<id>" does not exist
score: 25
has answer: http://stackoverflow.com/a/78427448
has answer: http://stackoverflow.com/a/73800376
has body: We have an online store web-app which is powered by django, postgresql and heroku. For a specific campaign (you can think a campaign like a product to purchase), we have sold 10k+ copies successfully. Yet some of our users are encountered this error according to our Sentry reports. Common specification of these users is; none of them have address information before the purchase. Generally, users fill out address form right after registering. If they don't, they need to fill the form while purchasing the product and submit them together. This is how the trace looks like: OperationalError: cursor "_django_curs_140398688327424_146" does not exist (66 additional frame(s) were not displayed) ... File "store/apps/store_main/templatetags/store_form_filters.py", line 31, in render_form return render_to_string('widgets/store_form_renderer.html', ctx) File "store/apps/store_main/templatetags/store_form_filters.py", line 20, in render_widget return render_to_string('widgets/store_widget_renderer.html', ctx) File "store/apps/store_main/widgets.py", line 40, in render attrs=attrs) + "&lt;span class='js-select-support select-arrow'&gt;&lt;/span&gt;&lt;div class='js-select-support select-arrow-space'&gt;&lt;b&gt;&lt;/b&gt;&lt;/div&gt;" OperationalError: cursor "_django_curs_140398688327424_146" does not exist So another weird common thing, there are exception messages between sql queries before the failure. You can see it in the image below: I'm adding it if they are somehow related. What may also be related is, the users who get this error are the users who tries to purchase the campaign right after a bulk mailing. So, extensive traffic might be the reason yet we are also not sure. We asked Heroku about the problem since they are hosting the postgres, yet they do not have any clue either. I know the formal reason of this error is trying to reach the cursor after a commit. Since it is destroyed after transaction, trying to reach it cause this error yet I don't see this in our scen…
type: Question
has answer: http://stackoverflow.com/a/76779208
tagged with: postgresql

http://stackoverflow.com/a/52048851
upvote count: 2
has body: When you say from x.y import * you are importing everything defined in __all__ from the module y that resides in directory x. If you'd only like to import a subset of y you can do the following: Limit what you're importing from your script from examplemodule.submodule import function_i_want or from examplemodule.submodule import ( function_i_want, other_function_i_want ) Define __all__ in your __init__.py __all__ = ['function_i_want', 'other_function_i_want']
downvote count: 0
answers question: http://stackoverflow.com/q/52048701
type: Answer
score: 2

http://stackoverflow.com/comment/111874380
has text: pd.read_excel() doesn't have the `encoding` argument.
score: 13
type: AnswerComment
comment on: http://stackoverflow.com/a/52066957
type: Comment

http://stackoverflow.com/a/52010907
answers question: http://stackoverflow.com/q/52010876
score: 4
accepted answer of: http://stackoverflow.com/q/52010876
type: AcceptedAnswer
downvote count: 0
has body: The easiest way would be to detect negative inputs, get their absolute values, and then put - on the front when you return them: def timer(ms): if ms &lt; 0: return "-" + timer(abs(ms)) ...
type: Answer
upvote count: 4

http://stackoverflow.com/comment/91082801
type: QuestionComment
comment on: http://stackoverflow.com/q/52066069
has text: @abarnert Right, that is interesting. I would never convert `str` to `int` to begin with, for this task :\
score: 0
type: Comment

tensorflow
tags question: http://stackoverflow.com/q/52067100
tags question: http://stackoverflow.com/q/52030675
tags question: http://stackoverflow.com/q/52079681
tags question: http://stackoverflow.com/q/52110635
tags question: http://stackoverflow.com/q/52023609
tags question: http://stackoverflow.com/q/51983410
tags question: http://stackoverflow.com/q/51958745
tags question: http://stackoverflow.com/q/52084911
tags question: http://stackoverflow.com/q/52032280
tags question: http://stackoverflow.com/q/51971050
tags question: http://stackoverflow.com/q/52067481
tags question: http://stackoverflow.com/q/52073782
tags question: http://stackoverflow.com/q/52042923
tags question: http://stackoverflow.com/q/52108685
tags question: http://stackoverflow.com/q/52045161
tags question: http://stackoverflow.com/q/52035644
tags question: http://stackoverflow.com/q/52089601
tags question: http://stackoverflow.com/q/51985357
tags question: http://stackoverflow.com/q/52092999
tags question: http://stackoverflow.com/q/51969493
tags question: http://stackoverflow.com/q/51994563
tags question: http://stackoverflow.com/q/52011744
tags question: http://stackoverflow.com/q/52033908
tags question: http://stackoverflow.com/q/52095790
tags question: http://stackoverflow.com/q/52001272
tags question: http://stackoverflow.com/q/52092340
tags question: http://stackoverflow.com/q/52097928
tags question: http://stackoverflow.com/q/52050767
tags question: http://stackoverflow.com/q/51969472
tags question: http://stackoverflow.com/q/52072640
tags question: http://stackoverflow.com/q/52110702
tags question: http://stackoverflow.com/q/52012010
tags question: http://stackoverflow.com/q/52006556
tags question: http://stackoverflow.com/q/52094498
tags question: http://stackoverflow.com/q/51995977
tags question: http://stackoverflow.com/q/51998587
tags question: http://stackoverflow.com/q/51995267
tags question: http://stackoverflow.com/q/52085468
tags question: http://stackoverflow.com/q/51970251
tags question: http://stackoverflow.com/q/52048528
tags question: http://stackoverflow.com/q/52098696
tags question: http://stackoverflow.com/q/52006745
tags question: http://stackoverflow.com/q/52043436
tags question: http://stackoverflow.com/q/52082538
tags question: http://stackoverflow.com/q/52088807
tags question: http://stackoverflow.com/q/52041028
tags question: http://stackoverflow.com/q/51983367
tags question: http://stackoverflow.com/q/52096523
tags question: http://stackoverflow.com/q/52026823
tags question: http://stackoverflow.com/q/52092881
tags question: http://stackoverflow.com/q/52011509
tags question: http://stackoverflow.com/q/52094675
tags question: http://stackoverflow.com/q/52093562
tags question: http://stackoverflow.com/q/52054238
tags question: http://stackoverflow.com/q/52034426
tags question: http://stackoverflow.com/q/51967552
tags question: http://stackoverflow.com/q/52049532
tags question: http://stackoverflow.com/q/51996163
tags question: http://stackoverflow.com/q/51999342
tags question: http://stackoverflow.com/q/51991589
tags question: http://stackoverflow.com/q/52047126
tags question: http://stackoverflow.com/q/52037512
tags question: http://stackoverflow.com/q/52063402
tags question: http://stackoverflow.com/q/51967975
tags question: http://stackoverflow.com/q/52064450
tags question: http://stackoverflow.com/q/52059580
tags question: http://stackoverflow.com/q/52016656
tags question: http://stackoverflow.com/q/52058758
tags question: http://stackoverflow.com/q/52079029
tags question: http://stackoverflow.com/q/51967083
tags question: http://stackoverflow.com/q/52080424
tags question: http://stackoverflow.com/q/51962659
tags question: http://stackoverflow.com/q/52015499
tags question: http://stackoverflow.com/q/51990034
tags question: http://stackoverflow.com/q/52087985
tags question: http://stackoverflow.com/q/51982179
tags question: http://stackoverflow.com/q/52039079
tags question: http://stackoverflow.com/q/52082959
tags question: http://stackoverflow.com/q/52029879
tag name: tensorflow

http://stackoverflow.com/comment/91052260
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52049714
has text: Possible duplicate of [Regex Mismatch: Searching anywhere for certain number of digits](https://stackoverflow.com/questions/52050018/regex-mismatch-searching-anywhere-for-certain-number-of-digits)

http://stackoverflow.com/comment/90920510
type: Comment
has text: @Loebl how to make sure it makes a check whether the list only contains integers and then the item is appended. if the list contains a mixture, move on to the else part and print out the original list
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/51985371

http://stackoverflow.com/a/52064926
has comment: http://stackoverflow.com/comment/91117620
has body: The snippet below should do what you're looking for. First, check for rows less than 1.0 apart from the preceding row. In order to catch the first row of the group, do the same thing with the following row. Combine these with np.logical_or and create group numbers by once again using shift. Finally, filter to the groups we created that have all 'True' values; that is, every value within the group is within one of its neighbor. Once we have the all-positive groups, take the biggest one (not necessarily a group of five). Once we get that group number, return those rows from the original df. df.columns = ['curve'] a = abs(df.curve - df.curve.shift()) &lt; 1.0 b = abs(df.curve - df.curve.shift(-1)) &lt; 1.0 c = np.logical_or(a, b) d = (c != c.shift()).cumsum() df['c'] = c df['d'] = d df = df.groupby(d).filter(lambda x: all(x['c'])) max_group = df.loc[df.groupby(d).cumcount().idxmax()]['d'] df_added = df.loc[df['d'] == max_group] EDIT: I should also note that the concerns raised in the comments to your original question are valid.
downvote count: 0
has comment: http://stackoverflow.com/comment/91080700
type: Answer
answers question: http://stackoverflow.com/q/52064521
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/91108626

http://stackoverflow.com/a/52102124
has body: array = [] for item in soup.findAll('tr', {'valign': 'top'}): array.append([f.text.strip().replace("\xa0\n\t", "") for f in item.findAll("td")]) output = [] for e in array: output.append({"Country": e[0].replace(" ", ""), "Date": e[1], "Time": e[2], "Description": e[3]}) if you want to print only the country, just do this for element in output: print (element["Country"])
has comment: http://stackoverflow.com/comment/91155301
has comment: http://stackoverflow.com/comment/91155096
has comment: http://stackoverflow.com/comment/91155629
has comment: http://stackoverflow.com/comment/91155356
answers question: http://stackoverflow.com/q/52101446
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52101446
has comment: http://stackoverflow.com/comment/91155646
type: Answer
has comment: http://stackoverflow.com/comment/91155519
has comment: http://stackoverflow.com/comment/91155260
has comment: http://stackoverflow.com/comment/91155424
score: 1
upvote count: 1

http://stackoverflow.com/q/52106531
has comment: http://stackoverflow.com/comment/91290477
favorite count: 0
has comment: http://stackoverflow.com/comment/91216413
type: Question
has title: jinja2 and weasyprint path to image
tagged with: python
tagged with: weasyprint
linked to: http://stackoverflow.com/q/57211774
upvote count: 1
has answer: http://stackoverflow.com/a/70018619
answer count: 1
tagged with: jinja2
accepted answer: http://stackoverflow.com/a/70018619
has body: My code convert the jinja2 template into PDF using weasyprint. Everything work fine except I can't get the image to appear in the PDF. My files structure: dist src img image.png templates statement.html.j2 build.py "build.py" import jinja2 import json import os import weasyprint from weasyprint.fonts import FontConfiguration def main(): if not os.path.exists('dist'): os.makedirs('dist') jinja_env = jinja2.Environment( loader = jinja2.FileSystemLoader('src/templates') ) css_dir = 'src/css' html_tpl = jinja_env.get_template('statement.html.j2') with open('sample/json/statement.json', 'r') as f: statement = json.load(f) statement = statement['statement'] font_config = FontConfiguration() html = html_tpl.render(statement=statement) css_files = [weasyprint.CSS(os.path.join(css_dir, filename)) for filename in os.listdir(css_dir)] rendered_html = weasyprint.HTML( string=html ) rendered_html.write_pdf( 'dist/statement.pdf', stylesheets=css_files, font_config=font_config ) if __name__ == '__main__': main() "statement.html.j2" &lt;img class="img-responsive" src="../img/image.png"&gt; Is the image path correct? How I can reference the image in the template? What will be the path then? Or the issue is not related to the image reference?
type: AnsweredQuestion
downvote count: 0
has comment: http://stackoverflow.com/comment/91188236
score: 1

http://stackoverflow.com/q/52027030
has title: Why can I only use the await keyword inside of async function?
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52027624
has comment: http://stackoverflow.com/comment/91005291
score: 55
has body: Suppose I have code like this async def fetch_text() -&gt; str: return "text " async def show_something(): something = await fetch_text() print(something) Which is fine. But then I want to clean the data, so I do async def fetch_text() -&gt; str: return "text " def fetch_clean_text(text: str) -&gt; str: text = await fetch_text() return text.strip(text) async def show_something(): something = fetch_clean_text() print(something) (I could clean text inside show_something(), but let's assume that show_something() can print many things and doesn't or shouldn't know the proper way of cleaning them.) This is of course a SyntaxError: 'await' outside async function. But—if this code could run—while the await expression is not placed inside a coroutine function, it is executed in the context of one. Why this behavior is not allowed? I see one pro in this design; in my latter example, you can't see that show_something()'s body is doing something that can result in its suspension. But if I were to make fetch_clean_text() a coroutine, not only would it complicate things but would probably also reduce performance. It just makes little sense to have another coroutine that doesn't perform any I/O by itself. Is there a better way?
type: Question
has comment: http://stackoverflow.com/comment/91005318
possible better answer: http://stackoverflow.com/a/69607531
accepted answer: http://stackoverflow.com/a/52027624
has answer: http://stackoverflow.com/a/69607531
answer count: 2
has comment: http://stackoverflow.com/comment/91004850
upvote count: 55
downvote count: 0
favorite count: 0
tagged with: python-asyncio

http://stackoverflow.com/comment/91113163
comment on: http://stackoverflow.com/q/52080614
score: 0
type: Comment
type: QuestionComment
has text: yes that's exactly what i meant. thanks

http://stackoverflow.com/comment/91113541
type: Comment
comment on: http://stackoverflow.com/q/52078723
has text: Your picture size is 35 megapixels ! Also, the GIF decoder isn't using any vectorized processing.
score: 1
type: QuestionComment

http://stackoverflow.com/a/52095244
score: 3
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/91645073
has comment: http://stackoverflow.com/comment/91554262
has comment: http://stackoverflow.com/comment/91554663
has comment: http://stackoverflow.com/comment/91554973
type: Answer
has comment: http://stackoverflow.com/comment/91625753
has comment: http://stackoverflow.com/comment/91698033
has comment: http://stackoverflow.com/comment/91726790
has comment: http://stackoverflow.com/comment/91630616
upvote count: 3
has comment: http://stackoverflow.com/comment/91555003
has comment: http://stackoverflow.com/comment/91645122
accepted answer of: http://stackoverflow.com/q/52087404
has comment: http://stackoverflow.com/comment/91554521
has body: Edit: Replaced synthetic dataset with sample data from OP Fixed function that builds new forecast period Fixed x-axis date format as per OPs request Answer: If you're looking for calculated values within your estimation period, you should use modelHW.fittedvalues and not modelHW.forecast(). The latter will give you just what it says; forecasts. And it's pretty awesome. Let me show you how to do both things: Plot 1 - Model within estimation period Plot 2 - Forecasts Code: #imports import matplotlib.pyplot as plt import pandas as pd import numpy as np from statsmodels.tsa.api import ExponentialSmoothing import matplotlib.dates as mdates #%% # # Load data pass_df = pd.read_csv('https://raw.githubusercontent.com/dacatay/time-series-analysis/master/data/passengers.csv', sep=';') pass_df = pass_df.set_index('month') type(pass_df.index) df = pass_df.copy() # Model modelHW = ExponentialSmoothing(np.asarray(df['n_passengers']), seasonal_periods=12, trend='add', seasonal='mul',).fit() modelHW.summary() # Model, fitted values model_values = modelHW.fittedvalues model_period = df.index df_model = pd.concat([df['n_passengers'], pd.Series(model_values, index = model_period)], axis = 1) df_model.columns = ['n_passengers', 'HWmodel'] df_model = df_model.set_index(pd.DatetimeIndex(df_model.index)) # Model, plot fig, ax = plt.subplots() myFmt = mdates.DateFormatter('%Y-%m') df_model.plot(ax = ax, x_compat=True) ax.xaxis.set_major_formatter(myFmt) # Forecasts prediction_size = 10 forecast_values = modelHW.forecast(prediction_size) # Forecasts, build new period forecast_start = df.index[-1] forecast_start = pd.to_datetime(forecast_start, format='%Y-%m-%d') forecast_period = pd.period_range(forecast_start, periods=prediction_size+1, freq='M') forecast_period = forecast_period[1:] # Forecasts, create dataframe df_forecast = pd.Series(forecast_values, index = forecast_period.values).to_frame() df_forecast.columns = ['HWforecast'] # merge input and forecast dataframes df_all = pd.merge(df,…
has comment: http://stackoverflow.com/comment/91554446
answers question: http://stackoverflow.com/q/52087404
has comment: http://stackoverflow.com/comment/91554388
has comment: http://stackoverflow.com/comment/91628481
has comment: http://stackoverflow.com/comment/91727012

http://stackoverflow.com/a/52077737
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/96612835
has body: If I understand correctly, the getOptimalNewCameraMatrix function is only for when you don't want to the black sides while undistorting an entire image (see this question), and not for when you are undistorting individual points. Also, it seems P and R in undistortPoints are only for stereo vision things. I would simplify it, and just say: undistorted_points = cv2.undistortPoints(np.array(points), optical_camera_matrix, d) where optical_camera_matrix is the matrix directly from the calibrateCamera function. Just make sure that points are a 1xN or Nx1 2-channel array. UPDATE: I realized what the problem was. The secret is the sentence on this website. Also the function performs a reverse transformation to projectPoints() As I understand it (please correct me if I'm wrong) the undistorted points are normalized. In order to put them back in pixel units simply do the following (in pseudo code): for each point in undistorted_points: point = point * focal_length + boresight I hope this helps!
has comment: http://stackoverflow.com/comment/91164060
has comment: http://stackoverflow.com/comment/91176934
has comment: http://stackoverflow.com/comment/91169744
has comment: http://stackoverflow.com/comment/91179445
score: 4
has comment: http://stackoverflow.com/comment/91176491
upvote count: 4
answers question: http://stackoverflow.com/q/52075881

http://stackoverflow.com/a/52083705
score: 3
has body: In opencv you can train a classifier on both 6 and 9 like Haar Feature-based Cascade Classifier for Object Detection ( https://docs.opencv.org/3.4/d5/d54/group__objdetect.html , https://docs.opencv.org/3.4/dc/d88/tutorial_traincascade.html ) Example code is in i.e. https://coding-robin.de/2013/07/22/train-your-own-opencv-haar-classifier.html i do not know if this is an assignment and if you are fixed to opencv if not you can use neural networks, cf chapter Tunnel Vision of https://medium.com/@ageitgey/machine-learning-is-fun-part-3-deep-learning-and-convolutional-neural-networks-f40359318721 or https://towardsdatascience.com/convnets-series-spatial-transformer-networks-cff47565ae81 however spatial transformer networks are a bit overcomplicated for this problem
downvote count: 0
answers question: http://stackoverflow.com/q/52083129
upvote count: 3
type: Answer

http://stackoverflow.com/comment/91151391
has text: @abarnert Thanks, I was curious if it was possible since I did not wish to modify the class containing the object.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52083986

http://stackoverflow.com/comment/91224047
comment on: http://stackoverflow.com/q/51985180
type: Comment
type: QuestionComment
score: 1
has text: FWIW I find that questions that focus on how to use a particular feature are much more commonly answered than questions of the form "here is my full workflow, please help"

http://stackoverflow.com/comment/90897127
type: Comment
comment on: http://stackoverflow.com/a/51973235
has text: that is a great solution. some entries are 'NaN'.. is there a smart way to convert those to '[ ]' inside the statement you have proposed?
score: 0
type: AnswerComment

http://stackoverflow.com/a/52047472
has comment: http://stackoverflow.com/comment/91045952
type: AcceptedAnswer
downvote count: 0
has body: There is no method dedicated to check if there is an open segment/subsegment or not but the code snippet you posted definitely works well. A better way to test a Lambda function locally is to mimic the Lambda container behavior so your instrumented Lambda function behaves exactly the same both locally and in actual Lambda. You can check the source code here https://github.com/aws/aws-xray-sdk-python/blob/master/aws_xray_sdk/core/lambda_launcher.py#L24. Basically the Lambda container will set environment variable LAMBDA_TASK_ROOT so the SDK knows it is "running inside Lambda" and create the facade segment based on https://github.com/aws/aws-xray-sdk-python/blob/master/aws_xray_sdk/core/lambda_launcher.py#L94. You can set the trace header to not sample any subsegments so the SDK doesn't generate data. It depends on what your local testing is for. The solution might vary depending on if you want to stub X-Ray SDK to test your function or you want to test X-Ray instrumentation and need to see actual data on X-Ray console.
type: Answer
answers question: http://stackoverflow.com/q/52002849
accepted answer of: http://stackoverflow.com/q/52002849
score: 4
upvote count: 4

http://stackoverflow.com/comment/91001008
has text: thanks for `wait-for-it.sh`, but I got the same error.
type: Comment
score: 0
comment on: http://stackoverflow.com/a/52025144
type: AnswerComment

http://stackoverflow.com/q/52098967
has answer: http://stackoverflow.com/a/52328684
has title: Python Redis Queue (rq) - how to avoid preloading ML model for each job?
score: 17
answer count: 2
tagged with: python-rq
has body: I want to queue my ml predictions using rq. Example code (pesudo-ish): predict.py: import tensorflow as tf def predict_stuff(foo): model = tf.load_model() result = model.predict(foo) return result app.py: from rq import Queue from redis import Redis from predict import predict_stuff q = Queue(connection=Redis()) for foo in baz: job = q.enqueue(predict_stuff, foo) worker.py: import sys from rq import Connection, Worker # Preload libraries import tensorflow as tf with Connection(): qs = sys.argv[1:] or ['default'] w = Worker(qs) w.work() I've read rq docs explaining that you can preload libraries to avoid importing them every time a job is run (so in example code I import tensorflow in the worker code). However, I also want to move model loading from predict_stuff to avoid loading the model every time the worker runs a job. How can I go about that?
downvote count: 0
favorite count: 0
tagged with: redis
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/91271523
upvote count: 17
type: Question
has answer: http://stackoverflow.com/a/53733438

http://stackoverflow.com/q/51989046
has answer: http://stackoverflow.com/a/51989514
type: Question
answer count: 1
tagged with: pandas
upvote count: 1
tagged with: python
favorite count: 0
has body: My dataframe has 3 buildings and the demand of electric vehicles in kW. Each building can only charge with max 11 kW, so if the demand is higher (eg. 13 kWh) then 13 - 11 = 2 must be added to the value of the next hour. To make it more clear, the dataframe looks like this, and I want transform it like this: bd1 bd2 bd3 bd1 bd2 bd3 0 11 9 7 0 11 9 7 1 15 6 14 1 11 6 11 2 8 12 13 -&gt; 2 11 11 11 3 2 0 0 3 3 1 5 ... ... 8759 8 7 12 8759 8 7 11 I can't add the surplus to the last row, so the rest should be removed.
accepted answer: http://stackoverflow.com/a/51989514
has title: Substract value from dataframe under certain condition and add the rest to the next value
type: AnsweredQuestion
downvote count: 0
score: 1
tagged with: dataframe

http://stackoverflow.com/comment/91037162
type: Comment
comment on: http://stackoverflow.com/a/52043068
has text: Thank you in advance! :D
type: AnswerComment
score: 0

numpy
tags question: http://stackoverflow.com/q/51988142
tags question: http://stackoverflow.com/q/51981916
tags question: http://stackoverflow.com/q/52003366
tags question: http://stackoverflow.com/q/52004248
tags question: http://stackoverflow.com/q/51991021
tags question: http://stackoverflow.com/q/51957712
tags question: http://stackoverflow.com/q/52103594
tags question: http://stackoverflow.com/q/51983498
tags question: http://stackoverflow.com/q/52101378
tags question: http://stackoverflow.com/q/52029820
tags question: http://stackoverflow.com/q/52067920
tags question: http://stackoverflow.com/q/51971312
tags question: http://stackoverflow.com/q/51984682
tags question: http://stackoverflow.com/q/52053590
tags question: http://stackoverflow.com/q/51991164
tags question: http://stackoverflow.com/q/52025597
tags question: http://stackoverflow.com/q/52079185
tags question: http://stackoverflow.com/q/51984056
tags question: http://stackoverflow.com/q/52038410
tags question: http://stackoverflow.com/q/52091535
tags question: http://stackoverflow.com/q/52109977
tags question: http://stackoverflow.com/q/52025082
tags question: http://stackoverflow.com/q/52099565
tags question: http://stackoverflow.com/q/52070051
tags question: http://stackoverflow.com/q/52107551
tags question: http://stackoverflow.com/q/52010861
tags question: http://stackoverflow.com/q/52041521
tags question: http://stackoverflow.com/q/52018663
tags question: http://stackoverflow.com/q/52002807
tags question: http://stackoverflow.com/q/52018689
tags question: http://stackoverflow.com/q/52082654
tags question: http://stackoverflow.com/q/52024613
tags question: http://stackoverflow.com/q/52046347
tags question: http://stackoverflow.com/q/51967731
tags question: http://stackoverflow.com/q/51978567
tags question: http://stackoverflow.com/q/52061661
tags question: http://stackoverflow.com/q/52012247
tags question: http://stackoverflow.com/q/52074332
tags question: http://stackoverflow.com/q/51957207
tags question: http://stackoverflow.com/q/52065226
tags question: http://stackoverflow.com/q/52094020
tags question: http://stackoverflow.com/q/51982417
tags question: http://stackoverflow.com/q/52064375
tags question: http://stackoverflow.com/q/52015011
tags question: http://stackoverflow.com/q/52076022
tags question: http://stackoverflow.com/q/52003418
tags question: http://stackoverflow.com/q/52008764
tags question: http://stackoverflow.com/q/52084735
tags question: http://stackoverflow.com/q/52102645
tags question: http://stackoverflow.com/q/52108417
tags question: http://stackoverflow.com/q/52035644
tags question: http://stackoverflow.com/q/52024486
tags question: http://stackoverflow.com/q/51975995
tags question: http://stackoverflow.com/q/52072528
tags question: http://stackoverflow.com/q/52039658
tags question: http://stackoverflow.com/q/51998466
tags question: http://stackoverflow.com/q/51992019
tags question: http://stackoverflow.com/q/52078235
tags question: http://stackoverflow.com/q/51989572
tags question: http://stackoverflow.com/q/52075557
tags question: http://stackoverflow.com/q/52057927
tags question: http://stackoverflow.com/q/52062060
tags question: http://stackoverflow.com/q/51980675
tags question: http://stackoverflow.com/q/51974524
tags question: http://stackoverflow.com/q/52005509
tags question: http://stackoverflow.com/q/52053729
tags question: http://stackoverflow.com/q/52087192
tags question: http://stackoverflow.com/q/52073649
tags question: http://stackoverflow.com/q/52102423
tags question: http://stackoverflow.com/q/52091657
tags question: http://stackoverflow.com/q/51985180
tags question: http://stackoverflow.com/q/51995490
tags question: http://stackoverflow.com/q/52101888
tags question: http://stackoverflow.com/q/51967617
tags question: http://stackoverflow.com/q/51979554
tags question: http://stackoverflow.com/q/52039411
tags question: http://stackoverflow.com/q/51964798
tags question: http://stackoverflow.com/q/52088966
tags question: http://stackoverflow.com/q/52068525
tags question: http://stackoverflow.com/q/52066502

http://stackoverflow.com/q/52035149
tagged with: git
type: Question
score: -5
accepted answer: http://stackoverflow.com/a/52035294
has comment: http://stackoverflow.com/comment/91020541
has comment: http://stackoverflow.com/comment/91020502
answer count: 1
has title: cd command in python
favorite count: 0
has comment: http://stackoverflow.com/comment/91020599
has body: I am new to python and I am trying to test syntaxnet in python using this github repo. and in the section "how to run the parser" is as following : git clone https://github.com/spoddutur/syntaxnet.git cd &lt;syntaxnet-git-clone-directory&gt; python main.py That's it!! It prints syntaxnet dependency parser output for given input english sentence through some research, I understood that first one indicates that I need to install the syntaxnet package in my cmd so I did and the package was successfully installed. but I don't understand how to perform the second one what does cd do, and where and how should I use it? also in main.py, from my_parser_eval import SyntaxNetProcess from my_parser_eval import _write_input from my_parser_eval import _read_output from my_parser_eval import pretty_print eclipse cannot find those imports, even after I created a package/module named my_parser_eval that includes all necessary codes from the reference
tagged with: python
has comment: http://stackoverflow.com/comment/129737825
has answer: http://stackoverflow.com/a/52035294
downvote count: 6
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91020466
upvote count: 1
has comment: http://stackoverflow.com/comment/91020292

http://stackoverflow.com/comment/91038510
type: AnswerComment
has text: Ah ok, and then I can do the ifft of the result? I'll give that a whirl
type: Comment
comment on: http://stackoverflow.com/a/52043767
score: 0

http://stackoverflow.com/q/52053761
type: AnsweredQuestion
has title: Array to image with colour map
has comment: http://stackoverflow.com/comment/91059465
has comment: http://stackoverflow.com/comment/91138286
type: Question
has answer: http://stackoverflow.com/a/52188187
accepted answer: http://stackoverflow.com/a/52188187
tagged with: python-imaging-library
has comment: http://stackoverflow.com/comment/91058725
tagged with: image
has comment: http://stackoverflow.com/comment/91079785
has comment: http://stackoverflow.com/comment/91060561
has body: I have some data in a 2048x2048 array that I want to convert to an image. import numpy as np from PIL import Image path = 'E:\\petra_2018_backup\\final\\raw\data\zn_2_run\\' file = 'Zn_2_Pos1-01537.tif' im = Image.open(path+file) a = np.array(im) img = Image.frombytes('CMYK', (2048, 2048), a) # pass in the bytestring img.save('pic.pdf') img.show() This result is quite dark and also has a mixture of green and blue colours. I should mention that the attached picture is a screendump of the result as the result picture is to large to attach. It would also be usefull if people can advice on a way to compress the resulting image.
answer count: 1
has comment: http://stackoverflow.com/comment/91112227
score: 0
has comment: http://stackoverflow.com/comment/91074053
tagged with: python

http://stackoverflow.com/a/52018630
answers question: http://stackoverflow.com/q/52014482
type: Answer
downvote count: 0
score: 1
upvote count: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/52014482
has body: I think you can simply do import re result = re.split(r"\s+(?:but|and)\s+", sentence) where `\s` Match a single character that is a "whitespace character" (spaces, tabs, line breaks, etc.) `+` Between one and unlimited times, as many times as possible, giving back as needed (greedy) `(?:` Match the regular expression below, do not capture Match either the regular expression below (attempting the next alternative only if this one fails) `but` Match the characters "but" literally `|` Or match regular expression number 2 below (the entire group fails if this one fails to match) `and` Match the characters "and" literally ) `\s` Match a single character that is a "whitespace character" (spaces, tabs, line breaks, etc.) `+` Between one and unlimited times, as many times as possible, giving back as needed (greedy) You can add more conjunction words in there separated by a pipe-character |. Take care though that these words do not contain characters that have special meaning in regex. If in doubt, escape them first with re.escape(word)

http://stackoverflow.com/comment/91008634
has text: Thank you. About dense: why does it not return a 2d result of dimensions (2,1)?
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52028841

http://stackoverflow.com/a/52037317
upvote count: 1
type: AcceptedAnswer
downvote count: 0
type: Answer
has body: It looks like date is already index. In other words, you cannot assign date as index twice. Thus below would work: df3 = df1.add(df2, axis='index', fill_value=0) Output: total_pnl_per_pos invested date 2015-03-16 -0.009346 3.843277e+06 2015-03-17 0.305111 4.641716e+06 2015-03-18 -0.225263 4.385528e+06 2015-03-19 0.044563 4.481589e+06 2015-03-20 0.315961 6.431091e+06 2015-03-21 -0.004500 1.499999e+05 Hope this helps.
score: 1
accepted answer of: http://stackoverflow.com/q/52036505
answers question: http://stackoverflow.com/q/52036505

http://stackoverflow.com/a/52049303
accepted answer of: http://stackoverflow.com/q/52049188
type: AcceptedAnswer
score: 0
answers question: http://stackoverflow.com/q/52049188
type: Answer
has body: Here's something pretty close (your example output is not valid python, unless it is just a string): In []: (df.groupby(['Column 1', 'Column 2'])'Column 3', 'Column 4' .apply(lambda x: x.to_dict(orient='record')) .reset_index(name='Column 5')) Out[]: Column 1 Column 2 Column 5 0 A B [{'Column 3': 1, 'Column4': '#'}, {'Column 3': 2, 'Column 4': '$'}] 1 A C [{'Column 3': 1, 'Column 4': '%'}]

recursion
type: Tag
tags question: http://stackoverflow.com/q/51996982
tags question: http://stackoverflow.com/q/52011799
tags question: http://stackoverflow.com/q/52105455
tags question: http://stackoverflow.com/q/52108345
tags question: http://stackoverflow.com/q/52041907
tag name: recursion
tags question: http://stackoverflow.com/q/52086142
tags question: http://stackoverflow.com/q/52104557
tags question: http://stackoverflow.com/q/52085323
tags question: http://stackoverflow.com/q/52015279
tags question: http://stackoverflow.com/q/52097608
tags question: http://stackoverflow.com/q/52022935
tags question: http://stackoverflow.com/q/52094973
tags question: http://stackoverflow.com/q/51994148
tags question: http://stackoverflow.com/q/51972291
tags question: http://stackoverflow.com/q/51966629

http://stackoverflow.com/comment/91180572
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/52110930
score: 0
has text: Microsecond precision is a *very* tough requirement. There's https://stackoverflow.com/questions/41987430/what-is-the-lowest-latency-communication-method-between-a-computer-and-a-microco to give you an idea of the problem. A signal through an Ethernet cable will only travel ca. 200 meters per microsecond and you'll have lots of random latency due to buffers, schedulers, GC etc in your stack. Even if you manage to trigger a signal to the camera at the exactly right time, you'll still have random latency before the shutter is activated. I would urge you to rethink your strategy.

http://stackoverflow.com/q/52042895
tagged with: http://stackoverflow.com/tag/csv
accepted answer: http://stackoverflow.com/a/52043007
tagged with: python
favorite count: 0
tagged with: python-3.x
tagged with: list
has comment: http://stackoverflow.com/comment/91036891
possible better answer: http://stackoverflow.com/a/52043021
score: 0
has answer: http://stackoverflow.com/a/52043021
has answer: http://stackoverflow.com/a/52043089
upvote count: 1
has comment: http://stackoverflow.com/comment/91036688
downvote count: 1
has answer: http://stackoverflow.com/a/52044301
has answer: http://stackoverflow.com/a/52043082
answer count: 5
has body: Lets suppose that I have two lists: users = [ user1, user2, user3, ...] codes = [ code1, code2, code3, ...] And I want to create a csv where I assign a code to each user like this: users, codes user1, code1 user2, code2 I have been trying for days and I can't find a solution. I've tried to extend the list, but it doesn't work the way it supposed to. Thanks for
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91036786
has title: Python: making a csv out of two lists
has comment: http://stackoverflow.com/comment/91036621
has answer: http://stackoverflow.com/a/52043007
has comment: http://stackoverflow.com/comment/91036617
type: Question

scrapy
tags question: http://stackoverflow.com/q/52104875
tags question: http://stackoverflow.com/q/51991170
tags question: http://stackoverflow.com/q/51988850
tags question: http://stackoverflow.com/q/52110829
tags question: http://stackoverflow.com/q/52091496
tags question: http://stackoverflow.com/q/52109732
tags question: http://stackoverflow.com/q/52010647
tags question: http://stackoverflow.com/q/51973028
tags question: http://stackoverflow.com/q/52049514
tags question: http://stackoverflow.com/q/51959143
tags question: http://stackoverflow.com/q/52059893
tags question: http://stackoverflow.com/q/52022266
tags question: http://stackoverflow.com/q/52053039
tags question: http://stackoverflow.com/q/52034814
tags question: http://stackoverflow.com/q/51962229
tags question: http://stackoverflow.com/q/52003829
tags question: http://stackoverflow.com/q/52065496
tags question: http://stackoverflow.com/q/52085907
tags question: http://stackoverflow.com/q/52080024
tags question: http://stackoverflow.com/q/51977764
tags question: http://stackoverflow.com/q/52098291
tags question: http://stackoverflow.com/q/52056897
tags question: http://stackoverflow.com/q/52080940
tags question: http://stackoverflow.com/q/51968013
tags question: http://stackoverflow.com/q/52069158
tags question: http://stackoverflow.com/q/52065083
tags question: http://stackoverflow.com/q/52082742
tag name: scrapy
tags question: http://stackoverflow.com/q/52031397
tags question: http://stackoverflow.com/q/52020484
tags question: http://stackoverflow.com/q/51976878
tags question: http://stackoverflow.com/q/52103834
tags question: http://stackoverflow.com/q/52091111
tags question: http://stackoverflow.com/q/52105782
tags question: http://stackoverflow.com/q/51997310
tags question: http://stackoverflow.com/q/52106040
tags question: http://stackoverflow.com/q/52046850
type: Tag
tags question: http://stackoverflow.com/q/52025186

http://stackoverflow.com/comment/90963599
has text: Thanks. Per a colleague, "the code doesn't help much. We can't tell what's preventing them from just having the closure capture the dynamic value." Can you edit your question to include a bit more code? That may prevent the question from being closed (code questions fare better when they present a clear, reproducible problem).
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/51959978
type: Comment

http://stackoverflow.com/a/52036820
upvote count: 1
has body: Get class name value and store in 'var' split class name using underscore and it will return array with splitted string access value at last index of array 'data' it will contain elements like "ui","bubble","rating bubble","50" var = driver. find_element_by_xpath("//span[contains(@class, 'ui_bubble_rating bubble_')]").get_attribute("class") data = var.split("_") print data[-1]
has comment: http://stackoverflow.com/comment/91051103
downvote count: 0
answers question: http://stackoverflow.com/q/52033155
type: Answer
score: 1

http://stackoverflow.com/q/52004018
type: Question
has title: QTableView model crash when calling endInsertRows()
has comment: http://stackoverflow.com/comment/90958306
upvote count: 3
has comment: http://stackoverflow.com/comment/90958179
tagged with: pyqt
answer count: 1
tagged with: qabstracttablemodel
favorite count: 0
tagged with: python-3.x
has body: I have been trying to update a QTableViewModel when inserting a new object that represents a row. I did follow the advise of several question in SO, but I cannot get an example to work. After debugging, I found that the call to self.endInsertRows() produces the crash. This is a minimal example: import sys from PyQt5.QtWidgets import * from PyQt5 import QtCore, QtGui, QtWidgets class Wire: def __init__(self, name, x, y, gmr, r): self.name = name self.x = x self.y = y self.r = r self.gmr = gmr class WiresCollection(QtCore.QAbstractTableModel): def __init__(self, parent=None): QtCore.QAbstractTableModel.__init__(self, parent) self.header = ['Name', 'R (Ohm/km)', 'GMR (m)'] self.index_prop = {0: 'name', 1: 'r', 2: 'gmr'} self.wires = list() def add(self, wire: Wire): """ Add wire :param wire: :return: """ row = len(self.wires) self.beginInsertRows(QtCore.QModelIndex(), row, row) self.wires.append(wire) self.endInsertRows() def delete(self, index): """ Delete wire :param index: :return: """ row = len(self.wires) self.beginRemoveRows(QtCore.QModelIndex(), row, row) self.wires.pop(index) self.endRemoveRows() def rowCount(self, parent=QtCore.QModelIndex()): return len(self.wires) def columnCount(self, parent=QtCore.QModelIndex()): return len(self.header) def parent(self, index=None): return QtCore.QModelIndex() def data(self, index, role=QtCore.Qt.DisplayRole): if index.isValid(): if role == QtCore.Qt.DisplayRole: val = getattr(self.wires[index.row()], self.index_prop(index.column())) return str(val) return None def headerData(self, p_int, orientation, role): if role == QtCore.Qt.DisplayRole: if orientation == QtCore.Qt.Horizontal: return self.header[p_int] def setData(self, index, value, role=QtCore.Qt.DisplayRole): """ Set data by simple editor (whatever text) :param index: :param value: :param role: """ wire = self.wires[index.row()] attr = self.index_prop[index.column()] setattr(wire, attr, value) class TowerBuilderGUI(QtWidgets.QDialog): def __init__(self, parent=None)…
tagged with: python
has comment: http://stackoverflow.com/comment/90958942
type: AnsweredQuestion
score: 3
has answer: http://stackoverflow.com/a/52005263
accepted answer: http://stackoverflow.com/a/52005263
downvote count: 0
tagged with: pyqt5

http://stackoverflow.com/comment/90934757
score: 0
type: Comment
has text: much thanks rstrip() did the trick.
type: QuestionComment
comment on: http://stackoverflow.com/q/51992452

http://stackoverflow.com/comment/91126103
type: Comment
comment on: http://stackoverflow.com/a/52087832
score: 1
type: AnswerComment
has text: Rather than `'Ahmed' + '\t' + 'Ashraf '` you may as well directly go `'Ahmed\tAshraf '`

http://stackoverflow.com/q/52076336
has comment: http://stackoverflow.com/comment/91102250
has comment: http://stackoverflow.com/comment/91104325
type: AnsweredQuestion
has body: I have a list like this but with thousands or maybe millions of elements: test = [ ("goodbye", "help", "buy","sell", "1.1.1.1", 25), ("hi dude", "text", "friends","love", "blablabla", 14), ("hi darling", "books", "letter","class", "club", 64) ] What would be the most optimized code for finding all the elements indexes that contain the word "hi"? In the given example above, it should return test[1] and test[2].
tagged with: list
linked to: http://stackoverflow.com/q/176918
possible better answer: http://stackoverflow.com/a/52076391
upvote count: 1
downvote count: 1
has answer: http://stackoverflow.com/a/52076414
type: Question
has title: Whats the fastest way of finding the indexes of an item given a list containing it in Python?
has comment: http://stackoverflow.com/comment/91102291
has comment: http://stackoverflow.com/comment/91104389
answer count: 2
tagged with: find
accepted answer: http://stackoverflow.com/a/52076414
favorite count: 0
has comment: http://stackoverflow.com/comment/91106543
score: 0
tagged with: element
has answer: http://stackoverflow.com/a/52076391
tagged with: python

http://stackoverflow.com/comment/91023648
comment on: http://stackoverflow.com/q/52036737
type: Comment
type: QuestionComment
score: 2
has text: Look up the `and` operator. It's not doing what you think it does. You can replace it with `,` to return a tuple.

http://stackoverflow.com/comment/91065213
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52053616
type: Comment
has text: I can't upvote as I don't have enough rep but I have accepted it as the answer.

http://stackoverflow.com/a/52181584
has comment: http://stackoverflow.com/comment/91337415
type: Answer
has comment: http://stackoverflow.com/comment/91453068
downvote count: 0
has body: Yes, CPython re-uses id() values. Do not count on these being unique in a Python program. This is clearly documented: Return the “identity” of an object. This is an integer which is guaranteed to be unique and constant for this object during its lifetime. Two objects with non-overlapping lifetimes may have the same id() value. Bold emphasis mine. The id is unique only as long as an object is alive. Objects that have no references left to them are removed from memory, allowing the id() value to be re-used for another object, hence the non-overlapping lifetimes wording. Note that this applies to CPython only, the standard implementation provided by python.org. There are other Python implementations, such as IronPython, Jython and PyPy, that make their own choices about how to implement id(), because they each can make distinct choices on how to handle memory and object lifetimes. To address your specific questions: In CPython, id() is the memory address. New objects will be slotted into the next available memory space, so if a specific memory address has enough space to hold the next new object, the memory address will be reused. You can see this in the interpreter when creating new objects that are the same size: &gt;&gt;&gt; id(1234) 4546982768 &gt;&gt;&gt; id(4321) 4546982768 The 1234 literal creates a new integer object, for which id() produces a numeric value. As there are no further references to the int value, it is removed from memory again. But executing the same expression again with a different integer literal, and chances are you'll see the same id() value (a garbage collection run breaking cyclic references could free up more memory, so you could also not see the same id() again. So it's not random, but in CPython it is a function of the memory allocation algorithms. If you need to check specific objects, keep your own reference to it. That can be a weakref weak reference if all you need to assure is that the object is still 'alive'. For example, recordin…
score: 34
accepted answer of: http://stackoverflow.com/q/52096582
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/52096582
upvote count: 34

group-by
tags question: http://stackoverflow.com/q/51968264
tags question: http://stackoverflow.com/q/52014853
tags question: http://stackoverflow.com/q/52037095
tags question: http://stackoverflow.com/q/52094879
tags question: http://stackoverflow.com/q/51975227
tags question: http://stackoverflow.com/q/52090690
tag name: group-by
tags question: http://stackoverflow.com/q/51987997
tags question: http://stackoverflow.com/q/51964771
tags question: http://stackoverflow.com/q/52015751
type: Tag
tags question: http://stackoverflow.com/q/52063696
tags question: http://stackoverflow.com/q/52073054

http://stackoverflow.com/q/52007165
tagged with: python
type: AnsweredQuestion
score: 5
has body: I need to normalize the rows of a dataframe containing rows populated with all zero. For example: df= pd.DataFrame({"ID": ['1', '2', '3', '4'], "A": [1, 0, 10, 0], "B": [4, 0, 30, 0]}) ID A B 1 1 4 2 0 0 3 10 30 4 0 0 My approach is to first exclude the zero-value rows followed by normalizing the non-zero subset using: df1 = df[df.sum(axis=1) != 0] df2 = df[df.sum(axis=1) == 0] sum_row = df1.sum(axis=1) df1.div(sum_row, axis=0) and then concatenate the two dataframes as follows: pd.concat([df1, df2]).reset_index() However, I end up with the following error while applying df1.div(sum_row, axis=0) ValueError: operands could not be broadcast together with shapes (6,) (2,) I wonder how to fix the error and if there exists a more efficient approach. Thanks! Edit: The resulting dataframe is expected to look like as: ID A B 1 0.2 0.8 2 0 0 3 0.25 0.75 4 0 0
type: Question
has answer: http://stackoverflow.com/a/52007429
upvote count: 5
has title: Normalizing rows of pandas dataframe
answer count: 3
downvote count: 0
has answer: http://stackoverflow.com/a/52007440
favorite count: 0
has comment: http://stackoverflow.com/comment/90964475
accepted answer: http://stackoverflow.com/a/52007440
tagged with: pandas
possible better answer: http://stackoverflow.com/a/52007424
has comment: http://stackoverflow.com/comment/90964684
has answer: http://stackoverflow.com/a/52007424

http://stackoverflow.com/q/52012513
downvote count: 0
possible better answer: http://stackoverflow.com/a/52012621
has body: I have two data frames as below: import pandas as pd d={'PART_NO': ['J661-03982','661-08913', '922-8972','661-00352','661-06291'], 'PART_NO_ENCODED': [541,1273,1110,1575,295]} suggest = pd.DataFrame(data=d) and d={'A': [1161,224, 505,1033,812], 'B': [957,417,440,588,910],'C':[392,167,97,70,703],'D':[187,2021,3437,2416,2117],'PART_NO':[541,1273,1110,1575,295]} result = pd.DataFrame(data=d) I want to replace the PART_NO in the result data frame with PART_NO of the suggest data frame. I am doing the following: df4 = result.replace(suggest.set_index('PART_NO_ENCODED').to_dict()['PART_NO']) df4 = df4[result.isin(suggest['PART_NO_ENCODED'].tolist())] However the problem is this is replacing the values for PART_NO but making all the other columns NaN. How do I solve this where I want the other column values to remain intact and only the PART_NO to be replaced with the PART_NO from suggest? The resulting data frame should look like this: d={'A': [1161,224, 505,1033,812], 'B': [957,417,440,588,910],'C':[392,167,97,70,703],'D':[187,2021,3437,2416,2117],'PART_NO':['J661-03982','661-08913', '922-8972','661-00352','661-06291']} result = pd.DataFrame(data=d)
favorite count: 0
has answer: http://stackoverflow.com/a/52012621
tagged with: python
type: AnsweredQuestion
score: 1
upvote count: 1
type: Question
has answer: http://stackoverflow.com/a/52012785
tagged with: dataframe
has title: replace one column with values of another column belonging to two different data frames
accepted answer: http://stackoverflow.com/a/52012785
answer count: 2
tagged with: pandas

http://stackoverflow.com/comment/91031183
score: 0
type: AnswerComment
has text: I thought it was bad form to change the question and still have this marked as solved. I am appreciative of the help, no offense to you intended :) I'll remark because you did solve my original problem.
type: Comment
comment on: http://stackoverflow.com/a/52031811

http://stackoverflow.com/q/51988022
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/51988217
has body: I was running some basic tests to get a grasp of pool in Python when i got the error : Error in `/usr/bin/python3.5': double free or corruption (fasttop): 0x0000000001adf380 with a full memory error stack and ending with : KeyError: 139961995958016 I was running the following code: from multiprocessing import Pool import time def f(x,t): print(time.time() - t) time.sleep(2) return x*x if __name__ == '__main__': with Pool(processes=2) as pool: time_start = time.time() l = [None]*4 for i in range(4): l[i] = pool.apply_async(f, (10, time_start)) l[-1].get(timeout=5*2) print(time.time()-time_start) I don't really understand what happens here. It is related to the use of time.time() in the f function as commenting that line solves the issue but outside of that, i am at a loss. I am running Python 3.5.2 (64 bits).
type: Question
tagged with: python-multiprocessing
score: 0
answer count: 1
has title: Double free or corruption error when using time.time() inside a pool worker subprocess

http://stackoverflow.com/comment/105720472
score: 1
has text: Note that you also need to define the `style` parameter to let it work. See: https://stackoverflow.com/questions/57485426/markers-are-not-visible-in-seaborn-plot
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51964145

http://stackoverflow.com/comment/91070408
comment on: http://stackoverflow.com/a/52034655
has text: Thanks for your answer. In the end, I just wrote my function (which was similar to yours) in cython.
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/91023231
type: Comment
comment on: http://stackoverflow.com/q/52036357
type: QuestionComment
score: 1
has text: I'd assume they are talking about @property, which actually is a getter and it literally has a setter; so maybe a better phrasing would be python has a better structure for getter and setters.

http://stackoverflow.com/q/52008544
tagged with: python
answer count: 0
has comment: http://stackoverflow.com/comment/90972623
has body: review_words is another text file that I have wherein I'll need to remove stopwords from. def remove_stopwords(word_list): review_words = [] for word in word_list: if word not in stopwords.word('english'): return review_words print(review_words) However, when I run it in powershell, it still doesn't remove the stopwords from review_words. Can somebody please enlighten me!! Thank you very much for your time.
type: Question
has title: how to remove stop words from a text file?
score: 0
has comment: http://stackoverflow.com/comment/90985238
upvote count: 1
downvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/90967678
type: UnansweredQuestion

http://stackoverflow.com/comment/91071815
has text: @AmirHadifar my code is completely balanced the number of positive and negative tweets are the same and equal
score: 0
comment on: http://stackoverflow.com/q/52060555
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51999837
has comment: http://stackoverflow.com/comment/90948845
has comment: http://stackoverflow.com/comment/90948922
has answer: http://stackoverflow.com/a/52000112
has comment: http://stackoverflow.com/comment/90948803
tagged with: pandas
answer count: 1
has comment: http://stackoverflow.com/comment/90948887
has comment: http://stackoverflow.com/comment/90948939
score: 0
has title: How to implement nested attributes of object like pandas series.str.find()
has body: Pandas has a neat feature where methods are given a namespace almost, like import pandas as pd s = pd.Series("Hi there Stack Overflow!".split()) print(s.str.len()) # 0 2 # 1 5 # 2 5 # 3 9 # dtype: int64 Here you see that the str methods like len are collected under a str namespace. I have an object that implements a lot of methods. I'd like to group them with attribute accesses like shown above. What is the simplest way to do that? If you could use the template below to make a dummy example that just prints attribute with a call to Series.str.print_attribute() that would likely be the simplest way to show how it works. class Series(): attribute = 42 str = ??? def __init__(self): ??? ???
tagged with: python
accepted answer: http://stackoverflow.com/a/52000112
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90948885
type: Question

http://stackoverflow.com/comment/91074355
has text: i tried 10:57:03 # find . -name command_file.txt...dont see the file..
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52061214

http://stackoverflow.com/q/51967739
has comment: http://stackoverflow.com/comment/90886199
favorite count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90886174
tagged with: python
has title: Python Pandas - Column - All possible combination
has comment: http://stackoverflow.com/comment/90886188
has comment: http://stackoverflow.com/comment/90886250
has answer: http://stackoverflow.com/a/51968239
upvote count: 1
downvote count: 1
type: Question
tagged with: combinations
has comment: http://stackoverflow.com/comment/90886040
has body: I have a dataset with 2 columns (Name and Score) and I would like to split the column Name in 2 groups: group 1 and group 2. Then, I will have to calculate sum(score group 1) / sum(score group 2). My goal is to find in all combinations of names and groups, what is the smallest sum(score group 1) / sum(score group 2). df = pd.DataFrame({ 'Name': list('ABCDEF'), 'Score': [600, 1000, 300, 100, -100, 3000], }, columns=['Name', 'Score']) df Name Score 0 A 600 1 B 1000 2 C 300 3 D 100 4 E -100 5 F 3000 Example of first interaction: Group Name Score 0 1 A 600 1 2 B 1000 2 2 C 300 3 2 D 100 4 2 E -100 5 2 F 3000 sum(score group 1) / sum(score group 2) = 0.1395 Example of second interaction: Group Name Score 0 1 A 600 1 1 B 1000 2 2 C 300 3 2 D 100 4 2 E -100 5 2 F 3000 sum(score group 1) / sum(score group 2) = 0.4848 And then, calculate score for all combinations and get the smallest sum(score group 1) / sum(score group 2)
score: 0
tagged with: pandas
has comment: http://stackoverflow.com/comment/90887412
answer count: 1

http://stackoverflow.com/a/52021234
type: AcceptedAnswer
has body: for loop 1st Iteration Before the for loop, children contains a list of three memory location of button widgets, [Button3, Button2, Button1]. In the first iteration, i is referencing the first item in children and it removed widget, Button3. 2nd Iteration Before the second iteration, children contains a list of two memory location of button widgets, [Button2, Button1]. In the second iteration, i is referencing the second item in children and it removed widget, Button1. 3rd Iteration Before the third iteration, children contains a list of two memory location of button widgets, [Button2]. Since there is no third item in children, the for loop exit. While loop Since i (index) always remains at 0, therefore, it was successful in removing all the three button widgets because it is always referencing the first item in the list, children. self.root.ids.box.remove_widget(children[i]) is equivalent to self.root.ids.box.remove_widget(children[0]) Solution The solution for the for loop is use reversed(self.root.ids.box.children). Snippet def del_button(self): for child in reversed(self.root.ids.box.children): self.root.ids.box.remove_widget(child)
type: Answer
score: 1
answers question: http://stackoverflow.com/q/52020838
upvote count: 1
accepted answer of: http://stackoverflow.com/q/52020838
downvote count: 0

http://stackoverflow.com/q/52040724
tagged with: dataframe
has answer: http://stackoverflow.com/a/52040759
downvote count: 0
has comment: http://stackoverflow.com/comment/91031915
type: UnansweredQuestion
favorite count: 0
has title: Performing a JSON operation on dataframe column
has comment: http://stackoverflow.com/comment/91031913
type: Question
tagged with: pandas
score: 1
upvote count: 1
tagged with: python
answer count: 1
has body: I have a data frame, where one of the columns is a column of strings, which can be converted by separately with json.loads(string) to a dictionary. I'd like to perform json.loads() on the entire column at once, turning the column of strings, to a column of dictionaries. Is this possible?
tagged with: http://stackoverflow.com/tag/json

http://stackoverflow.com/comment/90868963
has text: Iterating over a data-frame iterates over the names of it's columns...
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51959329

http://stackoverflow.com/q/52045051
has title: Prevent python from converting \x41 to A
type: Question
tagged with: encoding
linked to: http://stackoverflow.com/q/20806560
has body: In my code I receive a bytearray with the value 0x41 as b'\x41'. Printing this value gives b'A'. How can I print it in such a way that i get the result b'\x41'. (Python 3.7) Testcode: print("b'\x41'")
score: 0
accepted answer: http://stackoverflow.com/a/52045256
answer count: 1
tagged with: python-3.x
has answer: http://stackoverflow.com/a/52045256
tagged with: python
duplicate of: http://stackoverflow.com/q/20806560
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91041153

http://stackoverflow.com/q/52025872
has body: How to get a members list from a specific role with !getuser command in discord channel. @bot.command(pass_context=True) async def getuser(ctx): bot replys with their ID 1. @user1#123 2. @user2#123
tagged with: discord
answer count: 4
score: 2
tagged with: python-3.x
downvote count: 0
has answer: http://stackoverflow.com/a/64718830
type: Question
possible better answer: http://stackoverflow.com/a/64718830
type: AnsweredQuestion
tagged with: discord.py
has title: Python get all members list from a specific role
has answer: http://stackoverflow.com/a/62397138
has answer: http://stackoverflow.com/a/52026566
accepted answer: http://stackoverflow.com/a/52026566
upvote count: 2
has answer: http://stackoverflow.com/a/52026563
favorite count: 0
tagged with: python

django-rest-framework
tags question: http://stackoverflow.com/q/52005877
tags question: http://stackoverflow.com/q/52056456
tags question: http://stackoverflow.com/q/52112331
tags question: http://stackoverflow.com/q/51961515
tags question: http://stackoverflow.com/q/51973640
tags question: http://stackoverflow.com/q/52028493
tags question: http://stackoverflow.com/q/52001533
tags question: http://stackoverflow.com/q/52034740
tags question: http://stackoverflow.com/q/52073874
tags question: http://stackoverflow.com/q/52046328
tags question: http://stackoverflow.com/q/52064512
tags question: http://stackoverflow.com/q/52104679
tags question: http://stackoverflow.com/q/52020713
tags question: http://stackoverflow.com/q/52104433
type: Tag
tags question: http://stackoverflow.com/q/51961999
tags question: http://stackoverflow.com/q/51989857
tags question: http://stackoverflow.com/q/52011622
tags question: http://stackoverflow.com/q/52033003
tags question: http://stackoverflow.com/q/52024527
tags question: http://stackoverflow.com/q/52079860
tags question: http://stackoverflow.com/q/51984689
tags question: http://stackoverflow.com/q/51961630
tags question: http://stackoverflow.com/q/51972734
tags question: http://stackoverflow.com/q/52029155
tags question: http://stackoverflow.com/q/51976479
tag name: django-rest-framework
tags question: http://stackoverflow.com/q/52092805
tags question: http://stackoverflow.com/q/51990546
tags question: http://stackoverflow.com/q/52106232
tags question: http://stackoverflow.com/q/52095267
tags question: http://stackoverflow.com/q/52096073
tags question: http://stackoverflow.com/q/52096043
tags question: http://stackoverflow.com/q/52108303
tags question: http://stackoverflow.com/q/52016269
tags question: http://stackoverflow.com/q/52031799
tags question: http://stackoverflow.com/q/52032122
tags question: http://stackoverflow.com/q/52047360
tags question: http://stackoverflow.com/q/51989635
tags question: http://stackoverflow.com/q/51980815
tags question: http://stackoverflow.com/q/52041802
tags question: http://stackoverflow.com/q/52102921
tags question: http://stackoverflow.com/q/51977168

http://stackoverflow.com/q/52019181
tagged with: multiprocessing
type: Question
has answer: http://stackoverflow.com/a/52021667
has answer: http://stackoverflow.com/a/57477730
upvote count: 7
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion
tagged with: pickle
tagged with: python
answer count: 4
has body: this is my code class MusicHandler(object): """ Implements the logic to download musics """ def __init__(self): """ Creates the class object, loads configs, absolute paths and create directories. Does not init download """ # create logger self.logger = getLogger("music logger") self.logger.info("Initializing MusicHandler class object") # load config vars self.configs = utils.get_configs() # load absolute paths self.dir_music = self.configs["music_path"] self.dir_audio = utils.get_path_from_rel(self.configs["audio_path"], base_path=self.dir_music) self.dir_video = utils.get_path_from_rel(self.configs["video_path"], base_path=self.dir_music) self.taboo_path = utils.get_path_from_rel(self.configs["taboo_path"]) # make dir if not exists list(map(utils.make_dir_safe, (self.dir_music, self.dir_audio, self.dir_video))) @run_safe def download_one(self, link, keep_video=False): """ handles the download of one link. keep_video determines if video is saved or deleted. """ self.logger.info(f"Starting download of {link}") if self.is_taboo(link): self.logger.warning("Link is taboo, will skip it.") return name = self.download_video(link) self.logger.info(f"Download of {name} (video) was a success.") self.video_to_audio(name) self.add_to_taboo(link) if not keep_video: self.remove_video(name) self.logger.critical(f"Successfully downloaded {name}. Available at {self.dir_music}.") def get_musics_linear(self, url_list): """ Linear download of all links from list """ for link in url_list: self.download_one(link) @run_safe def get_musics_parallel(self, url_list, num_procs=3): """ Parallel download of all links from list """ with Pool(num_procs) as p: print("here") p.map(self.download_one, url_list) print("there") def is_taboo(self, link): """ Verifies if link exists in the taboo file """ return utils.is_in_file(self.taboo_path, link) def add_to_taboo(self, link): """ Adds link to the taboo file """ utils.append_to_file(self.taboo_path, link) def download_video(self, link): """ Downloads …
downvote count: 0
has answer: http://stackoverflow.com/a/67805772
score: 7
has answer: http://stackoverflow.com/a/60297682
has title: Adding logger causes can't pickle _thread.RLock objects error

http://stackoverflow.com/a/52048166
has comment: http://stackoverflow.com/comment/91203615
answers question: http://stackoverflow.com/q/52047967
has body: import pandas as pd # change names appropriately PURCHASE_ORDER = 'Purchase Order' DELIVERY_DATE = 'Delivery Date' DESIRED_DATE = 'Desired Date' DELAYED_DAYS = 'Delayed Days' df = pd.read_csv('otd.csv', index_col=PURCHASE_ORDER) - &gt;&gt; df Delivery Date Desired Date Purchase Order 001 2014-12-31 2014-12-31 002 2014-12-31 2014-12-31 003 2015-01-05 2015-01-05 004 2015-01-05 2015-01-05 005 2015-02-12 2015-02-11 006 2016-02-13 2016-02-11 The last two deliveries are late. df[DELIVERY_DATE] = pd.to_datetime(df[DELIVERY_DATE]) df[DESIRED_DATE] = pd.to_datetime(df[DESIRED_DATE]) df[DELAYED_DAYS] = df[DELIVERY_DATE] - df[DESIRED_DATE] late_threshold = pd.Timedelta(days=0) late_deliveries = df[DELAYED_DAYS] &gt; late_threshold - &gt;&gt; df[late_deliveries].drop([DELIVERY_DATE, DESIRED_DATE], axis=1) Delayed Days Purchase Order 005 1 days 006 2 days
accepted answer of: http://stackoverflow.com/q/52047967
has comment: http://stackoverflow.com/comment/91047725
type: AcceptedAnswer
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/91047889
has comment: http://stackoverflow.com/comment/91155450
upvote count: 2
has comment: http://stackoverflow.com/comment/91047766
score: 2

http://stackoverflow.com/comment/90892152
type: Comment
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/51963838
has text: Note that SciPy also has the `rfft` function for working with real (instead of complex) numbers.

http://stackoverflow.com/comment/90992402
type: QuestionComment
comment on: http://stackoverflow.com/q/52021003
has text: Do you want to store it?
score: 0
type: Comment

http://stackoverflow.com/q/52035560
has answer: http://stackoverflow.com/a/52035896
has body: I have the list: x=["2018-08-27 15:21:49","2018-08-27 15:21:52","2018-08-27 15:21:56"] y=["5523","3512","3383"] I want the csv will be like ("" is in one cell) "2018-08-27 15:21:49" "5523" "2018-08-27 15:21:52" "3512" but the following code could not work. If I don't use the [row], each cell will be filled with one character. I understand that this will be easy, but would you please offer a help? My brain just go blank and could not figure it out... Thanks! import csv x=["2018-08-27 15:21:49","2018-08-27 15:21:52","2018-08-27 15:21:56"] y=["5523","3512","3383"] L=[] with open("test.csv","w",newline='') as f: writer=csv.writer(f) for i in range(len(x)): row=x[i]+','+y[i] print([row])
type: AnsweredQuestion
tagged with: http://stackoverflow.com/tag/csv
has comment: http://stackoverflow.com/comment/91021564
has comment: http://stackoverflow.com/comment/91021298
tagged with: python
score: -2
favorite count: 0
possible better answer: http://stackoverflow.com/a/52035896
type: Question
accepted answer: http://stackoverflow.com/a/52035759
answer count: 2
upvote count: 1
downvote count: 3
has title: How to separate by comma with csv
has answer: http://stackoverflow.com/a/52035759

http://stackoverflow.com/comment/90929966
type: Comment
score: 1
type: QuestionComment
has text: `rstrip()` removes *any* from the character list, not *all*. For example `"Hello".rstrip('Ao2')` returns `'Hell'`.
comment on: http://stackoverflow.com/q/51990080

http://stackoverflow.com/q/52091437
type: Question
upvote count: 1
favorite count: 0
has title: How to get Star Rating from JPEG files in Python?
has comment: http://stackoverflow.com/comment/91134880
tagged with: python
tagged with: exif
tagged with: metadata
has body: How can I get the star rating info from a jpeg file in python? I've looked through the EXIF info and did not find anything indicating the star rating. However, I can see it in the windows file explorer. Are there anyways that I can get that information with some python packages?
answer count: 0
downvote count: 0
type: UnansweredQuestion
tagged with: python-imaging-library
score: 1
tagged with: image-processing

http://stackoverflow.com/q/51987840
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/90925186
has answer: http://stackoverflow.com/a/51988289
type: Question
has title: What do I have to remove from the Python3 installation to make it impossible to compile scripts
has body: I'm creating a system that will exposed on the Internet. I've done as much as I can do to limit the attack surface, but one important hole remains. The python scripts are only present in their compiled form (.pyc) and the sources (.py) are not present. How can I stop someone transforming their own script into an executable? Are there some parts of python that I can delete so that it will only execute pre-compiled scripts?
score: 0
answer count: 1
tagged with: python-3.x

http://stackoverflow.com/q/51996139
favorite count: 0
has comment: http://stackoverflow.com/comment/90941916
downvote count: 0
score: 6
type: AnsweredQuestion
type: Question
has body: Do I need to use regex here? The content I want looks like: &lt;meta content="text I want to grab" name="description"/&gt; However, there are many objects that start with "meta content=" I want the one that ends in name="description". I'm pretty new at regex, but I thought BS would be able to handle this.
answer count: 1
upvote count: 6
has title: Grabbing meta content with beautiful soup
tagged with: beautifulsoup
has answer: http://stackoverflow.com/a/51996257
accepted answer: http://stackoverflow.com/a/51996257
tagged with: python

http://stackoverflow.com/q/51987490
upvote count: 1
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/90924435
linked to: http://stackoverflow.com/q/111234
score: 0
possible better answer: http://stackoverflow.com/a/51987620
answer count: 3
has title: Rolling the dices game, TypeError: 'str' object is not callable error
has answer: http://stackoverflow.com/a/51987620
has answer: http://stackoverflow.com/a/51987957
favorite count: 0
has comment: http://stackoverflow.com/comment/90924679
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/51987957
has body: I wrote a little game in Python 3, and I want to repeat the dice rolling if the input is not 'stop'. If I write stop it is going to stop the program, so this is working, but when I write something else it is not repeating. Here is the source code: print('Throw the dices, then type stop if you want to stop') from random import * while input != 'stop': random1 = randint(1, 6) random2 = randint(1, 6) print('The numbers are: ', random1,' ', random2) input = input()
tagged with: input
tagged with: python
has answer: http://stackoverflow.com/a/51987568
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90924463

http://stackoverflow.com/comment/90967843
score: 0
comment on: http://stackoverflow.com/q/52008638
type: QuestionComment
type: Comment
has text: 2GB isn't there some filesystem limit in some old filesystems?

http://stackoverflow.com/q/51964983
score: 1
has comment: http://stackoverflow.com/comment/90882438
type: Question
downvote count: 0
has body: I find out that Django 1.7 with pypy2 flush JIT coverage to zero randomly, using vmprof. I don't know why, but when I run the simple Django app, JIT coverage goes back to zero randomly. you can reproduce using https://github.com/gtlim/pypy-django. I run this code in docker container based on ubuntu16.04 UPDATE Thanks for the response. I expected that when I run Django with runserver command PyPy will keep the optimized path on memory after some warm-up time because it's long-running process. But as you can see in the uploaded image, it doesn't keep optimized path and use interpreter instead of JIT. I want to know why PyPy repeats this behavior and how can we resolve it to use PyPy on our production server. First image from vmprof After 1min from vmprof
tagged with: pypy
has title: JIT not work on Django1.7 with PyPy2
favorite count: 0
type: UnansweredQuestion
tagged with: django
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/90880609
answer count: 0

http://stackoverflow.com/comment/91014539
comment on: http://stackoverflow.com/a/52031925
score: 1
type: AnswerComment
has text: `df.at` instead.
type: Comment

http://stackoverflow.com/a/52103697
has body: I would use Pyphen. This module has a Pyphen class used for hyphenation. One of its methods, positions(), returns the number of places in a word where it can be split: &gt;&gt;&gt; from pyphen import Pyphen &gt;&gt;&gt; p = Pyphen(lang='en_US') &gt;&gt;&gt; p.positions('exclamation') [2, 5, 7] If the word "exclamation" can be split in three places, it has four syllables, so you just need to filter all words with more than one split place. . . . But I noted you tagged it as an [t:nltk] question. I'm not experienced with NLTK myself but the question suggested by @Jules has a nice suggestion in this aspect: to use the cmudict module. It gives you a list of pronunciations of a word in American English: &gt;&gt;&gt; from nltk.corpus import cmudict &gt;&gt;&gt; d = cmudict.dict() &gt;&gt;&gt; pronounciations = d['exasperation'] &gt;&gt;&gt; pronounciations 'EH2', 'K', 'S', 'AE2', 'S', 'P', 'ER0', 'EY1', 'SH', 'AH0', 'N' Luckily, our fist word has only one pronounciation. It is represented as a list of strings, each one representing a phoneme: &gt;&gt;&gt; phonemes = pronounciations[0] &gt;&gt;&gt; phonemes ['EH2', 'K', 'S', 'AE2', 'S', 'P', 'ER0', 'EY1', 'SH', 'AH0', 'N'] Note that vowel phonemes have a number at the end, indicating stress: Vowels are marked for stress (1=primary, 2=secondary, 0=no stress). E.g.: NATURAL 1 N AE1 CH ER0 AH0 L So, we just need to count the number of phonemes with digits at the end: &gt;&gt;&gt; vowels = [ph for ph in phonemes if ph[-1].isdigit()] &gt;&gt;&gt; vowels ['EH2', 'AE2', 'ER0', 'EY1', 'AH0'] &gt;&gt;&gt; len(vowels) 5 . . . Not sure which is the best option but I guess you can work your problem out from here.
type: Answer
answers question: http://stackoverflow.com/q/52103070
score: 0

http://stackoverflow.com/q/51996982
score: 0
answer count: 2
tagged with: binary-tree
tagged with: python
possible better answer: http://stackoverflow.com/a/51997063
has body: class Solution: def findDuplicateSubtrees(self, root): self.res = [] self.dic = {} self.dfs(root) return self.res def dfs(self, root): if not root: return '#' tree = self.dfs(root.left) + self.dfs(root.right) + str(root.val) if tree in self.dic and self.dic[tree] == 1: self.res.append(root) self.dic[tree] = self.dic.get(tree, 0) + 1 return tree This is a solution for getting all duplicate subtrees given a binary tree. I am not sure what tree = self.dfs(root.left) + self.dfs(root.right) + str(root.val) is trying to give. I know it's trying to do a postorder traversal, but how does this part actually work? It would be great if anyone can follow through this code. Thanks.
type: AnsweredQuestion
has title: Not sure how this recursion works
accepted answer: http://stackoverflow.com/a/51997101
type: Question
tagged with: recursion
has answer: http://stackoverflow.com/a/51997063
has answer: http://stackoverflow.com/a/51997101

http://stackoverflow.com/comment/90920901
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51977855
score: 1
has text: What are the various versions of Python you're using here? If the conda version is Python 3.7, then [`async` is a reserved keyword](https://docs.python.org/3/whatsnew/3.7.html) and you should use Python 3.6, `conda create -n airflow pip setuptools python=3.6`

http://stackoverflow.com/a/52058840
answers question: http://stackoverflow.com/q/52058626
upvote count: 6
has body: According to the documentation you can use the discord.on_reaction_add(reaction, user) event to do something like this @client.event async def on_reaction_add(reaction, user): if reaction.emoji == '': #do stuff
type: Answer
downvote count: 0
score: 6

graphics
tag name: graphics
type: Tag
tags question: http://stackoverflow.com/q/51967105

http://stackoverflow.com/q/52041460
score: 1
type: Question
tagged with: mutex
has answer: http://stackoverflow.com/a/52041575
answer count: 1
downvote count: 0
has title: Is this the correct way to use variable between 2 Threads?
favorite count: 0
tagged with: python-3.x
tagged with: multithreading
accepted answer: http://stackoverflow.com/a/52041575
upvote count: 1
tagged with: python
has body: I have a script that read data from Serial Port, so I have an infinite loop that always fill my data to global variable, and also I schedule a function that run every X seconds to post in the database, and this function also use the same global variable. Here's a small example I create it to show you my situation : import serial import schedule import threading shared_var = [] def save_to_db(): print(threading.current_thread()) global shared_var for l in shared_var: print(l) shared_var.clear() def run_threaded(job_func): job_thread = threading.Thread(target=job_func) job_thread.start() ser = serial.Serial() # initialize the serial ser.baudrate = 115200 # set the baud rate : default 115200 ser.port = "/dev/ttyUSB0" # set the port to use ser.timeout = 30 ser.write_timeout = None if not ser.is_open: ser.open() # Open port ser.write(b'scan=01\r\n') # Stop scan if already started schedule.every(5).seconds.do(run_threaded, save_to_db) while 1: schedule.run_pending() line = ser.readline() shared_var.append(line) print(threading.current_thread()) Is this code can cause a problem ? more specific what will happen if the MainThread (the one that read from Serail Port and write to shared_var) write to the shared variable between the 2 thread and in the same moment the other Thread read from the variable, is This will cause a problem because the 2 threads gonna access the same global variable in the same time ? and if yes It's a problem should I use mutex mechanism for that ?
type: AnsweredQuestion

http://stackoverflow.com/comment/91120001
has text: No access to Python interpreter right now, please comment if something doesn't work or does not solve your problem :)
type: Comment
comment on: http://stackoverflow.com/a/52084842
score: 0
type: AnswerComment

elasticsearch-dsl-py
tags question: http://stackoverflow.com/q/51963116
type: Tag
tag name: elasticsearch-dsl-py
tags question: http://stackoverflow.com/q/52089760

http://stackoverflow.com/q/52020434
has comment: http://stackoverflow.com/comment/90995453
type: Question
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/90993531
tagged with: pandas
has comment: http://stackoverflow.com/comment/90992389
tagged with: python
has title: Ranking on multiple columns and labeling ties between obsersations in pandas
favorite count: 0
has answer: http://stackoverflow.com/a/52024930
upvote count: 2
type: UnansweredQuestion
score: 2
has comment: http://stackoverflow.com/comment/90993603
has body: I have a df like: group name sum count max_size 1 1 aaa 3 2 4 2 1 bbb 3 1 4 3 1 ccc 2 2 4 4 1 ddd 2 2 4 5 1 eee 1 0 4 6 2 aaa 3 2 3 7 2 bbb 3 1 3 8 2 ccc 2 3 3 9 2 ddd 2 1 3 10 3 aaa 3 4 4 11 3 bbb 3 2 4 12 3 ccc 2 5 4 13 3 ddd 2 1 4 14 3 eee 2 1 4 15 3 fff 2 1 4 I would like to label each observation according to this decision reasoning: First groupby() by group and then arrange the names by sum and then by count in a descending order Select the top n elements as in max_size, which is the max number of elements to be selected within the group In a case like group 2, there is a max size of elements to be selected (3) and 3 clear candidates. group name decision sum count max_size 1 2 aaa winner 3 2 3 2 2 bbb winner 3 1 3 3 2 ccc winner 2 3 3 4 2 ddd loser 2 1 3 aaa, bbb and ccc are the top 3 ordering first by sum and then count, while ddd is out. For group 3 though: group name decision sum count max_size 1 3 aaa winner 3 4 4 2 3 bbb winner 3 2 4 3 3 ccc winner 2 5 4 4 3 ddd unclear 2 1 4 5 3 eee unclear 2 1 4 6 3 fff unclear 2 1 4 aaa, bbb, ccc are the top 3 but the 4th element (given that max_size = 4) is unclear. ddd, eee and fff have the same count and same sum. I would like to reach a final dataframe labeling the observations like this: name decision sum count max_size 1 aaa winner 3 2 4 2 bbb winner 3 1 4 3 ccc unclear 2 2 4 4 ddd unclear 2 2 4 5 eee winner 1 0 4 6 aaa winner 3 2 3 7 bbb winner 3 1 3 8 ccc winner 2 3 3 9 ddd loser 2 1 3 10 aaa winner 3 4 4 11 bbb winner 3 2 4 12 ccc winner 2 5 4 13 ddd unclear 2 1 4 14 eee unclear 2 1 4 15 fff unclear 2 1 4 Reproducible example: {'group': {0: 1, 1: 1, 2: 1, 3: 1, 4: 1, 5: 2, 6: 2, 7: 2, 8: 2, 9: 3, 10: 3, 11: 3, 12: 3, 13: 3, 14: 3}, 'name': {0: 'aaa', 1: 'bbb', 2: 'ccc', 3: 'ddd', 4: 'eee', 5: 'aaa', 6: 'bbb', 7: 'ccc', 8: 'ddd', 9: 'aaa', 10: 'bbb', 11: 'ccc', 12: 'ddd', 13: 'eee', 14: 'fff'}, 'decision': {0: 'winner', 1: 'winner', 2: 'unclear', 3: 'unclear', 4: 'winner', 5: 'winner', 6: 'winner', 7: 'winner',…

http://stackoverflow.com/a/53667554
answers question: http://stackoverflow.com/q/52085191
score: 10
upvote count: 12
has body: There is a useful step by step guide here: https://learn.microsoft.com/en-us/sql/connect/python/pyodbc/step-1-configure-development-environment-for-pyodbc-python-development?view=sql-server-2017 For reference, the steps in this guide (windows) are (assuming you already have python installed): Install the Microsoft ODBC Driver for SQL Server on Windows, from https://learn.microsoft.com/en-us/sql/connect/odbc/windows/system-requirements-installation-and-driver-files?view=sql-server-2017#installing-microsoft-odbc-driver-for-sql-server Open cmd.exe as an administrator Navigate to your python scripts folder containing pip Type: pip install pyodbc
type: Answer
downvote count: 2

http://stackoverflow.com/q/52067475
type: Question
has title: Graphing multi-dimensional K-means cluster NLP python
tagged with: k-means
answer count: 1
tagged with: scatter-plot
has answer: http://stackoverflow.com/a/52078652
has body: I have a multidimensional vector designed for an NLP Classifier. Here's the dataframe (text_df): I used a TfidfVectorizer to create the vector: from sklearn.feature_extraction.text import TfidfVectorizer tfidf_v = TfidfVectorizer(max_df=0.5, max_features=13000, min_df=5, stop_words='english', use_idf=True, norm=u'l2', smooth_idf=True ) X = tfidf_v.fit_transform(corpus).toarray() y = text_df.iloc[:,1].values Shape of X is (13834, 2701). I used 7 clusters for KMeans: from sklearn.cluster import KMeans kmeans = KMeans(n_clusters=7,random_state=42) I tried using PCA, but I'm not sure if the graph looks right. from sklearn.decomposition import PCA X_pca = PCA(2).fit_transform(X) plt.scatter(X_pca[:,0],X_pca[:,1],c=y_kmeans) plt.title("Clusters") plt.legend() plt.show() Is this normal for NLP based clusters? I was hoping for more distinctive clusters. Is there a way to clean up this cluster graph? (i.e. clearer groupings, distinct boundaries, cluster points closer together, etc.).
score: 0
has comment: http://stackoverflow.com/comment/91137506
tagged with: nlp
tagged with: dimensionality-reduction
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/comment/91106893
type: QuestionComment
comment on: http://stackoverflow.com/q/52077043
type: Comment
score: 0
has text: I wish I can upload the file directly here, but let me try uploading a pic of it

http://stackoverflow.com/q/51976517
upvote count: 1
has title: Python - renaming files twice with os
tagged with: python-os
has comment: http://stackoverflow.com/comment/90903954
score: 1
type: Question
has comment: http://stackoverflow.com/comment/90904439
downvote count: 0
answer count: 1
has answer: http://stackoverflow.com/a/51977180
favorite count: 0
has comment: http://stackoverflow.com/comment/90904334
tagged with: python
tagged with: regex
has body: I am currently working on a script to take raw text files, place them in correct year folders based on a version number system, and rename them so that our devs can integrate them into our product easily. The file in question is called APR30CaseRVU-1Day.txt. I need this to be in the form refAPRCaseRVU-1Day.txt. Append ref, remove 30, keep 1Day. The script works fine for the other files that do not have this extra "1Day". I'm a beginner so I'm sure my workflow is shit but my idea was to use os.rename twice. Once to remove the characters, and then split on the hyphen to add the "1" back in to the filename, but when I print the filename after the first os.rename it still has 30 and 1. Anyone have any tips to do this more effectively? folder = r"C:\Users\xx\Desktop\Python Final Project\Raw" import os import re import shutil for root, dirs, filenames in os.walk(folder): for filename in filenames: srcpath = os.path.join(root, filename) #split the filename so that we can rename accordingly below, filename_split[0] = filename, filename_split[1] = file ext filename_split = os.path.splitext(filename) name = filename_split[0] ext = filename_split[1] newfolder = '' destpath = os.path.join(newfolder, "ref" + re.sub(r'\d', '', filename_split[0]) + filename_split[1]) #first step: remove AP files entirely from directory if filename.startswith("AP27"): os.remove(os.path.join(folder, filename)) #the rest include a version number that must be routed to the correct year folder directory created above elif filename.__contains__("30") and filename.__contains__("Day"): newfolder = r"C:\Users\xx\Desktop\Python Final Project\Raw\2013" os.rename(os.path.join(root, filename), os.path.join(newfolder, "ref" + re.sub(r'\d', '', filename_split[0]) + filename_split[1])) print(filename) day_name = re.split(r'[\s-]+', filename) print(day_name) first_name = day_name[0] last_name = day_name[1] os.rename(os.path.join(newfolder, filename), os.path.join(newfolder, "ref" + first_name + '1' + last_name))
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90904174

http://stackoverflow.com/comment/91080353
score: 0
type: Comment
has text: No exception is raised when I call `MyEnum('a')`. (Python 3.7 and stdlib `enum.Enum`)
comment on: http://stackoverflow.com/a/52064774
type: AnswerComment

http://stackoverflow.com/q/52070293
answer count: 4
type: AnsweredQuestion
tagged with: linear-regression
type: Question
upvote count: 4
tagged with: numpy
has comment: http://stackoverflow.com/comment/91090376
accepted answer: http://stackoverflow.com/a/52071283
has title: Efficient online linear regression algorithm in python
downvote count: 0
tagged with: scikit-learn
score: 4
has body: I got a 2-D dataset with two columns x and y. I would like to get the linear regression coefficients and interception dynamically when new data feed in. Using scikit-learn I could calculate all current available data like this: from sklearn.linear_model import LinearRegression regr = LinearRegression() x = np.arange(100) y = np.arange(100)+10*np.random.random_sample((100,)) regr.fit(x,y) print(regr.coef_) print(regr.intercept_) However, I got quite big dataset (more than 10k rows in total) and I want to calculate coefficient and intercept as fast as possible whenever there's new rows coming in. Currently calculate 10k rows takes about 600 microseconds, and I want to accelerate this process. Scikit-learn looks like does not have online update function for linear regression module. Is there any better ways to do this?
possible better answer: http://stackoverflow.com/a/77387867
has answer: http://stackoverflow.com/a/77387867
has answer: http://stackoverflow.com/a/71024232
has comment: http://stackoverflow.com/comment/91090344
favorite count: 0
has comment: http://stackoverflow.com/comment/91090822
has answer: http://stackoverflow.com/a/69514201
has answer: http://stackoverflow.com/a/52071283
tagged with: python

http://stackoverflow.com/q/52041802
has body: I am trying to mock the return_value for a MagicMock instance as a PropertyMock but it appears to be returning the PropertyMock object without invoking it i.e. does not return the actual value. class MySerializer(serializers.ModelSerializer): class Meta: model = MyModel # ... fields = ( "my_field" ) my_field = serializers.SerializerMethodField() def get_my_field(self, instance): other_models = instance.other_models.filter(stuff="stuff") if other_models: # returns &lt;class 'unittest.mock.PropertyMock'&gt; instead of an actual value print(type(other_models.get().my_property)) # throws error since it isn't receiving a string return ujson.loads(other_models.get().my_property) return {} # test case def test_hello(mocker): expected_value = ujson.dumps({'hello': 2}) instance_mock = mocker.MagicMock() other_model_mock = mocker.MagicMock() other_model_mock.get().my_property = mocker.PropertyMock(return_value=expected_value) instance_mock.other_models.filter.return_value = other_model_mock serializer = MySerializer() observed_value = serializer.get_my_field(instance_mock) assert expected_value == observed_value
upvote count: 1
type: Question
tagged with: pytest-django
answer count: 1
downvote count: 0
tagged with: django-rest-framework
favorite count: 0
tagged with: django
tagged with: python
has title: Pytest PropertyMock as return_value for MagicMock does not get invoked
type: AnsweredQuestion
tagged with: pytest
score: 1
has answer: http://stackoverflow.com/a/52042238
accepted answer: http://stackoverflow.com/a/52042238

http://stackoverflow.com/comment/90905324
comment on: http://stackoverflow.com/a/51965149
type: Comment
has text: Does the output must be sorted by the order of the ba list?
score: 0
type: AnswerComment

http://stackoverflow.com/q/52065898
has body: I'm having some issue how to actually calling the next player from LIST by sequence. Basically, I need to check from p_record LIST that contains the player names. def main(): attempts = 0 white = 0 wrong = 0 score = 0 black = 0 game = True p_record = [] whiteblack = [] colors = ['B', 'R', 'Y', 'O', 'G', 'P'] color_code = random.sample(colors, 4) print ("HIDDEN CODE", color_code) num = int(input('Please enter number of players: ')) for i in range(num): names = input('Please enter a name: ') p_record.append([names, 0, 0]) print(p_record) print(len(p_record)) print(names + ",", "make a guess of 4 colors from RGBYOP: ") player_guess = input("").upper() for i in range(len(player_guess)): if player_guess[i] == color_code[i]: black += 1 score += 5 whiteblack.append("B") if player_guess[i] != color_code[i] and player_guess[i] in color_code: white += 1 score += 1 whiteblack.append("W") else: whiteblack.append("") color_codeString = ''.join(color_code) whiteblackString = ''.join(whiteblack) print("Result", whiteblackString) print("Current player:", names, "Current Score:", score % score) print("Current player:", names, "Updated Score:", score) if(player_guess == color_codeString): print("Winner: ", p_record) main() Here is the outcome that I wanted. Enter number of players: 3 Enter player's name: alan Enter player's name: betty Enter player's name: cindy Alan, make a guess of 4 colors from RGBYOP: BYOP Result WWB Current Player: Alan Current Score: 0 Current Player: Alan Updated Score: 7 Betty, make a guess of 4 colors from RGBYOP: BYOR Result WB Current Player: Betty Current Score: 0 Current Player: Betty Updated Score: 0 Cindy, make a guess of 4 colors from RGBYOP: BYPG Result WWWB Current Player: Cindy Current Score: 0 Current Player: Cindy Updated Score: 1 Alan, make a guess of 4 colors from RGBYOP: BPGY Result BBBB Current Player: Alan Current Score: 7 Current Player: Alan Updated Score: 22 Correct guess! [['Alan', 22, 2], ['Betty', 0, 0], ['Cindy', 1, 0]] Winner: ['Alan…
has comment: http://stackoverflow.com/comment/91082331
score: 1
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/91082383
has answer: http://stackoverflow.com/a/52066220
linked to: http://stackoverflow.com/q/23294658
has title: Python - How to call in sequence of next player in LIST
tagged with: python
type: AnsweredQuestion
tagged with: list
upvote count: 2
has comment: http://stackoverflow.com/comment/91082280
accepted answer: http://stackoverflow.com/a/52066220
downvote count: 1
type: Question

http://stackoverflow.com/comment/92471758
type: AnswerComment
has text: @user4815162342: let me try to rephrase this then: yes, I think it is possible to build a win32 shim that will be close to the POSIX behaviour. However, that will be a lot of work, time that would be better spent in making the asyncio library itself take care of the underlying issue natively (e.g. by poking the win32 console and pipe APIs from C). Until then, it is possible to produce shims that meet *specific usecases*; mine here aims to work for line-based communication with a parent process, for which using a thread executor is sufficient. I'm not going to spend more time on it.
type: Comment
comment on: http://stackoverflow.com/a/52702646
score: 0

http://stackoverflow.com/comment/91065430
has text: So it's problem with your question as your code contains only 2 occurrences of the keyword argument. Your error report certainly contains the line number in your code where the TypeError exception occurred. Analyze that line.
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52056871

http://stackoverflow.com/comment/90963236
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52006634
score: 1
has text: Usages in PyCharm are - if i recall correctly - detected through imports, etc. But that does not mean it can not be imported for example through a string, etc. This is a consequence of the "hyperdynamic" nature of Python: it is impossible to determine *all* possible scenario's of usage.

http://stackoverflow.com/q/51987069
has comment: http://stackoverflow.com/comment/90927480
has comment: http://stackoverflow.com/comment/90928133
type: UnansweredQuestion
upvote count: 1
has comment: http://stackoverflow.com/comment/90927931
type: Question
downvote count: 5
score: -4
tagged with: http://stackoverflow.com/tag/r
has title: Split a Matrix file into multiple files based on column name
has answer: http://stackoverflow.com/a/51987133
answer count: 1
has body: I have a large tab delimited file with thousands of columns and many thousands of line. It looks like: ID A_1 A_2 A_3 B_1 B_3 B_4 C_2 C_3 C_5 xx 01 02 03 04 05 06 07 08 09 xy 03 05 33 44 15 26 27 08 09 I want to split this table in to multiple files: # A.txt ID A_1 A_2 A_3 xx 01 02 03 xy 03 05 33 # B.txt ID B_1 B_3 B_4 xx 04 05 06 xy 44 15 26 # C.txt ID C_2 C_3 C_5 xx 07 08 09 xy 27 08 09 So, file name would be the column header prefix. Id column is fixed in each file. Rest of the columns in each file is based on common prefix before underscore. How can I do it in Linux/Bash/Perl/python command?
tagged with: python
favorite count: 0

http://stackoverflow.com/comment/91026924
comment on: http://stackoverflow.com/q/52038317
type: QuestionComment
has text: add code snippet please !!!
type: Comment
score: 1

http://stackoverflow.com/q/52096069
score: -1
has body: I tried to do an union between two Spark DataFrame in Python, one of them sometime is empty, I did a test if, to return that full. This following a small code for example, it return an error: &gt;&gt;&gt; from pyspark.sql.types import * &gt;&gt;&gt; fulldataframe = [StructField("FIELDNAME_1",StringType(), True),StructField("FIELDNAME_2", StringType(), True),StructField("FIELDNAME_3", StringType(), True)] &gt;&gt;&gt; schema = StructType([]) &gt;&gt;&gt; &gt;&gt;&gt; dataframeempty = sqlContext.createDataFrame(sc.emptyRDD(), schema) &gt;&gt;&gt; resultunion = sqlContext.createDataFrame(sc.emptyRDD(), schema) &gt;&gt;&gt; if (fulldataframe.isEmpty()): ... resultunion = dataframeempty ... elif (dataframeempty.isEmpty()): ... resultunion = fulldataframe ... else: ... resultunion=fulldataframe.union(dataframeempty) ... Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; AttributeError: 'list' object has no attribute 'isEmpty' &gt;&gt;&gt; Someone can tell me where's the fault ?
type: Question
answer count: 1
favorite count: 0
accepted answer: http://stackoverflow.com/a/52097358
tagged with: apache-spark
tagged with: python
upvote count: 2
has title: Union of two Spark dataframes
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52097358
downvote count: 3

http://stackoverflow.com/q/52105713
type: AnsweredQuestion
score: 0
downvote count: 2
has comment: http://stackoverflow.com/comment/91162683
linked to: http://stackoverflow.com/q/15479928
has comment: http://stackoverflow.com/comment/91187449
type: Question
has comment: http://stackoverflow.com/comment/91162716
has answer: http://stackoverflow.com/a/52105819
answer count: 1
has body: I have dictionary with values as lists: myDict = {'id1': ["name1","Type1","Value_1"], 'id2': ["name2","Type1","Value_2"], 'id3': ["name1","Type2","Value_3"], 'id4': ["name1","Type1","Value_4"] } I wanna iterate through dictionary and look if Name and Type pair is already in list - replace "Type 1" value by any other and resulting dictionary will be: myDict = {'id1': ["name1","Type1","Value_1"], 'id2': ["name2","Type1","Value_2"], 'id3': ["name1","Type2","Value_3"], 'id4': ["name1","Modified_Type 1","Value_4"] } Have no idea currently how to deal with it with Python It's mostly question about comparing value[0], value[1] and if both are the same in some other list - replace it. I'm trying to iterate through existing dictionary and compare if it's values aren't in newDictionary, but obviously I'm checking if those values separately exist in newDict values not as pair: myDict = {'id1': ["name1","Type1","Value_1"], 'id2': ["name2","Type1","Value_2"], 'id3': ["name1","Type2","Value_3"], 'id4': ["name1","Type1","Value_4"] } newDict = {} for key, value in myDict.items(): if value[0] not in newDict.values() and value[1] not in newDict.values(): newDict[key] = value else: newDict[key] = [value[0],"Some modified value",value[2]] print (newDict)
favorite count: 0
has comment: http://stackoverflow.com/comment/91162748
has comment: http://stackoverflow.com/comment/91172814
has title: Check if there are duplicate pair in lists and replace one of the value
upvote count: 2
accepted answer: http://stackoverflow.com/a/52105819
has comment: http://stackoverflow.com/comment/91164546
tagged with: python
has comment: http://stackoverflow.com/comment/91162631
has comment: http://stackoverflow.com/comment/91162520

http://stackoverflow.com/comment/91081747
score: 0
type: Comment
type: QuestionComment
has text: @MichealJRoberts any ideas?
comment on: http://stackoverflow.com/q/52065617

http://stackoverflow.com/a/51957969
type: Answer
answers question: http://stackoverflow.com/q/51957872
has comment: http://stackoverflow.com/comment/90866389
has body: you need to use a regular expression (re): import re walmartIDS[re.match(r'^[-+]?[0-9]+$', walmartIDS.WalmartIDS) is not None]
score: 0

http://stackoverflow.com/comment/90967930
has text: I think your only choice there is use the current time when you receive the event. There is not way to use `Message.timestamp`, because no `Message` is being sent for these events.
type: AnswerComment
comment on: http://stackoverflow.com/a/52008081
score: 0
type: Comment

http://stackoverflow.com/comment/90891907
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51969969
has text: Now you have 3 solutions :) That's why I asked to share the code
score: 0

http://stackoverflow.com/q/51992770
has answer: http://stackoverflow.com/a/51993489
tagged with: http://stackoverflow.com/tag/r
tagged with: python
type: AnsweredQuestion
tagged with: rstudio
accepted answer: http://stackoverflow.com/a/51993489
tagged with: tensorflow
type: Question
score: 0
has title: Error in tensorflow for R example
answer count: 1
has body: I am new to Tensorflow. I heard really great things about the tensorflow interface to R. I am however finding it difficult to run example listed here: https://tensorflow.rstudio.com/tensorflow/articles/examples/linear_regression_multiple.html The specific problem is in the following lines while (TRUE) { + session$run(optimizer, feed_dict = feed_dict) + current_cost &lt;- session$run(cost, feed_dict = feed_dict) + if (last_cost - current_cost &lt; epsilon) break + last_cost &lt;- current_cost + } This throws the following error : Error in py_call_impl(callable, dots$args, dots$keywords) : TypeError: Fetch argument &lt;tensorflow.python.training.gradient_descent.GradientDescentOptimizer object at 0x126eaaf50&gt; of &lt;tensorflow.python.training.gradient_descent.GradientDescentOptimizer object at 0x126eaaf50&gt; has invalid type &lt;class 'tensorflow.python.training.gradient_descent.GradientDescentOptimizer'&gt;, must be a string or Tensor. (Can not convert a GradientDescentOptimizer into a Tensor or Operation.) The only thing I have changed from the above example is : tf$global_variables_initializer to tf$initialize_all_variables Anyone faced similar error?

http://stackoverflow.com/comment/133918982
comment on: http://stackoverflow.com/q/52003490
has text: What if the input values can exceed 0xff? Do you care?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91125534
has text: `mock_mkdir.assert_called_with("any path")`? is that what you needed?
score: 0
comment on: http://stackoverflow.com/q/52085969
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/90941990
score: 0
comment on: http://stackoverflow.com/q/51996262
has text: Please clarify your question
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52058400
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91067412
tagged with: method-resolution-order
has comment: http://stackoverflow.com/comment/91066892
has answer: http://stackoverflow.com/a/52058615
has body: [using Python3.6] I have a design where Grandchild inherits a Parent and Child (of Parent). class Parent: def aux_func(self): return "[parent aux]" def main_func(self): print("[parent main]" + self.aux_func()) class Child(Parent): def aux_func(self): return "[child aux]" def main_func(self): print("[child main]" + self.aux_func()) class Grandchild(Child, Parent): @classmethod def do_something(cls): g = Grandchild() g.main_func() super(Child, g).main_func() Parent.main_func(g) Grandchild.do_something() the result is - [child main][child aux] [parent main][child aux] [parent main][child aux] Calling a function from Parent causes the aux_func to resolve from the Child class. I tried to go through MRO process but can't explain functions being called from different classes. Could someone help me with Why this is happening ? What would be a workaround to achieve [parent main][parent aux] ?
accepted answer: http://stackoverflow.com/a/52058615
type: Question
answer count: 1
tagged with: multiple-inheritance
has title: Python using super with grandchild inheriting parent and child
tagged with: python-3.6
score: 0
has comment: http://stackoverflow.com/comment/91067086
has comment: http://stackoverflow.com/comment/91067033
tagged with: python

http://stackoverflow.com/q/52035617
score: 1
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/52035751
has comment: http://stackoverflow.com/comment/91021355
favorite count: 0
tagged with: ord
tagged with: python-3.x
upvote count: 2
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91021448
tagged with: python
has body: I am currently trying to figure out a coding issue where I receive a space at the end of my output when I am using ord. If anyone could please help me to fix this error in my code, I will be very grateful. x = input("Dessert idea: ") for i in x: print(ord(i),end=" ") The output always spits out space at the end of the code along with the numbers, eg: 89 101 101 116 115" " *Space is shown using quotation marks *
downvote count: 1
has answer: http://stackoverflow.com/a/52036433
has title: How to remove the space at the end of my output

http://stackoverflow.com/comment/90919757
has text: Have you figured it out with Python official example? :)
comment on: http://stackoverflow.com/q/51977594
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/52077845
has body: Use pandas text functions with str and for select 4. lists use str[3], because python counts from 0: df['page'] = df['Url'].str.split('/').str[3] Or if performance is important use list comprehension: df['page'] = [x.split('/')[3] for x in df['Url']] print (df) User Url \ 0 1 http://www.mycompany.com/Overview/Get 1 2 http://www.mycompany.com/News 2 3 http://www.mycompany.com/Accountinfo 3 4 http://www.mycompany.com/Personalinformation/I... page 0 Overview 1 News 2 Accountinfo 3 Personalinformation
type: AcceptedAnswer
downvote count: 0
type: Answer
score: 4
accepted answer of: http://stackoverflow.com/q/52077814
answers question: http://stackoverflow.com/q/52077814
upvote count: 4

pandas
tags question: http://stackoverflow.com/q/52044348
tags question: http://stackoverflow.com/q/52075870
tags question: http://stackoverflow.com/q/51969476
tags question: http://stackoverflow.com/q/51980469
tags question: http://stackoverflow.com/q/52074623
tags question: http://stackoverflow.com/q/52092887
tags question: http://stackoverflow.com/q/52100444
tags question: http://stackoverflow.com/q/52053415
tags question: http://stackoverflow.com/q/51982073
tags question: http://stackoverflow.com/q/52010037
tags question: http://stackoverflow.com/q/52087029
tags question: http://stackoverflow.com/q/52080683
tags question: http://stackoverflow.com/q/52005058
tags question: http://stackoverflow.com/q/52092405
tags question: http://stackoverflow.com/q/51959431
tags question: http://stackoverflow.com/q/52046690
tags question: http://stackoverflow.com/q/52002236
tags question: http://stackoverflow.com/q/51959658
tags question: http://stackoverflow.com/q/52086462
tags question: http://stackoverflow.com/q/52111092
tags question: http://stackoverflow.com/q/52080334
tags question: http://stackoverflow.com/q/52106643
tags question: http://stackoverflow.com/q/52056715
tags question: http://stackoverflow.com/q/51972853
tags question: http://stackoverflow.com/q/52085394
tags question: http://stackoverflow.com/q/52082351
tags question: http://stackoverflow.com/q/52091033
tags question: http://stackoverflow.com/q/51997349
tags question: http://stackoverflow.com/q/51981449
tags question: http://stackoverflow.com/q/52046307
tags question: http://stackoverflow.com/q/52011519
tags question: http://stackoverflow.com/q/52043117
tags question: http://stackoverflow.com/q/52075814
tags question: http://stackoverflow.com/q/52112130
tags question: http://stackoverflow.com/q/52043920
tags question: http://stackoverflow.com/q/52063094
tags question: http://stackoverflow.com/q/51976145
tags question: http://stackoverflow.com/q/51968722
tags question: http://stackoverflow.com/q/51982858
tags question: http://stackoverflow.com/q/51958471
tags question: http://stackoverflow.com/q/52012513
tags question: http://stackoverflow.com/q/52060033
tags question: http://stackoverflow.com/q/51962211
tags question: http://stackoverflow.com/q/51966450
tags question: http://stackoverflow.com/q/52071768
tags question: http://stackoverflow.com/q/52007489
tags question: http://stackoverflow.com/q/51994654
tags question: http://stackoverflow.com/q/52012587
tags question: http://stackoverflow.com/q/52076172
tags question: http://stackoverflow.com/q/51997818
tags question: http://stackoverflow.com/q/52046064
tags question: http://stackoverflow.com/q/52091011
tags question: http://stackoverflow.com/q/52092078
tags question: http://stackoverflow.com/q/51979636
tags question: http://stackoverflow.com/q/52059723
tags question: http://stackoverflow.com/q/52001241
tags question: http://stackoverflow.com/q/51971502
tags question: http://stackoverflow.com/q/52026405
tags question: http://stackoverflow.com/q/52105311
tags question: http://stackoverflow.com/q/52041232
tags question: http://stackoverflow.com/q/52063696
tags question: http://stackoverflow.com/q/52086863
tags question: http://stackoverflow.com/q/51989470
tags question: http://stackoverflow.com/q/51997618
tags question: http://stackoverflow.com/q/52098283
tags question: http://stackoverflow.com/q/52031908
tags question: http://stackoverflow.com/q/52048345
tags question: http://stackoverflow.com/q/52053522
tags question: http://stackoverflow.com/q/51986601
tags question: http://stackoverflow.com/q/52030490
tags question: http://stackoverflow.com/q/52023409
tags question: http://stackoverflow.com/q/52004234
tags question: http://stackoverflow.com/q/51994045
tags question: http://stackoverflow.com/q/52014819
tags question: http://stackoverflow.com/q/52012017
tags question: http://stackoverflow.com/q/52027851
tags question: http://stackoverflow.com/q/51959484
tags question: http://stackoverflow.com/q/52008200
tags question: http://stackoverflow.com/q/52038098
tags question: http://stackoverflow.com/q/52100572

http://stackoverflow.com/a/52081974
has comment: http://stackoverflow.com/comment/91117018
has comment: http://stackoverflow.com/comment/91116651
has comment: http://stackoverflow.com/comment/91117083
has comment: http://stackoverflow.com/comment/91115291
has comment: http://stackoverflow.com/comment/91121385
has comment: http://stackoverflow.com/comment/91118042
answers question: http://stackoverflow.com/q/52081913
type: AcceptedAnswer
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/91116832
has comment: http://stackoverflow.com/comment/91123925
score: 1
has comment: http://stackoverflow.com/comment/91116119
has body: replace does not modify the original string. You need to reassign to it for every sentence: for sentence in boilerplates: corpus_jn = corpus_jn.replace(sentence, '') Or you can use a regex: import re regex = '|'.join(map(re.escape, boilerplates)) corpus_jn = re.sub(regex, '', corpus_jn) This will probably be more efficient since it iterates over the string only once. Just to clarify: your original codes does not do any replacement at all. The argument to str is a generator expression which produces a generator object that does nothing until something iterates over it. The call to str however does not iterate over it, it just transforms it into that &lt;generator object ...&gt; text. Even if you consumed the generator properly using ''.join or a list-comprehension you would not obtain what you expected: &gt;&gt;&gt; text = 'hello 123 hello bye' &gt;&gt;&gt; boilerplates = ['hello', 'bye'] &gt;&gt;&gt; [text.replace(sentence, '') for sentence in boilerplates] [' 123 bye', 'hello 123 hello '] As you can see the first time the word hello is replaced from text but the second iteration is still done on the original value and hence you get a string with no bye but that still contains hello. To remove both you have to use the solutions above, you can't do that using a generator in that way.
upvote count: 1
accepted answer of: http://stackoverflow.com/q/52081913
has comment: http://stackoverflow.com/comment/91117159
has comment: http://stackoverflow.com/comment/91116920

http://stackoverflow.com/a/51982005
type: Answer
has body: You can iterate over each line of a file with a for loop, but calling next() on the file will skip the first one and the for loop will continue from the 2nd: with open('file.txt') as f: f = iter(f) first_line = next(f) for line in f: # .... do stuff with each line...
answers question: http://stackoverflow.com/q/51981951
score: 0

http://stackoverflow.com/q/51965661
linked to: http://stackoverflow.com/q/2023046
tagged with: pyopenssl
type: Question
tagged with: openssl
downvote count: 0
favorite count: 0
has title: Is there any way to use python OpenSSL module to convert certificate from pkcs7 format to pem format
tagged with: python
has body: Is there any way to use python OpenSSL module to convert a certificate from pkcs7 format to pem format? I saw this link: Is there any OpenSSL function to convert PKCS7 file to PEM with a C++ answer, but is there any way in python? I have a pkcs7 format certificate needed to be converted to pem format in python code. I searched on the Internet. It seems the most common way to do this is by using OpenSSL command line like below: OpenSSL pkcs7 -in intermediate.cert.p7b -text -out test.pem -print_certs I read the python OpenSSL module; it only provides some methods for checking pkcs7 format, but not something like get_certificate. I not quite familiar with the algorithm of converting pkcs7 to pem, is there any reference for this? Before I use the python os.system module to call the Linux OpenSSL command directly (I do not quite want to do it in this way). I am trying to look for some help from StackOverflow; please help, thanks in advance.
score: 2
answer count: 0
upvote count: 2
type: UnansweredQuestion

http://stackoverflow.com/comment/91106067
has text: Thanks for guiding me! Actually the html is very large, I'm not sure how to upload that
type: QuestionComment
type: Comment
score: 1
comment on: http://stackoverflow.com/q/52077888

http://stackoverflow.com/q/51980787
tagged with: pyqt5
type: Question
has body: I found a way to integrate a mayavi plot into a pyqt5 gui. import os os.environ['ETS_TOOLKIT'] = 'qt5' from traits.api import HasTraits, Instance, on_trait_change from traitsui.api import View, Item from mayavi.core.ui.api import MayaviScene, MlabSceneModel, \ SceneEditor ################################################################################ #The actual visualization class Visualization(HasTraits): scene = Instance(MlabSceneModel, ()) @on_trait_change('scene.activated') def update_plot(self): # This function is called when the view is opened. We don't # populate the scene when the view is not yet open, as some # VTK features require a GLContext. # We can do normal mlab calls on the embedded scene. self.scene.mlab.test_points3d() # the layout of the dialog screated view = View(Item('scene', editor=SceneEditor(scene_class=MayaviScene), height=250, width=300, show_label=False), resizable=True # We need this to resize with the parent widget ) QWidget containing the visualization, this is pure PyQt4 code. class MayaviQWidget(QtGui.QWidget): def __init__(self, parent=None): QtGui.QWidget.__init__(self, parent) layout = QtGui.QVBoxLayout(self) layout.setContentsMargins(0,0,0,0) layout.setSpacing(0) self.visualization = Visualization() # If you want to debug, beware that you need to remove the Qt # input hook. #QtCore.pyqtRemoveInputHook() #import pdb ; pdb.set_trace() #QtCore.pyqtRestoreInputHook() # The edit_traits call will generate the widget to embed. self.ui = self.visualization.edit_traits(parent=self, kind='subpanel').control layout.addWidget(self.ui) self.ui.setParent(self) if __name__ == "__main__": # Don't create a new QApplication, it would unhook the Events # set by Traits on the existing QApplication. Simply use the # '.instance()' method to retrieve the existing one. app = QtGui.QApplication.instance() container = QtGui.QWidget() container.setWindowTitle("Embedding Mayavi in a PyQt4 Application") # define a "complex" layout to test the behaviour lay…
tagged with: class
score: 0
answer count: 1
tagged with: mayavi
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51993676
tagged with: python
has title: Mayavi integration in PyQt5: Meaning of class

http://stackoverflow.com/a/51977878
has body: You first need to get values from your OrderedDict, then you can use simple list comprehension to get the values. To get the values you can use operator.itemgetter along with itertools.chain. This will give you a flat list of values. &gt;&gt;&gt; from itertools import chain &gt;&gt;&gt; from operator import itemgetter &gt;&gt;&gt; values = list(chain(*map(itemgetter('keyword'), list(d.values())))) &gt;&gt;&gt; values &gt;&gt;&gt; ['yellow', 'blue', 'lock', 'door'] &gt;&gt;&gt; m = ['red', 'blue', 'one'] &gt;&gt;&gt; correct = [s for s in m if s in values] &gt;&gt;&gt; correct &gt;&gt;&gt; ['blue'] &gt;&gt;&gt; incorrect = [a for a in m if a not in values] &gt;&gt;&gt; incorrect &gt;&gt;&gt; ['red', 'one']
upvote count: 1
has comment: http://stackoverflow.com/comment/90905761
answers question: http://stackoverflow.com/q/51977511
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/90905633
type: Answer

http://stackoverflow.com/comment/90992718
type: Comment
comment on: http://stackoverflow.com/q/52021136
type: QuestionComment
score: 0
has text: I mean this one placeholder we use in html form

http://stackoverflow.com/comment/91160894
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52104907
has text: True, the reason for python tag was more if there was anything smart in python that could just do it. But it seems like there is no need for that.
score: 0

http://stackoverflow.com/comment/91032575
type: QuestionComment
type: Comment
score: 0
comment on: http://stackoverflow.com/q/52040612
has text: What commands or scripts have you tried so far and what was the result?

http://stackoverflow.com/a/52097878
upvote count: 0
type: Answer
has body: text = ['Malte', 'ex', 'precio', 'empcionis', 'bovum', 'septem', 'laborancium', 'et', 'unius', 'thaurj', 'et', 'unius', 'vacce', 'cum', 'vitulo', 'sequenti', 'et', 'pecudum', 'fetancium', 'sexdecim', 'et', 'duarum', 'caprarum', 'cum', 'duobus', 'et', 'cum', 'vitulo'] result = [] for index, value in enumerate(text): if value == 'cum': try: if text[index + 1] == 'vitulo': result.append(index) except IndexError: # reached end break output result == [13, 26] A fancy way: from itertools import tee # recipe from itertools def pairwise(iterable): "s -&gt; (s0,s1), (s1,s2), (s2, s3), ..." a, b = tee(iterable) next(b, None) return zip(a, b) [index for (index, (first, second)) in enumerate(pairwise(text)) if first == 'cum' and second == 'vitulo']
score: -1
has comment: http://stackoverflow.com/comment/91148712
downvote count: 1
answers question: http://stackoverflow.com/q/52097767
has comment: http://stackoverflow.com/comment/91146792

http://stackoverflow.com/comment/91263384
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52130125
type: AnswerComment
has text: With my human logic, I just can't wrap my head around why looking for something in a shuffle bag is the fastest way of returning a sequence of items in order. It just does not make sense to me at all and I strongly believe there should be a better way to do it than to look for it in the dict.

http://stackoverflow.com/q/51989301
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/57056500
tagged with: lambda
type: Question
has comment: http://stackoverflow.com/comment/90928420
has comment: http://stackoverflow.com/comment/90928551
has comment: http://stackoverflow.com/comment/90929678
has body: I was trying to extract information from df['matrix'] into four new columns. The df['matrix'] look like this: id matrix 0 {'status': 'ZERO_RESULTS'} 1 {'distance': {'text': '3,899 km', 'value': 3898595}, 'duration': {'text': '1 day 13 hours', 'value': 133445}, 'status': 'OK'} 2 {'distance': {'text': '2,065 km', 'value': 2065157}, 'duration': {'text': '20 hours 7 mins', 'value': 72393}, 'status': 'OK'} my code: df['dist_value'] = df['matrix'].apply(lambda x: round((x['distance']['value']) / 1000) if "status" not in x else None) df['dist_text'] = df['matrix'].apply(lambda x: x['distance']['text'] if "status" not in x else None) df['duration_value'] = df['matrix'].apply(lambda x: float("%.2f" %((x['duration']['value'])/60/60)) if "status" not in x else None) df['duration_text'] = df['matrix'].apply(lambda x: x['duration']['text'] if "status" not in x else None) I get the following error: df['dist_value'] = df['matrix'].apply(lambda x: round((x['distance']['value']) / 1000) if "status" not in x else None) TypeError: argument of type 'float' is not iterable
has comment: http://stackoverflow.com/comment/90929199
answer count: 1
has title: Python lambda: TypeError: argument of type 'float' is not iterable
has comment: http://stackoverflow.com/comment/90945336
has comment: http://stackoverflow.com/comment/90928368
score: 0
has comment: http://stackoverflow.com/comment/90929771
tagged with: pandas
tagged with: python

nltk
tags question: http://stackoverflow.com/q/52037228
tags question: http://stackoverflow.com/q/51978112
tags question: http://stackoverflow.com/q/52014482
tags question: http://stackoverflow.com/q/51959810
tags question: http://stackoverflow.com/q/52030274
tags question: http://stackoverflow.com/q/52054622
tags question: http://stackoverflow.com/q/52099385
tags question: http://stackoverflow.com/q/52033188
tags question: http://stackoverflow.com/q/51982654
tags question: http://stackoverflow.com/q/52087044
tags question: http://stackoverflow.com/q/52107825
tags question: http://stackoverflow.com/q/52047163
tag name: nltk
tags question: http://stackoverflow.com/q/52021855
tags question: http://stackoverflow.com/q/52107352
tags question: http://stackoverflow.com/q/51958973
tags question: http://stackoverflow.com/q/51973450
tags question: http://stackoverflow.com/q/52053691
tags question: http://stackoverflow.com/q/52103070
tags question: http://stackoverflow.com/q/52029253
tags question: http://stackoverflow.com/q/52008433
tags question: http://stackoverflow.com/q/52001357
tags question: http://stackoverflow.com/q/52013552
tags question: http://stackoverflow.com/q/52022587
tags question: http://stackoverflow.com/q/52039155
type: Tag
tags question: http://stackoverflow.com/q/52055442
tags question: http://stackoverflow.com/q/52072898

http://stackoverflow.com/comment/91053771
type: Comment
score: 3
type: AnswerComment
has text: Well, a group shape contains other shapes, so it's a "container" shape. All other shapes are "leaf" shapes. The terminology comes from hierarchical data structures, in particular _trees_, where each node can either "contain" or point to other nodes, or it can be the end of a "branch" so to speak, hence the term :) https://en.wikipedia.org/wiki/Tree_(graph_theory) The usage here is only partly apt, hence the quotes.
comment on: http://stackoverflow.com/a/52012007

http://stackoverflow.com/q/52091047
tagged with: python
has title: Recalculate a convolution value with the eager execution
has body: I'm trying to use the eager execution. I create a training set, a weight, and a convolution layer. I declare the convolution and change the weights. How can I get the convolution calculated again without having to declare the layer again? I expected it to be something like that: import tensorflow as tf tf.enable_eager_execution() tfe = tf.contrib.eager TrainingDataExample = tf.constant(0.5, shape=[8, 5, 6, 1], name="Inputs") WeightExample = tfe.Variable(tf.truncated_normal([1, 3, 1, 4], seed=1), name="Weights") ConvExample = tf.nn.conv2d(TrainingDataExample, WeightExample, strides=[1, 1, 1, 1], padding="VALID", name="Conv") NewWeightExample = tf.constant(2.0, shape=[1, 3, 1, 4], name="NewWeights") WeightExample = tf.assign(WeightExample, NewWeightExample ) result = ConvExample print (result) But it does not work, the value of the convolution is not updated. How can I do this?
has answer: http://stackoverflow.com/a/52092446
tagged with: tensorflow
type: Question
answer count: 1
downvote count: 0
score: 1
favorite count: 0
type: UnansweredQuestion
upvote count: 1

http://stackoverflow.com/comment/90966821
type: QuestionComment
has text: Yes the b-tag before it is syntactically wrong.
score: 0
comment on: http://stackoverflow.com/q/52007897
type: Comment

global
type: Tag
tag name: global
tags question: http://stackoverflow.com/q/52036353

http://stackoverflow.com/comment/91192471
comment on: http://stackoverflow.com/a/52108182
type: Comment
has text: Thank you very much, your answer helped me a lot @cpander
score: 0
type: AnswerComment

http://stackoverflow.com/q/51989164
score: 0
has comment: http://stackoverflow.com/comment/90928094
answer count: 3
has title: Defining a function with another function
tagged with: python-3.x
has answer: http://stackoverflow.com/a/51989434
tagged with: python
has answer: http://stackoverflow.com/a/51989361
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51989354
accepted answer: http://stackoverflow.com/a/51989361
type: Question
possible better answer: http://stackoverflow.com/a/51989354
has body: Could someone help explain what's going on here? I don't understand what is going on in the third part, and why the result is 9. Thank you! &gt;&gt;&gt; def square(x): return x ** 2 &gt;&gt;&gt; def f(x): return x * x &gt;&gt;&gt; def try_f(f): return f(3) &gt;&gt;&gt; try_f(square) 9

http://stackoverflow.com/a/51986967
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/51986221
type: Answer
accepted answer of: http://stackoverflow.com/q/51986221
has body: You should use a template_dict to pass in the ds template in your PythonOperator. https://github.com/apache/incubator-airflow/blob/master/airflow/operators/python_operator.py#L56 For example, if I wanted to pass execution_date to a PythonOperator: def transform_py(**kwargs): today = kwargs.get('templates_dict').get('today', None) ... with dag: today = "{{ ds_nodash }}" transform = PythonOperator( task_id='test_date', python_callable=transform_py, templates_dict={ 'today': today, }, provide_context=True)
upvote count: 10
has comment: http://stackoverflow.com/comment/90952974
downvote count: 0
score: 10

http://stackoverflow.com/a/51995485
answers question: http://stackoverflow.com/q/51994481
has body: So if I understand correctly, you have two dataframes that each have a column with some overlap between the two. For simplicity, I'm going to call them df_one and df_two and they both have an id column. You can use isin() to filter down to just the overlap, or the converse to filter those out. eg import pandas as pd df_one = pd.DataFrame(data={'id':[1,2,3,4,5]}) df_two = pd.DataFrame(data={'id':[3,4,5,6,7]}) new_ids = ~df_one['id'].isin(df_two['id']) df_only_in_one = df_one[new_ids]
has comment: http://stackoverflow.com/comment/91005592
type: AcceptedAnswer
upvote count: 1
type: Answer
has comment: http://stackoverflow.com/comment/90940857
has comment: http://stackoverflow.com/comment/90967892
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51994481
score: 1

http://stackoverflow.com/q/52067591
type: Question
score: 0
has answer: http://stackoverflow.com/a/52067650
answer count: 1
tagged with: python
tagged with: python-decorators
accepted answer: http://stackoverflow.com/a/52067650
has title: Switch order of decorators based on what test case is running?
has body: In order to test a feature flag, I'm mocking/patching two functions with patch. However, whenever I switch the order of these mock decorators it causes some tests to fail. When I switch them again, those failing tests pass and the previously passing tests fail. To my knowledge, this is due to the order in which decorators are evaluated in Python. Is there a way to declare/specify for one specific test which decorator should be evaluated first? @mock.patch.object(MyMockClass, '_some_function', return_value=False) @mock.patch.object(MyMockClass, '_another_function', return_value=False) class MyClassTestCase(TestCase): # code...
tagged with: django
type: AnsweredQuestion
tagged with: python-unittest

http://stackoverflow.com/a/52048228
downvote count: 0
has comment: http://stackoverflow.com/comment/91047624
upvote count: 2
has comment: http://stackoverflow.com/comment/91047910
has comment: http://stackoverflow.com/comment/91047332
type: Answer
has body: I took a different approach and zipped your columns up, then compared them. Sorry the headers look wonky, I couldn't see the whole thing. I added 2 rows to your csv file to include late deliveries. These orders are: Purchase order number Delivery Date Source Desired Deliv 17 2/10/2018 2/5/2018 18 7/16/2017 7/14/2018 see below: import pandas as pd from datetime import datetime from datetime import timedelta import csv df = pd.read_csv('./Desktop/dummy.csv') late_items = [] date_format = '%m/%d/%Y' for x,y,z in zip(df['Purchase order number'], df['Delivery Date'], df['Source desired delive']): actual_deliv_date = datetime.strptime(y, date_format) supposed_deliv_date = datetime.strptime(z, date_format) diff_deliv_date = supposed_deliv_date - actual_deliv_date if diff_deliv_date &lt; timedelta(0): late_items.append([x, diff_deliv_date]) print(late_items) output: [[17, datetime.timedelta(-5)], [18, datetime.timedelta(-2)]] Or do it this way to just add the 'Diff Delivery Date' column to your original df: diff_delivery_date = [] date_format = '%m/%d/%Y' for x,y,z in zip(df['Purchase order number'], df['Delivery Date'], df['Source desired delive']): actual_deliv_date = datetime.strptime(y, date_format) supposed_deliv_date = datetime.strptime(z, date_format) diff_deliv_date = supposed_deliv_date - actual_deliv_date diff_delivery_date.append(diff_deliv_date) df['Diff Deliv Date'] = diff_delivery_date df.loc[df['Diff Deliv Date'] &lt; timedelta(0)] # To get only those values less than 0 for late deliveries. #df option to output whole df with on time and late deliveries. output: Purchase order number Delivery Date Source desired delive Diff Deliv Date 5 17 2/10/2018 2/5/2018 -5 days 6 18 7/16/2017 7/14/2017 -2 days
has comment: http://stackoverflow.com/comment/91158528
answers question: http://stackoverflow.com/q/52047967
has comment: http://stackoverflow.com/comment/91157719
has comment: http://stackoverflow.com/comment/91157894
has comment: http://stackoverflow.com/comment/91047645
score: 2

http://stackoverflow.com/comment/90950098
has text: use `visudo`: try it before. [Link](https://askubuntu.com/a/168885/772449)
score: 1
comment on: http://stackoverflow.com/q/52000490
type: QuestionComment
type: Comment

http://stackoverflow.com/a/52097372
has body: Use dayfirst=True Ex: import pandas as pd print(pd.to_datetime("01-08-2018 14:02:03", dayfirst=True)) Output: 2018-08-01 14:02:03
upvote count: 1
answers question: http://stackoverflow.com/q/52097306
downvote count: 0
type: Answer
score: 1

http://stackoverflow.com/q/52108345
score: 2
has answer: http://stackoverflow.com/a/52108443
has comment: http://stackoverflow.com/comment/91167486
has body: I am working on a homework assignment, and am a little stuck and could use some help please. I don't want the answer handed to me, but if I could get some help or tips I would greatly appreciate it. I have to create a anagram generator that makes only 1 recursive function call and no for loops. def anagram(st): if len(st) == 0: return [] else: if len(st) &gt; 1: print(st) return [st] + [st[0]] + anagram(st[1:]) else: print("test2",st) return [st[1:] + st[0]] ana = anagram('abc') This is my results: ['abc', 'a', 'bc', 'b', 'c'] 5 The answer should be: ['abc', 'acb', 'bac', 'bca', 'cab', 'cba'] 6
has comment: http://stackoverflow.com/comment/91167549
type: Question
has comment: http://stackoverflow.com/comment/91167518
has title: Python - Recursive anagram function
tagged with: anagram
downvote count: 0
accepted answer: http://stackoverflow.com/a/52108443
answer count: 1
has comment: http://stackoverflow.com/comment/91167402
favorite count: 0
upvote count: 2
has comment: http://stackoverflow.com/comment/91167389
has comment: http://stackoverflow.com/comment/91167400
tagged with: python
has comment: http://stackoverflow.com/comment/91167435
tagged with: recursion
type: AnsweredQuestion

http://stackoverflow.com/q/52014962
tagged with: django-messages
has body: I am trying to use django-directmessages app. It's an application to manage simple direct messages. A part of the Documentation says: Import the Message Management API on top of your views.py from directmessages.apps import Inbox Send message: Inbox.send_message(from_user, to_user, message) List all unread messages: Inbox.get_unread_messages(user) Read a message (and mark as read): Inbox.read_message(message) Print a message as : : Inbox.read_message_formatted(message) Print a list of all conversation partners for a user: Inbox.get_conversations(users) Get a conversation between two users: Inbox.get_conversation(user1, user2, _limit_, _reversed_, _mark_read_) How can i implement this application in my views.py file ?
score: 0
answer count: 1
has answer: http://stackoverflow.com/a/52084897
tagged with: django
tagged with: python
type: AnsweredQuestion
tagged with: django-views
has title: Implementation of django-directmessages application
accepted answer: http://stackoverflow.com/a/52084897
type: Question
tagged with: django-apps

http://stackoverflow.com/q/51966486
score: 1
has body: Trying out TensorFlow Lite with a pretrained Keras image classifier, I'm getting worse predictions after converting the H5 to the tflite format. Is this intended behaviour (e.g. weight quantization), a bug or am I forgetting something when using the interpreter? Example from imagesoup import ImageSoup from tensorflow.keras.applications.resnet50 import ResNet50, preprocess_input, decode_predictions from tensorflow.keras.preprocessing.image import load_img, img_to_array # Load an example image. ImageSoup().search('terrier', n_images=1)[0].to_file('image.jpg') i = load_img('image.jpg', target_size=(224, 224)) x = img_to_array(i) x = x[None, ...] x = preprocess_input(x) # Classify image with Keras. model = ResNet50() y = model.predict(x) print("Keras:", decode_predictions(y)) # Convert Keras model to TensorFlow Lite. model.save(f'{model.name}.h5') converter = tf.contrib.lite.TocoConverter.from_keras_model_file tflite_model = converter(f'{model.name}.h5').convert() with open(f'{model.name}.tflite', 'wb') as f: f.write(tflite_model) # Classify image with TensorFlow Lite. f = tf.contrib.lite.Interpreter(f'{model.name}.tflite') f.allocate_tensors() i = f.get_input_details()[0] o = f.get_output_details()[0] f.set_tensor(i['index'], x) f.invoke() y = f.get_tensor(o['index']) print("TensorFlow Lite:", decode_predictions(y)) Keras: ('n02098105', 'soft-coated_wheaten_terrier', 0.70274395), ('n02091635', 'otterhound', 0.0885325), ('n02090721', 'Irish_wolfhound', 0.06422518), ('n02093991', 'Irish_terrier', 0.040120784), ('n02111500', 'Great_Pyrenees', 0.03408164) TensorFlow Lite: ('n07753275', 'pineapple', 0.94529104), ('n03379051', 'football_helmet', 0.033994876), ('n03891332', 'parking_meter', 0.011431991), ('n04522168', 'vase', 0.0029440755), ('n02094114', 'Norfolk_terrier', 0.0022089847)
tagged with: tensorflow
type: Question
has comment: http://stackoverflow.com/comment/90941548
tagged with: tensorflow-lite
has comment: http://stackoverflow.com/comment/91509041
has title: Different predictions when running Keras model in TensorFlow Lite
answer count: 2
upvote count: 1
tagged with: keras
has answer: http://stackoverflow.com/a/52280550
has comment: http://stackoverflow.com/comment/90987150
favorite count: 0
accepted answer: http://stackoverflow.com/a/52280550
has comment: http://stackoverflow.com/comment/90987130
tagged with: python
possible better answer: http://stackoverflow.com/a/51967220
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51967220
downvote count: 0

http://stackoverflow.com/comment/90871540
type: Comment
type: QuestionComment
has text: i have pip it ,but pip are located in my dir, not in /user/local,because i don't have root
score: 0
comment on: http://stackoverflow.com/q/51959670

http://stackoverflow.com/comment/131748030
has text: In this specific case `list` as type hint would be sufficient. No need to import.
score: 3
comment on: http://stackoverflow.com/a/52064202
type: AnswerComment
type: Comment

http://stackoverflow.com/a/52037526
downvote count: 0
answers question: http://stackoverflow.com/q/52037437
has body: To find a key in a dict, you first find candidates by hash, then you see whether it is a fluke (the objects are different even though the hash is the same) or really the key you want. So if you can't find anything under that hash, there's nothing to eq with. Imagine you're looking for an acquaintance at a party, and don't know if she's here yet. She has red hair. Typically, you'd look for red-haired girls, then go face them to see whether it's really her or not. It makes no sense to check each and every person at the party if no red-haired girls arrived yet. (Assuming your friend is not into daily dye-jobs.) EDIT: CPython stores dicts in an array, where the primary array position is determined by the hash; if that position is occupied, it skips to a next candidate location in a mathematically deterministic way. Since a filled location can consequently hold either the "correct" hash or an unrelated hash, when looking up a hash CPython will start from the primary location, then go on comparing hashes till it decides it's impossible the searched-for key is there. The hashes are at this point plain low-level integers, not Python objects, which explains why hash comparisons don't trigger __eq__. Note a cute optimisation in the source: for each candidate, CPython first checks object identity; only then does it check whether hashes are still same, and if so, goes to the slow check to see whether objects are equal (using PyObject_RichCompareBool, which ultimately calls __eq__). Why does this matter? Look here: class Foo: def __eq__(self, other): return False # This shouldn't match... def __hash__(self): return 7 f = Foo() d = { f: "Yes!" } print(d[f]) # ...and yet it does! :) # =&gt; "Yes!"
score: 4
accepted answer of: http://stackoverflow.com/q/52037437
has comment: http://stackoverflow.com/comment/91025388
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/91025724
type: Answer
has comment: http://stackoverflow.com/comment/91025847
has comment: http://stackoverflow.com/comment/91025366
upvote count: 4

http://stackoverflow.com/a/52106833
score: 7
upvote count: 7
has body: If you don't want the subplot to eat into the third axes, already create an extra axes for it when you make the subplots. To make the plots square, you need to set the aspect ratio: axes.set_aspect(10). import numpy as np import matplotlib.pyplot as plt x = np.linspace(1, 100, 100) y = np.linspace(0.1, 10, 100) z = x[:, np.newaxis] + y[np.newaxis, :] gridspec = {'width_ratios': [1, 1, 1, 0.1]} fig, ax = plt.subplots(1, 4, figsize=(12, 4), gridspec_kw=gridspec) ax[0].contourf(x, y, z) ax[0].set_xlabel('x') ax[0].set_ylabel('y') ax[1].contourf(x, y, z) ax[1].set_xlabel('x') ax[1].set_ylabel('y') plt.sca(ax[2]) plt.contourf(x, y, z) ax[2].set_xlabel('x') ax[2].set_ylabel('y') for axes in ax[:3]: axes.set_aspect(10) cax = ax[3] plt.colorbar(cax=cax) plt.tight_layout() plt.show() Making the other plots square makes them less tall than the colorbar. The quick and dirty way to avoid this is to use a smaller plot height, e.g. figsize=(12, 3).
answers question: http://stackoverflow.com/q/52106591
type: Answer
downvote count: 0

http://stackoverflow.com/a/52006437
has comment: http://stackoverflow.com/comment/90966423
accepted answer of: http://stackoverflow.com/q/52006325
answers question: http://stackoverflow.com/q/52006325
type: Answer
upvote count: 4
downvote count: 0
has comment: http://stackoverflow.com/comment/90962801
score: 4
has body: Create the x, y indices with numpy.ogrid, and then use advanced indexing: idx, idy = np.ogrid[:c.shape[0], :c.shape[1]] c[idx, idy, ix] #array([[10, 5, 10], # [ 5, 5, 10], # [ 5, 5, 10], # [10, 10, 5]])
type: AcceptedAnswer

http://stackoverflow.com/comment/91164239
has text: I am using python 3.5
comment on: http://stackoverflow.com/q/52031708
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/a/52103928
answers question: http://stackoverflow.com/q/52100514
score: 0
has comment: http://stackoverflow.com/comment/91199504
has body: It really depends on what you're trying to visualize about the data. My first thought would be to make a density plot of the data (by first binning the data into a larger grid yourself and then plotting that grid with color that indicates how much stuff is in each bin).
type: Answer
has comment: http://stackoverflow.com/comment/91211872

http://stackoverflow.com/q/52112402
type: UnansweredQuestion
has title: PYQT How get data from MainUiWindows to QThread?
has comment: http://stackoverflow.com/comment/91819294
has answer: http://stackoverflow.com/a/52116210
tagged with: pyqt
type: Question
has body: I want know how I can send information from the MainUiWindows, like from a QlineEdit, and send it to a QThread. I need it in RealTime, I want change that information everytime that I want and it change variable in that QThread. What I have at moment is: class ThreadClassControl(QtCore.QThread): def __init__(self): QThread.__init__(self) self.ui=MainUiClass() def run(self): print self.ui.QlineEdit.text() But with that I only get the information when this Thread is started and as I said I want change that variable between her iterations. Thanks for Advance
tagged with: python
answer count: 1
tagged with: qthread
score: 0

http://stackoverflow.com/comment/90980160
type: AnswerComment
type: Comment
has text: @newbie But yours traverses the list twice, which isn't efficient either.
comment on: http://stackoverflow.com/a/52014577
score: 0

http://stackoverflow.com/a/52091030
has comment: http://stackoverflow.com/comment/91134063
type: Answer
accepted answer of: http://stackoverflow.com/q/52091011
has body: For avoid chained assignments assign back and remove inplace=True: mask = df['col1'] == 'yes' df.loc[mask, 'col2'] = df.loc[mask, 'col2'].replace({r'(fo)o(?!bar)' :r'\1'}, regex=True) print (df) col1 col2 1 yes foobar 2 yes fo 3 no foobar
has comment: http://stackoverflow.com/comment/91131892
has comment: http://stackoverflow.com/comment/91135495
has comment: http://stackoverflow.com/comment/91132983
has comment: http://stackoverflow.com/comment/91134033
upvote count: 4
has comment: http://stackoverflow.com/comment/91133553
answers question: http://stackoverflow.com/q/52091011
type: AcceptedAnswer
downvote count: 0
score: 4

http://stackoverflow.com/comment/124722075
type: Comment
score: 2
has text: I had to `pipwin refresh` before installing pyaudio, otherwise getting HTTP 404
type: AnswerComment
comment on: http://stackoverflow.com/a/59594881

pyinstaller
tags question: http://stackoverflow.com/q/52077246
type: Tag
tags question: http://stackoverflow.com/q/51960505
tag name: pyinstaller
tags question: http://stackoverflow.com/q/52063311
tags question: http://stackoverflow.com/q/51977659
tags question: http://stackoverflow.com/q/51981570
tags question: http://stackoverflow.com/q/52098208
tags question: http://stackoverflow.com/q/52009769
tags question: http://stackoverflow.com/q/52094675

http://stackoverflow.com/comment/90919449
score: 1
comment on: http://stackoverflow.com/q/51984719
type: Comment
type: QuestionComment
has text: You DONT HAVE TO INVOKE THEM IN YOUR TESTS. They get invoked automqtically maybe thats what got you Wondering. If you Want a specific one for your specific test you write it with your custom name and INVOKE them in the test

http://stackoverflow.com/a/51968181
type: Answer
score: 1
has body: the re lib is actually mostly a C extension package with a python wrapper over it. _sre is the C extention module and _sre.SRE_Match is the (C-coded) Match class. You'll find it in sys.modules: &gt;&gt;&gt; import sys &gt;&gt;&gt; import re &gt;&gt;&gt; sys.modules["_sre"] &lt;&lt;module '_sre' (built-in)&gt;
accepted answer of: http://stackoverflow.com/q/51966626
upvote count: 1
answers question: http://stackoverflow.com/q/51966626
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/51957872
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51957982
has answer: http://stackoverflow.com/a/51958030
type: Question
tagged with: filtering
downvote count: 0
has answer: http://stackoverflow.com/a/51958198
upvote count: 4
tagged with: pandas
has answer: http://stackoverflow.com/a/51957982
has answer: http://stackoverflow.com/a/51958017
has answer: http://stackoverflow.com/a/51957969
favorite count: 0
has title: Pandas Integer Filtering
possible better answer: http://stackoverflow.com/a/51958017
answer count: 5
tagged with: python
has body: I have made a dataframe using a function I created data = generate_xml() I then make a subset of the dataframe based on the column names which in this case are called WalmartIDS and ASINS. Below is also an example of what the dataframe looks like walmartIDS = data.loc[:,['WalmartIDS','ASINS']] &gt;&gt; WalmartIDS ASINS 602 20511489 B077BS6737 603 10311487 B077BMHVG7 604 10311302 B077BRTYCS 605 152381151 B077YW9PTQ 606 The-Holiday-Aisle-Projection-Kaleidoscope-Spider-Airblown-Inflatable- Halloween-Decoration-THDA5581.html B076CNN6K5 607 51409868 B0756DMVSC 608 51410962 B0756FKLCV 609 51411020 B0756F3F6J 610 51411529 B0756FDM74 611 915505165 B076W25SDZ 612 400796633 B076VM75ZF As you can see sometimes bad data will get into the WalmartIDS column. So I want to filter this out by deleting all of the rows in the newly created walmartIDS dataframe where the WalmartIDS column contains characters other than integers. I don't want to alter the data version of the data frame because it is the raw data. walmartIDS[walmartIDS.WalmartIDS != '^[-+]?[0-9]+$'] However, the above solution doesn't seem to do anything, and I can in fact still see the bad data, (in the example this is row 606) where it should have been deleted. What is the proper way to do this?
score: 4

http://stackoverflow.com/comment/91123441
type: Comment
comment on: http://stackoverflow.com/q/52086283
type: QuestionComment
has text: Fixing such .csv looks like a simple task. You can just replace \' ' with nothing. Or if don't know the number of space, you may use regexp '\ +'. I would preprocess a file using sed or just do the replacement in a gui text editor that supports regexp, instead of using python.
score: 0

http://stackoverflow.com/comment/91005346
has text: text is format for response. I can see [{'url': 'http://example.com/imageurl.jpg}] but I want only http://example.com/imageurl.jpg. This data in images tag. I use this code but not work. Code: for images in images["url"]: link = str(images["url"]) print(link)
comment on: http://stackoverflow.com/q/52027498
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52079999
tagged with: http://stackoverflow.com/tag/csv
tagged with: datetime
tagged with: python
linked to: http://stackoverflow.com/q/441147
tagged with: python-3.x
has answer: http://stackoverflow.com/a/52080608
upvote count: 2
type: Question
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/52080613
has answer: http://stackoverflow.com/a/52080613
linked to: http://stackoverflow.com/q/703907
accepted answer: http://stackoverflow.com/a/52080608
answer count: 2
score: 2
downvote count: 0
has body: I am newbie to Python. I have a CSV file with below data as an example. I wanted to skip rows between specific date range(2018-08-01 to 2018-08-28) and redirect output to a separate CSV file. Please note, a blank space in the header "LAST USE". NUMBER,MAIL,COMMENT,COUNT,LAST USE,PERCENTAGE,TEXTN 343,user1@example.com,"My comment","21577",2018-08-06,80.436%, 222,user2@example.com,"My comment","31181",2018-07-20,11.858%, 103,user3@example.com,"My comment",540,2018-06-14,2.013%, 341,user4@example.com,"My comment",0,N/A,0.000%, Any idea would be greatly appreciated.
has title: How to filter rows between two dates from CSV file using python and redirect to another file?
favorite count: 0
tagged with: pandas

http://stackoverflow.com/comment/90901466
type: AnswerComment
comment on: http://stackoverflow.com/a/51973665
type: Comment
score: 1
has text: When did we start downvoting correct answers with no comment?

http://stackoverflow.com/comment/91132173
has text: Thanks it's a nice (and short) solution, but it's adding .0 to my value. I try to force it to "object type" but still there. Thanks
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52090862

http://stackoverflow.com/comment/91155123
has text: Oh alright! I will try and see if I can make it to work! Appreciate it alot :)
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/52102064
type: Comment

http://stackoverflow.com/q/51974380
answer count: 4
score: 14
has title: Print Hex With Spaces Between
type: AnsweredQuestion
upvote count: 14
has answer: http://stackoverflow.com/a/51974501
linked to: http://stackoverflow.com/q/9475241
linked to: http://stackoverflow.com/q/434287
type: Question
has answer: http://stackoverflow.com/a/51974584
has answer: http://stackoverflow.com/a/51974447
has comment: http://stackoverflow.com/comment/90899351
has comment: http://stackoverflow.com/comment/90899260
downvote count: 0
has comment: http://stackoverflow.com/comment/90899382
accepted answer: http://stackoverflow.com/a/51974447
has comment: http://stackoverflow.com/comment/90899323
has answer: http://stackoverflow.com/a/62528037
favorite count: 0
tagged with: hex
tagged with: python-3.x
linked to: http://stackoverflow.com/q/34822676
has body: I'm trying to print my hex out in another way... First I'm converting this (bytestring is the name of the variable): b'\xff\x00\xff\xff\xff' to hex, print(bytestring.hex()) which outputs: ff00ffffff but I've been trying for a while to get it to output this: ff 00 ff ff ff but no luck. Any suggestions? Cheers! Update: stringdata = f.read(5) print(stringdata) #b'\xff\x00\xff\xff\xff' readHex = " ".join(["{:02x}".format(x) for x in stringdata.hex()]) # ValueError: Unknown format code 'x' for object of type 'str'
possible better answer: http://stackoverflow.com/a/62528037
tagged with: python

http://stackoverflow.com/comment/90966369
has text: Interesting, it works but I am curious as to why we did not have to escape the forward slash, "/" ?
comment on: http://stackoverflow.com/a/52007623
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/a/51989990
answers question: http://stackoverflow.com/q/51959810
has comment: http://stackoverflow.com/comment/90930187
score: 0
type: Answer
has body: Spacy is good, but not perfect. It looks like the best strategy is to split up the text, perhaps using something like this: text = 'meet me 9 Oct. - 8 am' sections = text.split(' - ') for section in sections: doc = nlp(section) for ent in doc.ents: print(ent, ent.label_) Of course, this code doesn't work if there's more than one hyphen in the text, but you get the idea.

http://stackoverflow.com/a/52096407
has comment: http://stackoverflow.com/comment/91164605
accepted answer of: http://stackoverflow.com/q/52096140
score: 0
has body: Sample weights are a multiplier factor, here is the code: https://github.com/scikit-learn/scikit-learn/blob/f0ab589f/sklearn/ensemble/gradient_boosting.py#L1225
type: AcceptedAnswer
type: Answer
answers question: http://stackoverflow.com/q/52096140

http://stackoverflow.com/comment/90981223
type: QuestionComment
has text: okay, now this error message is much clearer; and this seems to be an ongoing issue for [windows users](https://github.com/matterport/Mask_RCNN/issues/13#issuecomment-348775427). The suggested fix is to change `use_multiprocessing` from True to False.
comment on: http://stackoverflow.com/q/52014004
score: 0
type: Comment

http://stackoverflow.com/comment/91005691
comment on: http://stackoverflow.com/q/52027687
has text: @AnthonySottile Or `print = lambda x: hash(x)`
type: QuestionComment
type: Comment
score: 1

http://stackoverflow.com/q/52024472
has comment: http://stackoverflow.com/comment/91186632
has comment: http://stackoverflow.com/comment/91081135
tagged with: gatt
upvote count: 1
tagged with: floating-point
tagged with: raspberry-pi
answer count: 0
type: UnansweredQuestion
has title: How to convert or transcode BLE of IEEE 11073-10404 (Pulse Oximeter) to get SPO2
linked to: http://stackoverflow.com/q/11564270
has comment: http://stackoverflow.com/comment/91127859
downvote count: 0
score: 1
favorite count: 0
tagged with: bluetooth-lowenergy
has body: I'm working on creating a PHG(personal health gateway) using PRi that written with Python to detect PHD(personal home device) such as Pulse Oximeter, Blood pleasure etc. For Pulse Oximeter I've read about IEEE standard IEEE 11073-10404 and GATT definition. I've found a data contained into characteristics at 2A5F and dig into service number at 1822 then I've got data 1fc0f34f 00c0f34f 00c0f350 00000100 0100a2e4 Definition document https://www.bluetooth.com/specifications/gatt/viewer?attributeXmlFile=org.bluetooth.characteristic.plx_continuous_measurement.xml inside the link it define where the data containing on a stream I've searched in stack-overflow a bit, I found some question about SFLOAT but I don't understand why there are don't have build-in function to convert it. I'm not sure if python has method to convert SFLOAT or instead, I must implement it Another question, the data I've got it can be use for transcode into SPO2 value? or I must mapping into x72 (Bluetooth classic attribute) then transcode into SPO2 value
type: Question
tagged with: python

http://stackoverflow.com/q/51989867
type: AnsweredQuestion
has body: I want to use condition GANs with the purpose of generated images for one domain (noted as domain A) and by having input images from a second domain (noted as domain B) and the class information as well. Both domains are linked with the same label information (every image of domain A is linked to an image to domain B and a specific label). My generator so far in Keras is the following: def generator_model_v2(): global BATCH_SIZE inputs = Input((IN_CH, img_cols, img_rows)) e1 = BatchNormalization(mode=0)(inputs) e2 = Flatten()(e1) e3 = BatchNormalization(mode=0)(e2) e4 = Dense(1024, activation="relu")(e3) e5 = BatchNormalization(mode=0)(e4) e6 = Dense(512, activation="relu")(e5) e7 = BatchNormalization(mode=0)(e6) e8 = Dense(512, activation="relu")(e7) e9 = BatchNormalization(mode=0)(e8) e10 = Dense(IN_CH * img_cols *img_rows, activation="relu")(e9) e11 = Reshape((3, 28, 28))(e10) e12 = BatchNormalization(mode=0)(e11) e13 = Activation('tanh')(e12) model = Model(input=inputs, output=e13) return model So far my generator takes as input the images from the domain A (and the scope to output images from the domain B). I want somehow to input also the information of the class for the input domain A with the scope to produce images of the same class for the domain B. How can I add the label information after the flattening. So instead of having input size 1x1024 to have 1x1025 for example. Can I use a second Input for the class information in the Generator. And if yes how can I call then the generator from the training procedure of the GANs? The training procedure: discriminator_and_classifier_on_generator = generator_containing_discriminator_and_classifier( generator, discriminator, classifier) generator.compile(loss=generator_l1_loss, optimizer=g_optim) discriminator_and_classifier_on_generator.compile( loss=[generator_l1_loss, discriminator_on_generator_loss, "categorical_crossentropy"], optimizer="rmsprop") discriminator.compile(loss=discriminator_loss, optimizer=d_opti…
score: 7
upvote count: 7
type: Question
downvote count: 0
accepted answer: http://stackoverflow.com/a/52036334
has title: Add class information to Generator model in keras
answer count: 1
tagged with: keras
favorite count: 0
tagged with: machine-learning
tagged with: python
tagged with: artificial-intelligence
tagged with: generative-adversarial-network
has answer: http://stackoverflow.com/a/52036334

http://stackoverflow.com/q/52043180
has body: X=[1,2,1,0,1] def f(x): return {1:'car',2:'bike',0:'bus'}.get(x,'default') for i in X: print(i) f(i) output: 1 2 1 0 1 The problem with the above code is, its not executing the function f(x)
has comment: http://stackoverflow.com/comment/91037337
upvote count: 0
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/91037230
accepted answer: http://stackoverflow.com/a/52043255
tagged with: python-3.x
has title: Having trouble with using functions in for loop
has comment: http://stackoverflow.com/comment/91037799
tagged with: python
has comment: http://stackoverflow.com/comment/91037393
has answer: http://stackoverflow.com/a/52043255
type: AnsweredQuestion
downvote count: 1
tagged with: definition
type: Question
tagged with: for-loop
tagged with: arrays
score: -1
has comment: http://stackoverflow.com/comment/91037227

http://stackoverflow.com/q/52063286
score: 2
downvote count: 0
tagged with: keras
favorite count: 0
tagged with: tensorflow-datasets
type: UnansweredQuestion
tagged with: python
has title: How to train and evaluate Keras Sequential Neural Network through tf.Dataset Pipeline
answer count: 0
upvote count: 2
has body: I am trying to put together a keras Sequential model and train/evaluate it on a large dataset by using the Dataset api. I'm seeing bits and pieces of how to do this, but nowhere that fits it all together. My data source is a large csv file. I see samples of how to parse out the csv file through the TextLineDataset's iterator (plus a decode_csv utility function), but I don't see how to fit this into the basic Keras model creation...training pattern, like: #create model model = models.Sequential() #add layers model.add(layers.Dense(..., activation='relu')) model.add(layers.Dense(...,acticvation='relu')) ... model.add(layers.Dense(...,activation='tanh') #compile model model.compile(optimizer='adam',...) #train model.fit(???) #evaluate model.evaluate(???) Is this pattern possible with the tf.data.Dataset way of doing things, and if not, what is the preferred pattern? How do I train a keras Sequential with data fed through the Dataset API pipeline's iterators?
tagged with: machine-learning
has comment: http://stackoverflow.com/comment/92150368
tagged with: tensorflow
type: Question

http://stackoverflow.com/q/51996000
has comment: http://stackoverflow.com/comment/90941717
has comment: http://stackoverflow.com/comment/90941579
tagged with: python-object
tagged with: python-3.x
has body: I have the following class: import pandas as pd class CashFlowSchedule: flows = {} annual_growth_rate = None df = None daterange = None months = None amount = None growth = None growth_month = None name = None def copy(self): return CashFlowSchedule(daterange=self.daterange, months=self.months, amount=self.amount, growth=self.growth, growth_month=self.growth_month) def render_named_df(self): temp = self.df.copy() temp.columns = [self.name] return temp def re_init_df(self): self.df = pd.DataFrame([self.flows]).T def __init__(self, daterange=pd.date_range('19900101', '20010101'), months=range(1, 13), amount=0, growth=0, growth_month=1, name=None, years=None): self.daterange = daterange self.months = months self.amount = amount self.growth = growth self.growth_month = growth_month self.name = name self.annual_growth_rate = growth if years is None: years = list({x.year: 0 for x in daterange}.keys()) for dt in daterange: if dt.month == growth_month: amount *= (1. + self.annual_growth_rate) if dt.month in months and dt.year in years: self.flows[dt] = amount else: self.flows[dt] = 0. self.df = pd.DataFrame([self.flows]).T and another class in another module: class SinglePropertyValuation: # descriptive desc_zipcode = None desc_property_type = None desc_units = None desc_beds = None desc_smooth_annual_expenses = None # dates date_purchase = None date_sale = None date_distance_months = None date_daterange_ownership = None # revenue rev_rent = None # recurring expenses exp_taxes = None exp_insurance = None exp_maintenance = None exp_management = None exp_hoa = None cash_flows = {} monthly_raw_rents = [] desc_nearby_zips = None def establish_rent_cashflows(self, monthly_per_unit_rent, growth_rate=None, growth_month=None, default_growth_rate=.02): self.rev_rent =copy.copy(cfs.CashFlowSchedule(daterange=copy.copy(self.date_daterange_ownership), amount=monthly_per_unit_rent * self.desc_units, growth=growth_rate, growth_month=growth_month, name='rev_rent')) def establish_tax_cashf…
tagged with: python
has comment: http://stackoverflow.com/comment/90941696
has comment: http://stackoverflow.com/comment/90941808
has comment: http://stackoverflow.com/comment/90941776
has comment: http://stackoverflow.com/comment/90941801
answer count: 0
type: UnansweredQuestion
score: 0
linked to: http://stackoverflow.com/q/1680528
has comment: http://stackoverflow.com/comment/90941683
has title: python class variables linked despite calling copy
type: Question
tagged with: oop
has comment: http://stackoverflow.com/comment/90941664
has comment: http://stackoverflow.com/comment/90941457

http://stackoverflow.com/a/52057662
type: AcceptedAnswer
type: Answer
has comment: http://stackoverflow.com/comment/91093555
upvote count: 4
downvote count: 0
has comment: http://stackoverflow.com/comment/91079253
has body: The cross entropy function is indeed not bounded upwards. However it will only take on large values if the predictions are very wrong. Let's first look at the behavior of a randomly initialized network. With random weights, the many units/layers will usually compound to result in the network outputing approximately uniform predictions. That is, in a classification problem with n classes you will get probabilities of around 1/n for each class (0.5 in the two-class case). In this case, the cross entropy will be around the entropy of an n-class uniform distribution, which is log(n), under certain assumptions (see below). This can be seen as follows: The cross entropy for a single data point is -sum(p(k)*log(q(k))) where p are the true probabilities (labels), q are the predictions, k are the different classes and the sum is over the classes. Now, with hard labels (i.e. one-hot encoded) only a single p(k) is 1, all others are 0. Thus, the term reduces to -log(q(k)) where k is now the correct class. If with a randomly initialized network q(k) ~ 1/n, we get -log(1/n) = log(n). We can also go of the definition of the cross entropy which is generally entropy(p) + kullback-leibler divergence(p,q). If p and q are the same distributions (e.g. p is uniform when we have the same number of examples for each class, and q is around uniform for random networks) then the KL divergence becomes 0 and we are left with entropy(p). Now, since the training objective is usually to reduce cross entropy, we can think of log(n) as a kind of worst-case value. If it ever gets higher, there is probably something wrong with your model. Since it looks like you only have two classes (0 and 1), log(2) &lt; 1 and so your cross entropy will generally be quite small.
accepted answer of: http://stackoverflow.com/q/52048171
score: 4
answers question: http://stackoverflow.com/q/52048171

http://stackoverflow.com/comment/90923806
comment on: http://stackoverflow.com/q/51987139
type: Comment
type: QuestionComment
has text: It sounds like you want combinations, not permutations. Combinations don't count element order, permutations do.
score: 5

http://stackoverflow.com/q/52058007
has comment: http://stackoverflow.com/comment/91066346
answer count: 1
downvote count: 0
has title: How insert a list as a column in MySQL with Python?
accepted answer: http://stackoverflow.com/a/52058177
tagged with: python-2.7
tagged with: sql
tagged with: python
has comment: http://stackoverflow.com/comment/91066429
favorite count: 0
upvote count: 2
has comment: http://stackoverflow.com/comment/91066447
has comment: http://stackoverflow.com/comment/91066213
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52058177
score: 2
tagged with: list
has comment: http://stackoverflow.com/comment/91068905
has body: So basically I have this list : L1 = ['hel-lo', 'world123', 'bye', 'python'] I want to insert this list in my MySQL table, as follow : +-------------------------+ | words | +-------------------------+ | hel-lo | | world123 | | bye | | python | +-------------------------+ In reality, my list is composed of about 1000 elements. I tried many things which I found on StackOverflow, but nothing is working. (It seems that the elements are trying to be insert with this format "['string']"). Last solution I tried : values = [list([item]) for item in L1] cursor.executemany(u"INSERT INTO `table`(`data`) VALUES %s", values) Which returns this error : mysql.connector.errors.ProgrammingError: 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''hel-lo')' at line 1 Any advices are welcomed !
tagged with: mysql
has comment: http://stackoverflow.com/comment/91066369
type: Question

http://stackoverflow.com/a/52104414
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/52104002
type: Answer
has comment: http://stackoverflow.com/comment/91166927
has body: If you have only one socket, select is not necessary. Use makefile and read lines: handle = reader.makefile() for line in handle: filename = "FILE.0000.{:%Y.%m.%d.%H.%M}.txt".format(datetime.datetime.now()) with open(os.path.join('/tmp', filename), "a") as output: output.write(line)
upvote count: 1
score: 1
accepted answer of: http://stackoverflow.com/q/52104002

http://stackoverflow.com/a/51998372
downvote count: 0
answers question: http://stackoverflow.com/q/51997053
type: Answer
score: 1
upvote count: 1
has body: I'll try to explain your errors and warning. y = np.matrix([[-1,1,4],[2,-2,7],[10,7,1]]) could just as well be y = np.array([[-1,1,4],[2,-2,7],[10,7,1]]) You don't, especially as a beginner, need to use np.matrix. np.array() produces the regular numpy array object. Using np.matrix is discouraged, since it doesn't add anything special now. a = OrdenaMatriz(y) produces a Python list. You start with [], and either insert or append values, so the result is still a list. It's the a == y that produces the DeprecationWarning. It's the result of comparing a list with a numpy array. Then you y=a. Now y is a list, not the original array (or matrix). So on the next loop, OrdenaMatriz is called with a list. That's when y[a,2] &lt; y[a+1,2] raise the TypeError. That indexing is ok for array/matrix, but not for list. So if you stick with this code, or something similar, start with an np.array() call, and make sure that OrdenaMatriz returns an array, not a list.
has comment: http://stackoverflow.com/comment/90946252
has comment: http://stackoverflow.com/comment/90946034

http://stackoverflow.com/q/51971276
accepted answer: http://stackoverflow.com/a/51976678
type: AnsweredQuestion
score: 3
has body: I'm Holding SalesForce Data on Amazon Redshift DB. I would like to create a function on Redshift that will convert SalesForce 15 Char ID to 18 Char ID. I found this topic that gives a direction of how to: salesforce id - How can I convert a 15 char Id value into an 18 char Id value? - Salesforce Stack Exchange But non of this functions is working on Redshift and I cannot use that \ create a similar function on Amazon Redshift DB. (Have to say I'm pretty new @ this. Can someone have a code that works on Redshift?
upvote count: 3
type: Question
answer count: 1
tagged with: salesforce
tagged with: amazon-web-services
downvote count: 0
favorite count: 0
has title: Amazon Redshift: How can I convert a 15 char Salesforce Id value into an 18 char Id value
tagged with: amazon-redshift
tagged with: python
has answer: http://stackoverflow.com/a/51976678

http://stackoverflow.com/q/52067136
type: AnsweredQuestion
upvote count: 0
has comment: http://stackoverflow.com/comment/91084632
has comment: http://stackoverflow.com/comment/91084679
type: Question
has body: I'm sure this must've been asked before, but I couldn't find anything like that, sorry. Let's say I have a list of numbers [1..24]: numbers = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24] I want to make a function that accepts two integers: mynum which is a number in the list and modifier. It will then find mynum in the list and then cycle through the list modifier number of positions (right if positive, left if negative). If it reaches the end of the list, it will loop to the other side. What I want now is to basically shift the number mynum based on the input, within the list. Example: shift_function(2, 1) # returns 3 shift_function(23, 3) # returns 2 shift_function(4, -8) # returns 20 shift_function(15, 51) # returns 18 How can I cycle through the ends of a list like this? I thought of using the time module to get a time with mynum as current hour and then add/subtract modifier hours to it. This will work with my [1..24] range but I'm looking for a more general solution to this what seems to be a simple problem. Edit: To clearify further, I simply want to count through a list of numbers. If the end is reached, start over from the beginning, same backwards. Edit2: I don't know how much more clear I have to be. Imagine you have big numbers on your desk: 3,4,5,6,7. And then you start at the 5 and take modifier steps to the right, let's say 3 steps. So you count: "six, seven, three", starting over from the beginning again. If modifier is negative, you count backwards. E.g. with -4 you count: "four, three, seven, six". I can't see how this is so hard to get. Seems like a very simple and common problem to me.
tagged with: python
score: -2
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/52067210
answer count: 2
downvote count: 2
accepted answer: http://stackoverflow.com/a/52067210
has comment: http://stackoverflow.com/comment/91084669
has title: Count up/down within a specific number range using Python
possible better answer: http://stackoverflow.com/a/52067207
has answer: http://stackoverflow.com/a/52067207
has comment: http://stackoverflow.com/comment/91084914
has comment: http://stackoverflow.com/comment/91084783

http://stackoverflow.com/comment/90937355
has text: Hy Klaus..at the beginning I would like to read the ID of the tag, maybe in the near future even a message wrote inside, but now the ID. Could you help me? Thank you in advance.
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51992826

http://stackoverflow.com/comment/90985120
has text: Just to understand the problem how could you have a looping solution to solve your sample case?
type: Comment
score: 1
comment on: http://stackoverflow.com/q/52017524
type: QuestionComment

http://stackoverflow.com/comment/91037309
score: 1
comment on: http://stackoverflow.com/q/52043230
has text: This isn't legal Python syntax. What are you trying to achieve?
type: Comment
type: QuestionComment

http://stackoverflow.com/a/62549103
downvote count: 0
type: Answer
score: 3
upvote count: 3
has body: To write: with open('game_vars.txt', 'w') as file: file.write(f'{score}\n{time}\n{high_score}\n') To read: with open('game_vars.txt', 'r') as file: score = int(file.readline().strip()) time = int(file.readline().strip()) high_score = int(file.readline().strip())
answers question: http://stackoverflow.com/q/51970463

http://stackoverflow.com/comment/91046180
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52020929
has text: @MichealJRoberts I would like a full page refresh

http://stackoverflow.com/q/51984719
has comment: http://stackoverflow.com/comment/90919582
has answer: http://stackoverflow.com/a/61647454
has comment: http://stackoverflow.com/comment/90919303
has body: In the following example from pytest documentation: The function setup_function is supposed to setup some data for some other function, say test_data. So If i write the function test_data i will have to invoke setup_function like this: def test_data(): setup_function(....) &lt;Test logic here&gt; teardown_function(....) So the only difference is name convention ? I don't understand how exactly is helps me creating setup data. I could have written the same code like this: def test_data(): my_own_setup_function(....) &lt;Test logic here&gt; my_own_teardown_function(....) Since there is no way to tell pytest to automatically link a setup function to the test function it creates the setup data for - the parameter function of the function setup_function doesn't really help me if i don't need a function pointer.... so why bother creating name conventions for no reason? From what i understand, the setup function parameter function only helps me if i need to use a function pointer - something i rarely need.
has title: Pytest setup and teardown functions - same as self written functions?
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90919449
has comment: http://stackoverflow.com/comment/90919154
tagged with: python
score: 10
upvote count: 11
favorite count: 0
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/90923307
has comment: http://stackoverflow.com/comment/90919225
downvote count: 1
has answer: http://stackoverflow.com/a/55474376
has comment: http://stackoverflow.com/comment/90919087
tagged with: pytest

http://stackoverflow.com/comment/90953478
comment on: http://stackoverflow.com/q/52002135
has text: it's rather straightforward, but why not extract the links from the "see more" buttons and open them later? no need to keep track of new tabs.
type: QuestionComment
type: Comment
score: 2

http://stackoverflow.com/q/52069965
has comment: http://stackoverflow.com/comment/91097627
type: Question
tagged with: sqlalchemy
answer count: 1
linked to: http://stackoverflow.com/q/18753465
has comment: http://stackoverflow.com/comment/91096628
has answer: http://stackoverflow.com/a/52093142
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91093496
tagged with: python
has title: SQLAlchemy: Filter by objects in a member list
score: 0
has body: Consider the following classes, class Person: id name jobs class Job: name person person_id (FK) where Person.jobs refers to class Job objects. Now I'd like to perform the following query, # for a given person p Job.query.filter(Job.notin_(p.jobs)) Is it possible in SQLAlchemy? Please not that I do not want to write Job.query.filter(Job.person_id != p.id).
has comment: http://stackoverflow.com/comment/91092761

http://stackoverflow.com/a/52055035
downvote count: 0
has comment: http://stackoverflow.com/comment/91060554
has body: Your should rename your variables - here a short correction of your code, although it is looking good already! I changed the insert to append as well! But it will obviously forget since the list is always initialized with Bob and Jim in it, and then you ask for the name - if is not Bob or Jim, it is new and therefore appended. But then your program ends, so when you start it new, your list is only populated with Bob &amp; Jim again. You could put the whole construct in a "while True" construct to make the same question multiple times until you dont want to anymore! EDIT: included the while (you can enter it numerous times if you just press "Enter" for the question! and put the list in the beginning, so it will not be initialized every time you run a new name! and important: if you see someone for the first time, include the print in the else-clause, otherwise it will be printed everytime, even if you saw the name before! name_list = ['Bob','Jim'] while True: print("Hello, What\'s your name? ") input_name = input("Enter your Name: ") if str(input_name) in name_list: print("Nice to meet you again, " + input_name) else: name_list.append(input_name) print("Hi " + input_name + ", Nice too meet you for the first time.") # Troubleshoot print(name_list) if str(input("Another name? ")) == '': continue else: break
type: Answer
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/91060533
answers question: http://stackoverflow.com/q/52054899

http://stackoverflow.com/comment/91174811
type: QuestionComment
score: 1
has text: perosnally and i knwo that's not what you asked, i use a csv file with name of varaible as name of columns. It's simpler that anything else (but not the best way to do it)
comment on: http://stackoverflow.com/q/52112118
type: Comment

http://stackoverflow.com/q/51958273
tagged with: selenium-webdriver
has body: I'm trying to modify an active URL in python. I'm able to modify the url of a hard-coded url within my existing code but I would like to modify the URL of the page on my apache server For example if I'm on: http://localhost/?foo=stackoverflow I want my script to modify this to http://localhost/?foo=Hello stackoverflow A number of sources I've looked at regarding how to do this all have used hardcoded URLs. For reference here is my code on doing just that, with the modification I'm talking about. #!"C:/PythonPath" import cgi import datetime import time def htmlTop(): print("""Content-type: text/html\n\n My server template """) def htmlTail(): print(""" """) if __name__ == "__main__": try: htmlTop() current_time = str(datetime.datetime.now()) url = 'http://localhost/helloworld/?foo=bar' print(url) print(""" """) url_array = url.split('?') base_url = url_array[0] #'http://localhost/helloworld/?foo=bar' params = url_array[1] # query parameters 'foo' url_array2 = params.split("=") #['foo', 'bar'] # print through all key values param_value_dict = {} # {'foo': 'bar'} for i, str in enumerate(url_array2): if i % 2 == 0: param_value_dict[str] = url_array2[i + 1] former_value = param_value_dict['foo'] # to store old value param_value_dict['foo'] = 'Hello '+former_value+'! '+current_time # form the new url from the dictonary new_url = base_url + '?' for param_name, param_value in param_value_dict.items(): new_url = new_url + param_name + "=" + param_value print(new_url.replace("%20", " ")) htmlTail() except: cgi.print_exception()
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51959357
type: Question
score: 0
answer count: 1
tagged with: python
has title: Modify the current URL string query with python

http://stackoverflow.com/comment/90977736
type: AnswerComment
type: Comment
has text: Yeah, tkinter's trace sends 3 useless arguments when calling the function. Just add `print(args)` to see them if you are curious.
score: 1
comment on: http://stackoverflow.com/a/51997602

http://stackoverflow.com/q/52005509
tagged with: python
has comment: http://stackoverflow.com/comment/90960950
type: Question
tagged with: numpy
has body: I'm trying to install python requirements in jenkins through pip install requirements.cfg For now i have 3 packages in requirements file: numpy, pandas and tslearn. Numpy and pandas are installed correctly and when trying to install tslearn it failes because 'numpy is not installed'. I'm installing in conda virtual environment. Here is a jenkins job output: Collecting numpy==1.14.3 (from -r pip_requirements.cfg (line 1)) Using cached https://files.pythonhosted.org/packages/20/09/6f302aba4a08ffcd34b20a6ee94f34a76207105f59acd83462b81469c06e/numpy-1.14.3-cp35-none-win_amd64.whl Collecting pandas==0.19.2 (from -r pip_requirements.cfg (line 2)) Using cached https://files.pythonhosted.org/packages/d9/c9/0197da1728e813d37b8b38f795aac95ea0c334b75b365078b2b8476dcd11/pandas-0.19.2-cp35-cp35m-win_amd64.whl Collecting tslearn&gt;=0.1.9 (from -r pip_requirements.cfg (line 3)) Cache entry deserialization failed, entry ignored Downloading https://files.pythonhosted.org/packages/5e/9e/4315deb6e42ed0fc8dc5e233c90b6b843199686119d5429b835a4ca25e41/tslearn-0.1.19.2.tar.gz (584kB) Complete output from command python setup.py egg_info: Traceback (most recent call last): File "&lt;string&gt;", line 1, in &lt;module&gt; File "C:\Users\econib.ci\AppData\Local\Temp\pip-build-s3wdsvej\tslearn\setup.py", line 2, in &lt;module&gt; import numpy ImportError: No module named 'numpy' Any ideas why this is happening?
has answer: http://stackoverflow.com/a/56488435
has title: tslearn package not seeing numpy installation python
downvote count: 0
answer count: 1
score: 1
favorite count: 0
tagged with: python-3.x
tagged with: jenkins
type: UnansweredQuestion
tagged with: pip
upvote count: 1

http://stackoverflow.com/q/52096388
answer count: 1
downvote count: 0
has title: get results of numpy sub arrays in seperate sub-arrays on performing an operation, without using for loop
favorite count: 0
tagged with: python-3.x
tagged with: multidimensional-array
type: UnansweredQuestion
upvote count: 1
tagged with: python
has body: The below code checks if each element of sub-arrays is greater than 2 and gives the result in their respective sub-arrays: 2d_array=np.array([[1,2,3,4],[4,56,7,1]]) for elem in 2d_array: print(elem[elem[:]&gt;2]) Output: [3 4] [ 4 56 7] Can we do the same without using a for loop, Preferably using numpy functions.
score: 1
type: Question
tagged with: numpy
tagged with: arrays
has answer: http://stackoverflow.com/a/52096525

http://stackoverflow.com/comment/138530972
type: AnswerComment
type: Comment
has text: @KurtBourbaki, the documentation uses slightly different wording since it’s really about whether the string is interpolated or not. I’ll update the link to a more recent version and clarify. However if log level is properly implemented, it avoids doing unnecessary tasks.
comment on: http://stackoverflow.com/a/52012660
score: 0

http://stackoverflow.com/a/52057110
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52056456
has comment: http://stackoverflow.com/comment/91065328
has comment: http://stackoverflow.com/comment/91064715
has comment: http://stackoverflow.com/comment/91073172
upvote count: 2
has comment: http://stackoverflow.com/comment/91064386
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/91064607
type: Answer
has body: First, avoid totally useless queries - this: Device.objects.get(pk=obj.pk) is as useless as can be since obj already the Device instance you are looking for. Then override your DeviceAdmin.get_queryset method to make proper use of select_related and prefetch_related so you only have the minimal required number of queries.
score: 2
answers question: http://stackoverflow.com/q/52056456

http://stackoverflow.com/a/52099738
upvote count: 4
type: AcceptedAnswer
downvote count: 0
score: 4
type: Answer
has body: You can use itertools.islice to avoid iterating through the whole input list after you've already found the two dicts you need from itertools import islice a, b = islice((d for d in my_list if d.get('a') == 1), 2)
answers question: http://stackoverflow.com/q/52099650
accepted answer of: http://stackoverflow.com/q/52099650

http://stackoverflow.com/q/52073187
has comment: http://stackoverflow.com/comment/91096429
favorite count: 0
has comment: http://stackoverflow.com/comment/91097511
type: Question
tagged with: django
tagged with: python
has body: I'm currently learning how to write tests in Django: I've used the approach to create an extra test folder which has test files for every "Django module". tests/ test_urls.py test_views.py test_models.py ... My problem is that I don't know the exact different between the test_urls.py file and test_views.py For example I have this test: def test_login_url(self): path = reverse('login') response = self.client.get(path) self.assertEqual(response.status_code, 200) Should I place this test in the test_urls.py file or in test_views.py The "login" url is in the urls.py file but the view that belongs to that url is in views.py Which file should I choose? Are there any best practices for this?
has comment: http://stackoverflow.com/comment/91097078
has title: Difference between test_urls.py and test_views.py
has comment: http://stackoverflow.com/comment/91096975
upvote count: 1
answer count: 1
tagged with: testing
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/52073519
downvote count: 0
score: 1

ethereum
type: Tag
tags question: http://stackoverflow.com/q/52104686
tag name: ethereum
tags question: http://stackoverflow.com/q/52081776

http://stackoverflow.com/comment/90980727
type: QuestionComment
comment on: http://stackoverflow.com/q/52015029
score: 0
has text: I think in general it is, but… That `import foo` declares that you’re going to use functions/types/constants out of `foo`, not just `foo.bar`. When the sub packages are closely related, this doesn’t add much information—if you imported `importlib.util` I won’t be surprised if you call `importlib` functions. But when they’re more independent, it is—using `os.path` doesn’t inherently imply that you’re going to use `os`.
type: Comment

http://stackoverflow.com/a/51994987
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51990272
type: Answer
answers question: http://stackoverflow.com/q/51990272
has body: You can use CSS selector to select all &lt;td&gt; tags that contain attribute style with string color: #F5645C and then apply method find_next(): for td in soup.select('td[style*="color: #F5645C"]'): print(td.find_next('td').text) This prints: Michael Lisa John Francesca
upvote count: 1
score: 1

graph
tags question: http://stackoverflow.com/q/52030344
tag name: graph
tags question: http://stackoverflow.com/q/52102791
tags question: http://stackoverflow.com/q/52084122
tags question: http://stackoverflow.com/q/52066886
tags question: http://stackoverflow.com/q/52014798
tags question: http://stackoverflow.com/q/51957550
type: Tag
tags question: http://stackoverflow.com/q/52013446
tags question: http://stackoverflow.com/q/52016961
tags question: http://stackoverflow.com/q/52063999

http://stackoverflow.com/q/51987299
favorite count: 0
has comment: http://stackoverflow.com/comment/90924240
has title: Connection error in python-requests
tagged with: python
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/51987491
downvote count: 0
score: 1
tagged with: python-requests
type: Question
tagged with: anaconda
has answer: http://stackoverflow.com/a/51988205
accepted answer: http://stackoverflow.com/a/51988205
has comment: http://stackoverflow.com/comment/90926245
has body: I'm trying to search using beautifulsoup with anaconda for python 3.6. I am trying to scrape accuweather.com to find the weather in Tel Aviv. This is my code: from bs4 import BeautifulSoup import requests data=requests.get("https://www.accuweather.com/he/il/tel- aviv/215854/weather-forecast/215854") soup=BeautifulSoup(data.text,"html parser") soup.find('div',('class','info')) I get this error: raise ConnectionError(err, request=request) ConnectionError: ('Connection aborted.', OSError("(10060, 'WSAETIMEDOUT')",)) What can I do and what does this error mean?
has answer: http://stackoverflow.com/a/51987491
answer count: 2
upvote count: 1
has comment: http://stackoverflow.com/comment/90925203
has comment: http://stackoverflow.com/comment/90925495
has comment: http://stackoverflow.com/comment/90925076

http://stackoverflow.com/a/52005498
has comment: http://stackoverflow.com/comment/90961834
has comment: http://stackoverflow.com/comment/90966870
type: Answer
answers question: http://stackoverflow.com/q/52005385
score: 1
has body: You can certainly do random selections of a random number of scripts, e.g. say you want to run between 2 and 5 scripts for 10 runs then you can simply do: import random scripts = ['script1', 'script2', 'script3', 'script4', 'script5'] number_of_runs = 10 for run in range(number_of_runs): for script in random.sample(scripts, k=random.randint(2, 5)): print("Run {}: {}".format(run, script)) # execute script
upvote count: 1
downvote count: 0

http://stackoverflow.com/q/52017963
has answer: http://stackoverflow.com/a/52021674
has title: How to detect green lanes and border of the football field?
tagged with: hough-transform
upvote count: 5
has answer: http://stackoverflow.com/a/58091937
answer count: 4
has body: I am tring to somehow very accurate detect green lanes and border of the footbal field. Here if my code and result but looks like I something missed and I guess result can be much better img = cv2.imread(im_path) gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) kernel_size = 3 bilarImg = cv2.bilateralFilter(gray,7,7,7) image_enhanced = cv2.equalizeHist(bilarImg) plt.imshow(image_enhanced) masked_edges = cv2.Canny(image_enhanced, 100, 170, apertureSize = 3) plt.imshow(masked_edges, cmap='gray') # Define the Hough transform parameters # Make a blank the same size as our image to draw on rho = 2 # distance resolution in pixels of the Hough grid theta = np.pi/180 # angular resolution in radians of the Hough grid threshold = 110 # minimum number of votes (intersections in Hough grid cell) min_line_length = 90 #minimum number of pixels making up a line max_line_gap = 20 # maximum gap in pixels between connectable line segments line_image = np.copy(img)*0 #creating a blank to draw lines on # Run Hough on edge detected image lines = cv2.HoughLinesP(masked_edges, rho, theta, threshold, np.array([]), min_line_length, max_line_gap) # Iterate over the output "lines" and draw lines on the blank for line in lines: for x1,y1,x2,y2 in line: cv2.line(line_image,(x1,y1),(x2,y2),(255,255,255),2) # Create a "color" binary image to combine with line image color_edges = np.dstack((masked_edges, masked_edges, masked_edges)) # Draw the lines on the edge image combo = cv2.addWeighted(color_edges, 0.8, line_image, 1, 0) # remove small objects se1 = cv2.getStructuringElement(cv2.MORPH_RECT, (3,3)) combo = cv2.morphologyEx(combo, cv2.MORPH_OPEN, se1) cv2.imwrite("gray.png", image_enhanced) cv2.imwrite("res.png", combo) Here is src image: and results Ideally I would keep only field border and vertical lines of green lanes.
downvote count: 0
type: UnansweredQuestion
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/52031663
score: 5
has answer: http://stackoverflow.com/a/52031707
tagged with: python
tagged with: computer-vision
tagged with: opencv
has comment: http://stackoverflow.com/comment/93716240

dictionary
tags question: http://stackoverflow.com/q/52041232
tags question: http://stackoverflow.com/q/52001964
tags question: http://stackoverflow.com/q/51962854
tags question: http://stackoverflow.com/q/51991052
tags question: http://stackoverflow.com/q/52088762
tags question: http://stackoverflow.com/q/52064649
tags question: http://stackoverflow.com/q/51997881
tags question: http://stackoverflow.com/q/52038466
tags question: http://stackoverflow.com/q/51963134
tags question: http://stackoverflow.com/q/52012798
tags question: http://stackoverflow.com/q/51973105
tags question: http://stackoverflow.com/q/52028482
tags question: http://stackoverflow.com/q/52013541
tags question: http://stackoverflow.com/q/52053845
tags question: http://stackoverflow.com/q/51957849
tags question: http://stackoverflow.com/q/51986258
tags question: http://stackoverflow.com/q/51984682
tags question: http://stackoverflow.com/q/52021223
tags question: http://stackoverflow.com/q/52085573
tags question: http://stackoverflow.com/q/52072604
tags question: http://stackoverflow.com/q/51990646
tags question: http://stackoverflow.com/q/52010628
tags question: http://stackoverflow.com/q/52096279
tags question: http://stackoverflow.com/q/51996545
tags question: http://stackoverflow.com/q/52068188
tags question: http://stackoverflow.com/q/52099650
tags question: http://stackoverflow.com/q/51959497
tags question: http://stackoverflow.com/q/52062893
tags question: http://stackoverflow.com/q/52003858
tags question: http://stackoverflow.com/q/52029013
tags question: http://stackoverflow.com/q/51981627
tags question: http://stackoverflow.com/q/52103063
tags question: http://stackoverflow.com/q/52062156
tags question: http://stackoverflow.com/q/52023867
tags question: http://stackoverflow.com/q/52007830
tags question: http://stackoverflow.com/q/51996871
tags question: http://stackoverflow.com/q/52107864
tags question: http://stackoverflow.com/q/52027563
tags question: http://stackoverflow.com/q/51995270
tags question: http://stackoverflow.com/q/52005471
tags question: http://stackoverflow.com/q/52067004
tags question: http://stackoverflow.com/q/52059309
tag name: dictionary
tags question: http://stackoverflow.com/q/51961496
tags question: http://stackoverflow.com/q/52077888
tags question: http://stackoverflow.com/q/52029148
tags question: http://stackoverflow.com/q/51999007
tags question: http://stackoverflow.com/q/52011846
tags question: http://stackoverflow.com/q/52094996
tags question: http://stackoverflow.com/q/52104310
tags question: http://stackoverflow.com/q/52087845
tags question: http://stackoverflow.com/q/52060788
tags question: http://stackoverflow.com/q/52081545
tags question: http://stackoverflow.com/q/51963659
tags question: http://stackoverflow.com/q/52032714
tags question: http://stackoverflow.com/q/51979357
tags question: http://stackoverflow.com/q/51959569
tags question: http://stackoverflow.com/q/52011401
tags question: http://stackoverflow.com/q/51986297
tags question: http://stackoverflow.com/q/52006711
tags question: http://stackoverflow.com/q/52104839
tags question: http://stackoverflow.com/q/51995808
tags question: http://stackoverflow.com/q/52074701
tags question: http://stackoverflow.com/q/52001019
tags question: http://stackoverflow.com/q/52022178
tags question: http://stackoverflow.com/q/51984121
tags question: http://stackoverflow.com/q/51974207
tags question: http://stackoverflow.com/q/51994575
tags question: http://stackoverflow.com/q/52029520
tags question: http://stackoverflow.com/q/52022271
tags question: http://stackoverflow.com/q/51963174
tags question: http://stackoverflow.com/q/52084899
tags question: http://stackoverflow.com/q/52033056
tags question: http://stackoverflow.com/q/52000649
tags question: http://stackoverflow.com/q/52052397
tags question: http://stackoverflow.com/q/51959329
tags question: http://stackoverflow.com/q/52106580
tags question: http://stackoverflow.com/q/51957374
tags question: http://stackoverflow.com/q/52033242
tags question: http://stackoverflow.com/q/51994213

http://stackoverflow.com/comment/91056337
has text: TRY explicit wait using Expected conditions class once and see if issue still persists
comment on: http://stackoverflow.com/q/52051934
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/a/52089336
has comment: http://stackoverflow.com/comment/91129421
has comment: http://stackoverflow.com/comment/91129236
score: 3
has body: Updated In [180]: pd.crosstab(df.Destination, df.Station.str[3:6]) Out[180]: Station ABC ABD ABX ABY Destination KPS 1 1 0 0 MRK 1 1 0 0 MRS 0 0 1 0 MTS 0 0 0 1 You could use In [160]: pd.DataFrame([df.Station.str[3:6].value_counts().to_dict()]) Out[160]: ABC ABD ABX ABY 0 2 2 1 1 Or, In [149]: df.Station.str[3:6].value_counts().to_frame().T Out[149]: ABC ABD ABX ABY Station 2 2 1 1 Details In [162]: df.Station.str[3:6] Out[162]: 0 ABC 1 ABD 2 ABX 3 ABY 4 ABC 5 ABD Name: Station, dtype: object In [163]: df.Station.str[3:6].value_counts() Out[163]: ABC 2 ABD 2 ABX 1 ABY 1 Name: Station, dtype: int64
upvote count: 3
has comment: http://stackoverflow.com/comment/91129037
type: Answer
downvote count: 0
answers question: http://stackoverflow.com/q/52089327

http://stackoverflow.com/a/52111768
score: 1
has comment: http://stackoverflow.com/comment/91189645
upvote count: 2
has comment: http://stackoverflow.com/comment/91174323
downvote count: 1
answers question: http://stackoverflow.com/q/52111627
has body: What I would do would be just put it in one loop. if index is 0 to 83 for i in range(0,84): if i&gt;=0 and i&lt;=20: a.append(codes[i]) elif i&gt;20 and i&lt;=41: b.append(codes[i]) elif i&gt;41 and i&lt;=62: c.append(codes[i]) elif i&gt;62 and i&lt;=83: d.append(codes[i])
type: Answer

http://stackoverflow.com/q/52044333
downvote count: 0
has comment: http://stackoverflow.com/comment/91040503
favorite count: 0
has title: Add a date range column to Queryset
has comment: http://stackoverflow.com/comment/91067233
has answer: http://stackoverflow.com/a/52044591
has answer: http://stackoverflow.com/a/52058798
tagged with: python
type: UnansweredQuestion
tagged with: django
upvote count: 1
type: Question
score: 1
has body: Django newbie, thanks in advance for any help. I want to add a field that includes a date range for a grouping. The date range would look like "1/1/2018 to 1/2/2018" where the first date is the minimum date and the second is the maximum date in the set for a particular name. qs = Qs.objects.filter(**filter_kwargs) \ .values('name') .annotate(v1 = Sum('something') , DATE_RANGE = Min('date') + ' - ' + Max('date')) .order_by() The end goal is to be able to display this in the template.
answer count: 2
has comment: http://stackoverflow.com/comment/91067555

http://stackoverflow.com/q/52030554
has body: Basically, I'm running a reinforcement learning model in eager mode and I need to limit the amount of memory that each process will claim from the gpu. In the graph api, this could be achieved by modifying a tf.ConfigProto() object and creating a session with said config object. However, in eager api, there is no session. My doubt then is, how can I manage gpu memory in this case?
score: 2
downvote count: 0
tagged with: tensorflow
type: Question
has answer: http://stackoverflow.com/a/52044760
has title: Allocating gpu fraction eager execution
tagged with: keras
upvote count: 2
tagged with: deep-learning
answer count: 1
favorite count: 0
type: UnansweredQuestion
tagged with: python

batch-normalization
tag name: batch-normalization
tags question: http://stackoverflow.com/q/52024253
type: Tag

http://stackoverflow.com/comment/91078563
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52063999
has text: It is actually a graph I'm trying to create. graph package is most welcome
score: 0

http://stackoverflow.com/comment/91023182
score: 2
type: QuestionComment
has text: ... this sounds like the [XY problem](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem). You want a piece of your program (a thread?) to wait for a certain "state" of an other piece of your program (an other thread)... the proper way to do that is using synchronization primitives.
type: Comment
comment on: http://stackoverflow.com/q/52036520

http://stackoverflow.com/q/51965706
upvote count: 3
has body: Problem Consider P: A (N, n_x) matrix. Then I want to find the indices of a sparse COO matrix such that indices = [] for i in range(N): for j1 in range(n_x): for j2 in range(n_x): indices.append([P[i, j1], P[i, j2]]) indices = unique(indices, axis=0) Faster Solution The above solution is both inefficient in terms of time and memory. A faster option using Numpy is below col_idx = np.reshape(np.tile(P, n_x), [N, n_x, n_x]) row_idx = np.transpose(col_idx, [0,2,1]) indices = np.concatenate((row_idx[:,None], col_idx[:, None]), axis=1) indices = np.unique(indices, axis=0) Note however that this still requires building 2 N*n_x*n_x arrays which can be much larger than necessary if we only have a small number of unique elements. Question How can I build a fast but also memory efficient algorithm for doing the following. Currently the fast solution is not usable as it requires too much memory. The solution could be Python but also an algorithm that I could code in C would suffice.
tagged with: python
has title: Building sparse COO matrix structure from Cartesian product of indices
downvote count: 0
type: UnansweredQuestion
type: Question
score: 3
has answer: http://stackoverflow.com/a/52040537
answer count: 1
tagged with: sparse-matrix
favorite count: 0

http://stackoverflow.com/comment/91127401
has text: Thanks @BobbyDurrett but most of the time the comments can be extensive because I use org-mode to write data science reports and using print statements wouldn’t be feasible for me.
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/52067440
type: Comment

http://stackoverflow.com/comment/90984025
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/52017013
has text: have you read what you posted? It literally makes no sense in English
type: Comment

http://stackoverflow.com/comment/91007950
comment on: http://stackoverflow.com/q/52028794
type: Comment
type: QuestionComment
has text: You can do this pretty easily with a loop and simple arithmetic.
score: 0

http://stackoverflow.com/q/51998314
has comment: http://stackoverflow.com/comment/90949350
score: 0
type: UnansweredQuestion
upvote count: 1
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/90945760
has title: How to correctly write boolean expression involving python dictionaries
has body: I have two python dictionary structures in which I am looking up for a specific key. But python evaluates it to None if the value is 0 . I am using Python2.7 A = {'distribution_1':{'mu':0.0,'sigma':0.5}} B = {'distribution_1':{'sigma':0.1}} x = A.get('mu') or B.get('mu') # This evaluates to None, expected 0.0 whereas A = {'distribution_1':{'mu':0.1,'sigma':0.5}} B = {'distribution_1':{'sigma':0.1}} x = A.get('mu') or B.get('mu') # This evaluates to 0.1 To set the context, these two dictionaries contain parameters for probability distributions
tagged with: boolean
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/51998569
tagged with: python
tagged with: dictionary

http://stackoverflow.com/q/52082520
tagged with: python
has answer: http://stackoverflow.com/a/52085253
type: UnansweredQuestion
tagged with: pyside2
tagged with: pyqt5
upvote count: 1
type: Question
score: 1
has body: I've this question that has tangled my brain for so many days by now. It possible to connect a pyqt slider value onto a Maya current time change? I have a slider that represents the rotation value, if these values are keyframed and change over time the slider doesn't.
has title: Move a PyQt slider based on maya timeline
downvote count: 0
answer count: 1
favorite count: 0
tagged with: maya

http://stackoverflow.com/comment/100719475
comment on: http://stackoverflow.com/q/51975231
score: 0
has text: I am asking this question because I feel it is important to understand why the top companies in the world would prefer such a style. By understanding why the top coders do this I can better learn the language. It's not about admitting google has the best style, it's about learning from different perspective. It's very funny to see people attacking me for asking this and downvoting the question.
type: Comment
type: QuestionComment

http://stackoverflow.com/a/52106744
type: Answer
answers question: http://stackoverflow.com/q/52105938
score: 0
has body: This list comprehension should handle the whitespace you are encountering: s = "\t42 4 -17 \n" sorted([int(x) for x in " ".join(s.split()).split()]) [-17, 4, 42]

http://stackoverflow.com/a/52102026
answers question: http://stackoverflow.com/q/52101881
has body: You can do with mask and to_numeric, this will mask all nonnumeric value to NaN df=df.mask(df.apply(pd.to_numeric,errors = 'coerce').isnull(),df.astype(str).apply(lambda x : x.str.strip())) df Out[572]: a b k 0 1 a q 1 2 b 1 2 3 c e 3 4 d r
type: Answer
score: 3
upvote count: 3
accepted answer of: http://stackoverflow.com/q/52101881
downvote count: 0
type: AcceptedAnswer

http://stackoverflow.com/q/52055318
tagged with: python
possible better answer: http://stackoverflow.com/a/52055363
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/52055467
type: Question
type: AnsweredQuestion
has body: I have this data frame DF1 emp_no no_children status 1 3 3 2 2 2 23 5 5 And another DF2 emp_no no_children status 1 3 3 2 2 2 3 5 5 I am trying to create a new dataframe based on DF1 and DF2 e.g emp_no no_children status 23 5 5 the new DF should contain emp_no not in DF2
has title: Create new data frame based on another data frame
has answer: http://stackoverflow.com/a/52056746
has answer: http://stackoverflow.com/a/52055467
has answer: http://stackoverflow.com/a/52055363
score: 0
answer count: 3
tagged with: pandas

masking
tag name: masking
tags question: http://stackoverflow.com/q/52010551
type: Tag

http://stackoverflow.com/q/51973670
accepted answer: http://stackoverflow.com/a/51977363
downvote count: 2
has body: I am trying to download all sample files from my s3 bucket in amazon ec2 via boto3 and python3 script to my local hard drive. Here is the script. #downloading files from s3 import boto3 import sys import os import argparse import threading from botocore.client import Config instance_id = "i-03e7f6391a0f523ee" action = 'ON' ec2 = boto3.client('ec2') s3=boto3.resource('s3') for bucket in s3.buckets.all(): print(bucket.name) my_bucket=s3.Bucket('tkbucket32') print("listing all files in bucket") for s3_file in my_bucket.objects.all(): print(s3_file.key) s3.meta.client.download_file('tkbucket32', 'hello.txt', '/tmp/hello.txt') Currently there are following files in bucket hello.txt myhomepage.html Now I want them to be downloaded to D:\folder1\folder2\folder3 I am running scripts in Windows 7. My problem is this line s3.meta.client.download_file('tkbucket32', 'hello.txt', '/tmp/hello.txt') Where do I specify the path of on local hard drive where I want to download these files?
type: AnsweredQuestion
tagged with: amazon-s3
score: 1
type: Question
has answer: http://stackoverflow.com/a/51977363
tagged with: boto3
tagged with: amazon-web-services
has title: downloading files from s3 bucket in amazon ec2 to local drive in windows 7
answer count: 1
tagged with: python
favorite count: 0
tagged with: python-3.x
upvote count: 3

http://stackoverflow.com/a/51958637
answers question: http://stackoverflow.com/q/51958604
score: 0
type: Answer
has body: You are being mislead by the output. See: Quoting backslashes in Python string literals In [8]: t = "arst \\'{}\\' arst" In [9]: t Out[9]: "arst \\'{}\\' arst" In [10]: print(t) arst \'{}\' arst In [11]: print(t.format('21-1-2')) arst \'21-1-2\' arst In [12]:

http://stackoverflow.com/comment/91050242
type: QuestionComment
has text: is it possible to grant the access?
score: 0
type: Comment
comment on: http://stackoverflow.com/q/52049875

http://stackoverflow.com/comment/91166600
type: QuestionComment
score: 2
comment on: http://stackoverflow.com/q/52107910
has text: Are you using [pytest-cov](https://github.com/pytest-dev/pytest-cov)? I am not at work right now to look at the setup I am using, by I think what you are asking is the default for pytest-cov.
type: Comment

http://stackoverflow.com/a/52050974
answers question: http://stackoverflow.com/q/52048562
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52048562
type: Answer
has body: Here's one following the same method as with @Bi Rico's post, but with einsum for the norm computations - den = np.sqrt(np.einsum('ij,ij-&gt;i',arr,arr)*np.einsum('j,j',vec,vec)) out = arr.dot(vec) / den Also, we can use vec.dot(vec) to replace np.einsum('j,j',vec,vec) for some marginal improvement. Timings - In [45]: vec = np.random.randn(300,) ...: arr = np.random.randn(400, 300) # @Bi Rico's soln with norm In [46]: %timeit (np.linalg.norm(arr, axis=1) * np.linalg.norm(vec)) 10000 loops, best of 3: 100 µs per loop In [47]: %timeit np.sqrt(np.einsum('ij,ij-&gt;i',arr,arr)*np.einsum('j,j',vec,vec)) 10000 loops, best of 3: 77.4 µs per loop On bigger arrays - In [48]: vec = np.random.randn(3000,) ...: arr = np.random.randn(4000, 3000) In [49]: %timeit (np.linalg.norm(arr, axis=1) * np.linalg.norm(vec)) 10 loops, best of 3: 22.2 ms per loop In [50]: %timeit np.sqrt(np.einsum('ij,ij-&gt;i',arr,arr)*np.einsum('j,j',vec,vec)) 100 loops, best of 3: 8.18 ms per loop
upvote count: 1
score: 1

sqlalchemy
tags question: http://stackoverflow.com/q/52073307
tags question: http://stackoverflow.com/q/51973057
tags question: http://stackoverflow.com/q/52045801
tags question: http://stackoverflow.com/q/52041377
tags question: http://stackoverflow.com/q/52056772
tags question: http://stackoverflow.com/q/52094206
tags question: http://stackoverflow.com/q/51997479
tags question: http://stackoverflow.com/q/52037060
tags question: http://stackoverflow.com/q/52061554
tags question: http://stackoverflow.com/q/51989977
tags question: http://stackoverflow.com/q/52073561
tags question: http://stackoverflow.com/q/51966096
tags question: http://stackoverflow.com/q/52045100
tags question: http://stackoverflow.com/q/52098712
tags question: http://stackoverflow.com/q/52063948
tags question: http://stackoverflow.com/q/52019939
tags question: http://stackoverflow.com/q/51982306
tags question: http://stackoverflow.com/q/51994006
tags question: http://stackoverflow.com/q/51964024
tags question: http://stackoverflow.com/q/52070240
tags question: http://stackoverflow.com/q/52008365
tags question: http://stackoverflow.com/q/52031875
tags question: http://stackoverflow.com/q/52036566
tag name: sqlalchemy
tags question: http://stackoverflow.com/q/51975411
tags question: http://stackoverflow.com/q/52098561
tags question: http://stackoverflow.com/q/52101595
tags question: http://stackoverflow.com/q/52105564
tags question: http://stackoverflow.com/q/52067058
tags question: http://stackoverflow.com/q/51958257
tags question: http://stackoverflow.com/q/52093022
tags question: http://stackoverflow.com/q/51957917
tags question: http://stackoverflow.com/q/52089432
tags question: http://stackoverflow.com/q/51992358
tags question: http://stackoverflow.com/q/52052536
tags question: http://stackoverflow.com/q/52049114
tags question: http://stackoverflow.com/q/52092803
tags question: http://stackoverflow.com/q/52025871
tags question: http://stackoverflow.com/q/52069965
tags question: http://stackoverflow.com/q/52045695
tags question: http://stackoverflow.com/q/52075642
tags question: http://stackoverflow.com/q/51990714
tags question: http://stackoverflow.com/q/52057470
tags question: http://stackoverflow.com/q/52007802
tags question: http://stackoverflow.com/q/51966866
tags question: http://stackoverflow.com/q/52059019
tags question: http://stackoverflow.com/q/51987856
tags question: http://stackoverflow.com/q/51981733
type: Tag

http://stackoverflow.com/a/51990101
has comment: http://stackoverflow.com/comment/90931025
type: Answer
has body: df['Group'] = np.where(df['ID'].isin([1, 2]), 'A', 'B') df2 = df.groupby(['Group','ID']).size() df2.groupby('Group').agg(['mean', 'min', 'max']) Here's what I got: mean min max Group A 2.5 2 3 B 3.0 1 5
accepted answer of: http://stackoverflow.com/q/51989861
downvote count: 0
score: 1
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/51989861
upvote count: 1

http://stackoverflow.com/comment/91021086
type: Comment
has text: @kevinkayaks the image is a 3D numpy array. In the code I set shape=(100, 100, 100), but, generally, I have 512x512x190 images.
score: 0
comment on: http://stackoverflow.com/q/52006223
type: QuestionComment

http://stackoverflow.com/q/52054067
tagged with: numeric
type: Question
has body: I am not too convinced by the parameter optimization classes sklearn provides, in fact GridSearchCV (http://scikit-learn.org/stable/modules/generated/sklearn.model_selection.GridSearchCV.html#sklearn.model_selection.GridSearchCV) just loops over the parameters I pass in via param_grid. RandomizedSearch (http://scikit-learn.org/stable/modules/generated/sklearn.model_selection.RandomizedSearchCV.html) seems like a we-gave-up-approach to me. One of my approaches was to re-use adaptive integration of a function (used in numerical mathematics): basically reduce the search-space of a parameter in every iteration until a certain error-threshold is reached. The biggest advantage of this method is that the error is also reduced in each iteration. The problem is that certain parameter-values may be untouched if you consider the different score-values (precision, roc-auc etc.) as functions. I still got good results in one case, not so good in other cases. What would be a good mathematical approach to optimize values more efficient than GridSearch and RandomizedSearch?
tagged with: numerical-integration
tagged with: optimization
downvote count: 0
tagged with: scikit-learn
has title: Python Sklearn - Multidimensional Parameter Optimization
favorite count: 0
tagged with: python
answer count: 0
type: UnansweredQuestion
score: 1
upvote count: 1

http://stackoverflow.com/q/52083886
tagged with: random
tagged with: for-loop
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91118100
has answer: http://stackoverflow.com/a/52084059
score: 1
has comment: http://stackoverflow.com/comment/91118122
has comment: http://stackoverflow.com/comment/91118385
favorite count: 0
tagged with: tuples
type: Question
tagged with: python
has comment: http://stackoverflow.com/comment/91118069
has title: How to select a random object except one spesific one from a list?
tagged with: list
upvote count: 2
accepted answer: http://stackoverflow.com/a/52084059
answer count: 2
has body: I am designing an experiment with the Expyriment package. There is two boxes and I give them random colors but they must be different from each others. I use for loop and enumerate to loop through: color = [(0, 76, 153), (204, 0, 0), (0, 153, 0), (255, 230, 0)] for i, x in enumerate(color): print(color[i]) print(random.choice(color.remove(color[i]))) 2 problems emerged from here, the tuple I removed gone forever and I got a TypeError: object of type 'NoneType' has no len() I search for a way to temporarely remove an tuple for looping but cant find it. Also, when I tried using pop print(random.choice(color.pop(i))), it didnt give me an error but it just prints int not tuple. Also, object that I pop is still gone forever. Full code> color = [(0, 76, 153), (204, 0, 0), (0, 153, 0), (255, 230, 0)] letter = ('b', 'r', 'g', 'y') for i, x in enumerate(color): frame = stimuli.Canvas((600, 600)) sti = stimuli.TextLine(letter[i], text_bold=True, text_colour=misc.constants.C_WHITE, text_size=100, text_font='calibri') positions = (200, -200) n = (0, 1) ac = random.choice(n) # randomize the place of true box sti_squ_1 = stimuli.Rectangle((100, 100), colour=color[i], position=(positions[ac], -200)) # true box sti_squ_2 = stimuli.Rectangle((100, 100), colour=color[random.choice(color.remove(color[i]))], position=(positions[1 - ac], -200))
downvote count: 1
has comment: http://stackoverflow.com/comment/91118144
has comment: http://stackoverflow.com/comment/91118155
possible better answer: http://stackoverflow.com/a/52084231
has comment: http://stackoverflow.com/comment/91118130
has answer: http://stackoverflow.com/a/52084231

http://stackoverflow.com/comment/91192371
type: Comment
has text: I think it cannot decrease with time because I am actually following the gradient so that the weights of the linear regression are adjusted towards the TD-target. Considering that, how is it possible to perform updates in a direction that the value function becomes more and more inexact? I can assume that, because it is gradient descent, the figure is not always monotonically increasing, but there is one point in which it becomes monotonically decreasing and that can't fit in my brain. I checked also that the weights don't grow towards infinity...
comment on: http://stackoverflow.com/a/52112494
type: AnswerComment
score: 0

http://stackoverflow.com/comment/91128180
has text: numPos must be smaller than tbe actual number of your available positive samples, because if your minHitRate is less than 1, you will lose samples on each stage (up to (1-minHitRate) which is about 0.1 of the total number for 20 stages and minHitRate 0.999), but you can't be sure that you won't lose additional yetvunused samples, because you don't know whether they share the features..
type: Comment
comment on: http://stackoverflow.com/q/52084725
score: 0
type: QuestionComment

http://stackoverflow.com/q/52087044
answer count: 4
favorite count: 0
has comment: http://stackoverflow.com/comment/91127897
tagged with: python
score: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91125206
possible better answer: http://stackoverflow.com/a/52087159
has title: How to identify a sentences related to a topic?
type: Question
has answer: http://stackoverflow.com/a/52087670
has comment: http://stackoverflow.com/comment/91124395
has body: Im doing a project that require me to sort the document to match with topic. For example, I have 4 topics which is Lecture, Tutor, Lab and Exam. I have some sentences which are: Lecture was engaging Tutor is very nice and active The content of lecture was too much for 2 hours. Exam seem to be too difficult compare with weekly lab. And now I wanna sort these sentences into topic above, result should be: Lecture: 2 Tutor: 1 Exam: 1 I did research and the most instruction I found is using LDA topic modeling. But seem like cannot solve my problem because as I know LDA support for identifying topic in document, and dont know how to pre-choose topic manually. Could anyone help me please? Im stuck with that.
tagged with: nltk
downvote count: 0
has answer: http://stackoverflow.com/a/52088896
accepted answer: http://stackoverflow.com/a/52088896
has comment: http://stackoverflow.com/comment/91124755
upvote count: 2
linked to: http://stackoverflow.com/q/3113428
has answer: http://stackoverflow.com/a/52087080
has answer: http://stackoverflow.com/a/52087159

python-2.x
tags question: http://stackoverflow.com/q/51997003
tags question: http://stackoverflow.com/q/52079640
tags question: http://stackoverflow.com/q/51994368
tags question: http://stackoverflow.com/q/51994148
tag name: python-2.x
type: Tag
tags question: http://stackoverflow.com/q/51990688
tags question: http://stackoverflow.com/q/52104374
tags question: http://stackoverflow.com/q/52005381
tags question: http://stackoverflow.com/q/52063244

cisco
type: Tag
tag name: cisco
tags question: http://stackoverflow.com/q/52076141

http://stackoverflow.com/a/52084933
has comment: http://stackoverflow.com/comment/91153879
has comment: http://stackoverflow.com/comment/91120481
upvote count: 1
has body: AttributeError: module 'selenium.webdriver' has no attribute 'execute_script' You are getting this error because 'execute_script' is not a class attribute, you just can not use it directly. Since it is an instance attribute you should create an instance of the class. Please check here to learn more about classes. This will work fine now since 'execute_script' is running as an instance attribute. last_height = browser.execute_script("return document.body.scrollHeight") Your final code would have looked like this: import time import pandas as np import numpy as np from selenium import webdriver from selenium.webdriver.common.keys import Keys from selenium.webdriver.common.by import By browser = webdriver.Chrome() url = 'https://twitter.com/search?f=tweets&amp;q=csubwaystats%20since%3A2018-05-28%20until%3A2018-08-28' browser.get(url) time.sleep(1) SCROLL_PAUSE_TIME = 0.5 # Get scroll height last_height = browser.execute_script("return document.body.scrollHeight") while True: # Scroll down to bottom webdriver.execute_script("window.scrollTo(0,document.body.scrollHeight);") # Wait to load page time.sleep(SCROLL_PAUSE_TIME) # Calculate new scroll height and compare with last scroll height new_height = webdriver.execute_script("return document.body.scrollHeight") if new_height == last_height: break last_height = new_height
answers question: http://stackoverflow.com/q/52084458
has comment: http://stackoverflow.com/comment/91122151
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/91153813
has comment: http://stackoverflow.com/comment/91153903
type: Answer

http://stackoverflow.com/comment/90954473
has text: DO NOT use the dev server for production !!! it's a DEVELOPPER tool only, it's absolutely NOT made to be used in production. Use a proper frontend web server and wsgi connector instead.
type: Comment
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/52002647

http://stackoverflow.com/comment/126077697
comment on: http://stackoverflow.com/a/52973985
score: 0
type: AnswerComment
has text: Not to be contrarian, but I find that CEM's awswrangler answer below (https://stackoverflow.com/a/67294231/3897315) is by far the best solution for queries I have been making. However, very large queries, you may need special permissions to apply the default ctas_approach=True flag. (Documentation linked in his solution.)
type: Comment

http://stackoverflow.com/a/51997210
score: 1
accepted answer of: http://stackoverflow.com/q/51997029
answers question: http://stackoverflow.com/q/51997029
upvote count: 1
has body: Using column_stack: pd.DataFrame(np.column_stack(data).T) 0 1 2 0 1 2 3 1 1 2 3 2 1 2 3 3 4 5 6 4 4 5 6 5 7 8 9
type: AcceptedAnswer
type: Answer
downvote count: 0

http://stackoverflow.com/comment/90882330
comment on: http://stackoverflow.com/a/51966220
has text: @DBA108642 you could also use `reduce` for this (albeit it harder to grok what you're doing), eg: `functools.reduce(lambda x, y: (x[0] + (y[0] > y[1]), x[1] + (y[0] < y[1])), zip(a[:3], b[:3]), (0, 0))`...
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/90897238
score: 1
comment on: http://stackoverflow.com/q/51973319
has text: Are you misogynist? What does it have to do to be a girl or boy here?
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52013248
has comment: http://stackoverflow.com/comment/90977290
answer count: 1
tagged with: database
has body: I've just finished a segment about stopping the spam in a forums database, and now it's time to clean them up. The goal is to use an update statement to update the database records and delete the posts marked as spam. After scratching my head and receiving vague hints and instructions from an online Instructor (this is for an online class), I've ran into an error. This may not be the correct way to do this, and I'm looking for guidance after having no luck on google. Here is a snippet of forumdb.py: # "Database code" for the DB Forum. import bleach import psycopg2 import datetime DBNAME = "forum" def get_posts(): """Return all posts from the 'database', most recent first.""" db = psycopg2.connect(database=DBNAME) c = db.cursor() UPDATE posts SET content = 'cheese' WHERE content like 'spam' ; c.execute("select content, time from posts order by time desc") return c.fetchall() db.close() def add_post(content): """Add a post to the 'database' with the current timestamp.""" db = psycopg2.connect(database=DBNAME) c = db.cursor() clean_cont = bleach.clean(content) c.execute("insert into posts values (%s)", (clean_cont,)) db.commit() db.close() And here is the error I get: Traceback (most recent call last): File "forum.py", line 7, in <module> from forumdb import get_posts, add_post File "/vagrant/forum/forumdb.py", line 13 UPDATE posts ^ SyntaxError: invalid syntax In case it helps, here is forum.py: #!/usr/bin/env python3 # # A buggy web service in need of a database. from flask import Flask, request, redirect, url_for from forumdb import get_posts, add_post app = Flask(__name__) # HTML template for the forum page HTML_WRAP = '''\ DB Forum DB Forum Post message %s ''' # HTML template for an individual comment POST = '''\ %s %s ''' @app.route('/', methods=['GET']) def main(): '''Main page of the forum.''' posts = "".join(POST % (date, text) for text, date in get_posts()) html = HTML_WRAP % posts return html @app.route('/', methods=['POST']) def post(): '''New post submissi…
type: AnsweredQuestion
tagged with: sql
has answer: http://stackoverflow.com/a/52013263
tagged with: bleach
has comment: http://stackoverflow.com/comment/90977326
has title: SQL syntax error on table name
type: Question
tagged with: python
has comment: http://stackoverflow.com/comment/90977313
accepted answer: http://stackoverflow.com/a/52013263
score: 0
tagged with: mysql

http://stackoverflow.com/q/51970497
type: AnsweredQuestion
downvote count: 0
accepted answer: http://stackoverflow.com/a/51970718
linked to: http://stackoverflow.com/q/39257712
favorite count: 0
type: Question
tagged with: python
score: 4
has title: How to display x axis labels on all bar chart subplots?
answer count: 1
has body: Problem: I am trying to display all of the labels on my bar chart subplots. I have tried everything in this answer and this answer with no luck. Data: data = StringIO(""" Index-- --Rk Passing-Player Passing-Cmp Passing-Att Passing-Pct Passing-Yds Passing-Y/A Passing-AY/A Passing-TD Passing-Int Passing-Rate 0 0 1 Patrick Mahomes 364 573 63.5 4653 8.1 8.2 36 15 147.2 1 1 2 Davis Webb 22 41 53.7 300 7.3 8.3 2 0 131.2 2 2 3 Nic Shimonek 1 2 50.0 18 9.0 9.0 0 0 125.6 3 3 4 Jakeem Grant 1 1 100.0 72 72.0 92.0 1 0 1034.8 4 4 5 Jonathan Giles 1 1 100.0 3 3.0 3.0 0 0 125.2 5 5 6 Ian Sadler 0 1 0.0 0 0.0 0.0 0 0 0.0 """) df = pd.read_table(data, delim_whitespace=True) dfs = [df] * 9 Plotting code: fig, axs = plt.subplots(3,3, figsize=(10,10), sharey=True, sharex=False) for ax,df in zip(axs.ravel(), dfs): ax.bar(df['Passing-Player'], df['Passing-Yds']) for tick in ax.get_xticklabels(): tick.set_visible(True) fig.autofmt_xdate(rotation=90) fig.tight_layout(pad=2.0, w_pad=2.0, h_pad=10.0) fig.savefig("tester.png") Result: How can I display all of the x axis labels because in my real data each plot is different with different player names.
tagged with: matplotlib
has answer: http://stackoverflow.com/a/51970718
upvote count: 4
linked to: http://stackoverflow.com/q/46912100
has comment: http://stackoverflow.com/comment/90891741

http://stackoverflow.com/comment/90900360
comment on: http://stackoverflow.com/a/51974914
type: Comment
score: 0
type: AnswerComment
has text: besides, it's really over complicated and hard to understand.

http://stackoverflow.com/comment/90979469
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52014473
has text: Hey @Atif. Have you tried running this without using sep= At all? Pandas does a pretty good job of working out the delimiter for you. So... “df=pd.read_csv(os.path.join(path,file),error_bad_lines=False,engine='python’)”

http://stackoverflow.com/comment/90992747
score: 0
comment on: http://stackoverflow.com/q/52020838
has text: I'm not sure this is quite a duplicate of [this question](https://stackoverflow.com/questions/1207406/), [this one](https://stackoverflow.com/questions/6022764/), or [this one](https://stackoverflow.com/questions/6500888/). The answers do explain the problem, once you realize that you're trying to delete from the same list you're iterating over, but the alternatives they suggest aren't really necessary here.
type: Comment
type: QuestionComment

http://stackoverflow.com/a/51977554
accepted answer of: http://stackoverflow.com/q/51977511
type: AcceptedAnswer
type: Answer
score: 3
downvote count: 0
has body: v=[x for i in od.values() for x in list(i.values())[0]] l=['red','blue','one'] correct=[i for i in v if i in l] incorrect=[i for i in l if i not in v] print(correct) print(incorrect) Output: ['blue'] ['red', 'one']
answers question: http://stackoverflow.com/q/51977511
upvote count: 3

http://stackoverflow.com/q/52029233
has answer: http://stackoverflow.com/a/70029045
score: 14
tagged with: opencv
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/70253370
has answer: http://stackoverflow.com/a/67500768
possible better answer: http://stackoverflow.com/a/60603969
has comment: http://stackoverflow.com/comment/91009080
type: Question
has comment: http://stackoverflow.com/comment/91009419
downvote count: 0
has answer: http://stackoverflow.com/a/60603969
tagged with: windows-7-x64
has body: I copied code from https://stackoverflow.com/a/34588758/210342 and used with default (built-in) camera, it worked. Then I attached USB camera, tested it with VLC and changed the code to open camera 1: cam = cv2.VideoCapture(1) I check whether the camera is open cam.isOpened() -- it is -- but the camera is not enabled (its hardware indicator, LED, is off) and indeed all I see on the screen is black frame. Is there some extra special code to add in order to enable USB camera?
upvote count: 14
has answer: http://stackoverflow.com/a/77396996
answer count: 7
tagged with: python
accepted answer: http://stackoverflow.com/a/52029556
has answer: http://stackoverflow.com/a/78344413
favorite count: 0
tagged with: webcam
has title: How to make USB camera work with OpenCV?
has comment: http://stackoverflow.com/comment/91009187
linked to: http://stackoverflow.com/q/34588464
has answer: http://stackoverflow.com/a/52029556

http://stackoverflow.com/q/52010127
has answer: http://stackoverflow.com/a/52946121
tagged with: python
answer count: 1
tagged with: save
score: 0
has comment: http://stackoverflow.com/comment/90972190
has title: How to export complex array from python to tiff file for IDL
tagged with: tiff
tagged with: idl-programming-language
type: UnansweredQuestion
has body: I have a complex 2D numpy array and I would like to save it as a tiff file to import it into IDL. What would be the best way to do this? Thanks!
type: Question

http://stackoverflow.com/a/52027692
upvote count: 4
has comment: http://stackoverflow.com/comment/91005894
score: 4
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/52026962
has body: It'd be nice if plot_implicit could work directly with one complex symbol z, but at present it cannot: the expectation is that the user provides an expression with two real symbols. So do that, by introducing real x, y and making z an expression with x and y. from sympy import symbols, Eq, I from sympy.plotting import plot_implicit x, y = symbols('x y', real=True) z = x + I*y expr = Eq(abs(z), 1) p1 = plot_implicit(expr)
type: Answer
accepted answer of: http://stackoverflow.com/q/52026962

http://stackoverflow.com/q/52004887
tagged with: parallel-processing
has title: Multiprocessing fails to pickle top level functions
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/93831542
score: 1
has body: I am trying to parallelize my task and decided to use the multiprocessing (mp) module. I have soon learnt that mp can't handle nested functions, so I had to unnest a function similar to this: def foo(nomer1, nomer2): def bar(nomer1, nomer2): return ([nomer1] * nomer2) return(bar(nomer1, nomer2)) to this: def bar(nomer1, nomer2): return([nomer1]*nomer2) def foo(nomer1, nomer2): return(bar(nomer1, nomer2)) However, when I run: import multiprocessing as mp n_proc = 2 pool = mp.Pool(processes=n_proc) pool.starmap(foo, [11, 2]) The console produces this error: Traceback (most recent call last): File "&lt;input&gt;", line 1, in &lt;module&gt; File "C:\Users\user\Anaconda2\envs\env1\lib\multiprocessing\pool.py", line 274, in starmap return self._map_async(func, iterable, starmapstar, chunksize).get() File "C:\Users\user\Anaconda2\envs\env1\lib\multiprocessing\pool.py", line 644, in get raise self._value File "C:\Users\user\Anaconda2\envs\env1\lib\multiprocessing\pool.py", line 424, in _handle_tasks put(task) File "C:\Users\user\Anaconda2\envs\env1\lib\multiprocessing\connection.py", line 206, in send self._send_bytes(_ForkingPickler.dumps(obj)) File "C:\Users\user\Anaconda2\envs\env1\lib\multiprocessing\reduction.py", line 51, in dumps cls(buf, protocol).dump(obj) _pickle.PicklingError: Can't pickle &lt;function foo at 0x00000189D37902F0&gt;: attribute lookup foo on __main__ failed Foo is on top-most level, as specified in the documentation, but mp still fails to pickle it. How can I solve this, preferably w/out installing additional packages?
favorite count: 0
tagged with: python
has answer: http://stackoverflow.com/a/52005616
type: UnansweredQuestion
tagged with: pickle
upvote count: 1
tagged with: multiprocessing
type: Question

http://stackoverflow.com/comment/90868162
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51958809
has text: if you downvote an accepted answer, you should really leave a comment.
type: AnswerComment

http://stackoverflow.com/a/52039733
has comment: http://stackoverflow.com/comment/91029952
upvote count: 1
has comment: http://stackoverflow.com/comment/91039950
has comment: http://stackoverflow.com/comment/91029934
score: 1
answers question: http://stackoverflow.com/q/52039093
has comment: http://stackoverflow.com/comment/91038541
downvote count: 0
has comment: http://stackoverflow.com/comment/91039879
has comment: http://stackoverflow.com/comment/91055996
has comment: http://stackoverflow.com/comment/91039865
has comment: http://stackoverflow.com/comment/91030242
has comment: http://stackoverflow.com/comment/91039898
type: Answer
has body: From my understanding, a post is Liked if it exists in the Like model. Solution: from django import template # import `Like` model from path.to.models import Like register = template.Library() @register.simple_tag def isliked(post): if Like.objects.filter(post=post).exists(): return "Like" return "Unlike" You can then load it in the template: {% load isliked %}. And, then use it by passing an instance of Post model: {% isliked post %}.
has comment: http://stackoverflow.com/comment/91030016

http://stackoverflow.com/comment/91304638
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52094242
score: 1
has text: @Sharku edited question added my work with docx.

http://stackoverflow.com/comment/91012986
comment on: http://stackoverflow.com/q/52031203
has text: Can you add `print(fileB.__file__)` to `fileA.py` and confirm that the path of the `fileB` module is as expected? Maybe you're importing a different file by accident.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91005600
comment on: http://stackoverflow.com/q/52027687
has text: Can you show your full shell session? This shouldn't happen
type: QuestionComment
type: Comment
score: 2

http://stackoverflow.com/comment/91074179
type: AnswerComment
type: Comment
has text: Can you please change your answer to write to output file?
comment on: http://stackoverflow.com/a/52061896
score: 0

http://stackoverflow.com/comment/91007009
score: 0
type: Comment
has text: I guess we need to compile from source. That's the only option I didn't try.
comment on: http://stackoverflow.com/a/51994922
type: AnswerComment

http://stackoverflow.com/comment/91098668
type: Comment
comment on: http://stackoverflow.com/a/52059462
has text: I try to replace the c with B but error still there, can you recommend me the library like python3-wifi in python3?
type: AnswerComment
score: 0

http://stackoverflow.com/a/52087829
type: Answer
has body: Your code will work, with a few syntax corrections: comp = 'rock' user = 'rock' if comp == 'rock': print('I win *_*!') elif user == 'paper': print('You win.') else: print('Tie.') All I've done here is change the second if to elif, and put parentheses around the print statement output. In Python, 'else if' is written 'elif'. You can have as many elif statements as you want.
answers question: http://stackoverflow.com/q/52087398
score: 0

http://stackoverflow.com/q/52002973
has body: I am trying to import pyautogui in visual studio but it's not recognising it. How to add python libraries in visual studio code? And is there a better text editor which I can use?
tagged with: python
tagged with: text
tagged with: editor
answer count: 0
tagged with: libraries
has title: How to install python 3rd party librarys in visual studio code?
type: Question
tagged with: visual-studio-code
has comment: http://stackoverflow.com/comment/91008169
has comment: http://stackoverflow.com/comment/90954995
score: 0
type: UnansweredQuestion

http://stackoverflow.com/comment/91047549
type: QuestionComment
type: Comment
score: 2
has text: It looks like you want us to write some code for you. While many users are willing to produce code for a coder in distress, they usually only help when the poster has already tried to solve the problem individually. A good way to show this effort is to include a [Minimal, complete, verifiable example](http://stackoverflow.com/help/mcve). Check the [intro tour](https://stackoverflow.com/tour) you finished before posting, especially [How to Ask](http://stackoverflow.com/help/how-to-ask).
comment on: http://stackoverflow.com/q/52048391

http://stackoverflow.com/comment/91299575
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52132523
type: Comment
has text: Thank you so much for the answer, it honestly sheds a lot of light on what I didn't know about Numba. When I ran the vectorized code on my machine, I saw my block size was set to 64 compared to your block size of 128 (For reference I am running a GTX 1080ti). Is there a limit on the card, or maybe there is a fix by changing a Nvidia setting or by adding some code? Secondly, regarding guvectorize, I have tried to slice the arrays along the second axis in an attempt to shorten times using

http://stackoverflow.com/comment/90965875
score: 0
has text: @greenapps Thank you. The problem was on python server.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52007455

http://stackoverflow.com/comment/90938697
type: AnswerComment
has text: i get :Traceback (most recent call last): File "python", line 6 else: ^ SyntaxError: invalid syntax
comment on: http://stackoverflow.com/a/51994367
type: Comment
score: 0

http://stackoverflow.com/comment/90937487
comment on: http://stackoverflow.com/a/51993853
score: 0
type: AnswerComment
type: Comment
has text: Ok, after using your code. My build responds with the following

http://stackoverflow.com/a/51992961
answers question: http://stackoverflow.com/q/51992879
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51992879
type: Answer
score: 1
upvote count: 1
has body: Untested, but instead of: for i, elem in enumerate(all_trs): inside_td = elem.find("td") if "NAICS" in inside_td.text: inside_td = elem.find("td") print(inside_td.text) Try this: for i, elem in enumerate(all_trs): td_elems = elem.findAll('td') if 'NAICS' in td_elems[0].text: print(td_elems[1].text) Explanation: The findAll method returns a list of td elements so, just get a handle on this sequence, and you can of course index it :) find_all(self, name=None, attrs={}, recursive=True, text=None, limit=None, **kwargs) Extracts a list of Tag objects that match the given criteria. You can specify the name of the Tag and any attributes you want the Tag to have. The find method returns only the first td element, equivalent to basically: findAll('td')[0] find(self, name=None, attrs={}, recursive=True, text=None, **kwargs) Return only the first child of this Tag matching the given criteria.

http://stackoverflow.com/a/51971010
type: Answer
answers question: http://stackoverflow.com/q/51970828
has body: You could iterate the list of lists students then assemble a dictionary to print the values. print_dict = {} for name, score in students: if score in print_dict: print_dict[score] += [name] else: print_dict[score] = [name] Once you have the dictionary of values to print you could print by iterating and sorting: for score, names in print_dict.items(): print score, ', '.join(sorted(names)) Out: 41 Akriti 37.2 Tina 37.21 Berry,Harry 39 Harsh
score: 0

http://stackoverflow.com/comment/91036617
type: Comment
type: QuestionComment
has text: Can you post what you tried and how you want the cells to look?
score: 0
comment on: http://stackoverflow.com/q/52042895

http://stackoverflow.com/comment/91056258
score: 0
has text: It is very annoying. However, OK
comment on: http://stackoverflow.com/q/51967989
type: QuestionComment
type: Comment

http://stackoverflow.com/a/52047571
answers question: http://stackoverflow.com/q/52047532
type: Answer
upvote count: 6
score: 6
has comment: http://stackoverflow.com/comment/91046153
has body: df.column.str.extract will produce a dataframe with one column per matched group in the regex, indexed by int position. Then you can use rename to rename the columns. &gt;&gt;&gt; df.VALUE.str.extract(r'([-]?[\d.]*)([\w\D]*)').rename(columns={0:'VALUE', 1:'UNIT'}) VALUE UNIT 0 -1.234 NS 1 0.22 MH
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52047532

http://stackoverflow.com/q/52046333
type: Question
has body: I am learning statistics and Python from this book called ThinkStats. It has instructions on how to download the code and solve the exercises. I did everything that was told but am still not able to run the code on jupyter notebook. I am not sure what I am missing. Can someone please help me? Here is a list of instructions in the book and the things I did till now. "After you clone the repository or unzip the zip file, you should have a folder called ThinkStats2/code with a file called nsfg.py. If you run nsfg.py, it should read a data file, run some tests, and print a message like, “All tests passed.” If you get import errors, it probably means there are packages you need to install." Till now I downloaded the zip file, unzipped it and got the file named nsfg.py. I opened the file in jupyter notebook, but I am getting an error called" cannot find module thinkstats2". This module is specific to the book and from what I understand, the module is in the Thinkstats2 directory. How do I make jupyter notebbok run the file in the ThinkStats 2 directory?
tagged with: statistics
upvote count: 1
answer count: 1
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/52047390
type: UnansweredQuestion
tagged with: python
has title: Error running exercises from ThinkStats on Jupyter Notebook
downvote count: 0
score: 1

http://stackoverflow.com/comment/91153594
type: QuestionComment
has text: There's an important distinction between applying a function to each element of an array, and applying the function to subarrays (slices) along one or another axis. If working with every element, the problem isn't inherently multidimensional; with `ravel` and `reshape` you can cast it as a 1d problem.
score: 0
comment on: http://stackoverflow.com/q/52098465
type: Comment

http://stackoverflow.com/comment/91186942
has text: Thanks for the help.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52106903

http://stackoverflow.com/comment/91049732
has text: You misunderstood me. I'm not saying that you can't pass a docstring as a parameter. I'm saying you can't write your argument, then type in a docstring next to it to do a "comment block" if you will. In some languages, you could do foo(arg1, arg2 /*This does bar*/, arg3). Attempting to do foo(arg1, arg2"""this does bar""", arg3) causes a SyntaxError. You totally can pass a docstring, it'll just be treated as a regular string. But that isn't was the OP was asking.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52047431
type: AnswerComment

http://stackoverflow.com/comment/90894455
type: Comment
comment on: http://stackoverflow.com/q/51971579
score: 0
type: QuestionComment
has text: probably more helpful as a question but less funny :D

http://stackoverflow.com/a/52007492
has comment: http://stackoverflow.com/comment/90965405
has comment: http://stackoverflow.com/comment/90965357
has comment: http://stackoverflow.com/comment/90965487
upvote count: 2
has comment: http://stackoverflow.com/comment/90965619
type: Answer
accepted answer of: http://stackoverflow.com/q/52007431
answers question: http://stackoverflow.com/q/52007431
score: 2
has body: Use the pattern: ^Tue.*?2018 ^ Assert position beginning of line. Tue Literal substring. .*? Match anything lazily. 2018 Match literal substring. Since you are working with a multiline string and you want to match pattern at the beginning of a string, you have to use the re.MULTILINE flag. import re mystr=""" Tue Aug 21 17:02:26 2018 (gtgrhrthrhrhrthhhthrthrhrh) fjfpjpgporejpejgjr[eh[[[jh[j[ej[[ej[ej[e]]]] fkw[kgkeg[ekrk[ekg[kergk[erkg[eg[kg] Tue Aug 21 17:31:06 2018 ( ijwejfwfjwpfjwf[[few[jjfwfefwfeffeww]] fiowhfiweohewhfpwfhpfhpepwehfphpwhfpehfpwfh f,wfpewfefewgpwpg,pewgp Tue Aug 21 18:10:42 2018 ( reijpjfpjejferjfrejfpjefjer k[pfk[epkf[kr[ek[ke[gkk] r[g[keprkgpekg[rkg[pkg[ekg] """ print(re.findall(r'^Tue.*?2018',mystr,re.MULTILINE)) Prints: ['Tue Aug 21 17:02:26 2018', 'Tue Aug 21 17:31:06 2018', 'Tue Aug 21 18:10:42 2018']
has comment: http://stackoverflow.com/comment/90965434
has comment: http://stackoverflow.com/comment/90965435
has comment: http://stackoverflow.com/comment/91013317
has comment: http://stackoverflow.com/comment/90965499
downvote count: 0
has comment: http://stackoverflow.com/comment/90965537
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/90965406

osx-elcapitan
tag name: osx-elcapitan
type: Tag
tags question: http://stackoverflow.com/q/51971477

http://stackoverflow.com/a/52031165
accepted answer of: http://stackoverflow.com/q/52031127
upvote count: 2
has body: You need to read as lines of text. Otherwise the delimiter is wrong df = spark.read.text("hdfs:////data/stn") And then parse df = df.select( df.value.substr(1, 11).alias('id'), df.value.substr(13, 20).alias('LATITUDE'), df.value.substr(22, 30).alias('LONGITUDE'), df.value.substr(32, 37).alias('c3'), df.value.substr(39, 40).alias('c4'), df.value.substr(42, 71).alias('c5'), df.value.substr(73, 75).alias('c6'), df.value.substr(77, 79).alias('c7'), df.value.substr(81, 85).alias('c8')) df.show(3)
score: 2
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/52031127
type: Answer

http://stackoverflow.com/a/52004505
type: AcceptedAnswer
score: 1
accepted answer of: http://stackoverflow.com/q/52001753
answers question: http://stackoverflow.com/q/52001753
type: Answer
upvote count: 1
has body: The simplest way is to create a download link from that blob and manually run a Python script on the downloaded image. I assume that instead you want to display the classification result in the same web page. For this you have to make an XMLHttpRequest to a Python web server, which will then process the image and send the the classification back to the browser. See Sending and Receiving Binary Data (MDN) for how to create such a request. If you don't already have a web server I suggest you look at Flask or Tornado. But this is not the place to explain this all, and good tutorials do exist. If this answer doesn't help I suggest to make a more specific question. Tell us what problem you are trying to solve (instead of just the solution you think you need), and tell us where you think this Python program should be running, or if you already have it running and know how it can receive/decode the image, what you have already tried or read.
downvote count: 0

http://stackoverflow.com/q/52096829
has title: VBO PyOpenGL Points
has answer: http://stackoverflow.com/a/52097105
answer count: 1
downvote count: 0
score: 1
favorite count: 0
tagged with: vbo
tagged with: vao
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/52097105
upvote count: 1
tagged with: pyopengl
type: Question
has body: I'm working with PyOpenGL and GLUT at the moment and just want to visualize some points on the screen with VBO. I'm pretty new to programming with PyOpenGL, so maybe the code isn't good at all. But should work in my opinion. But I always get just one point. Anyone an idea, why? Thanks for helping!! import sys import random #for random numbers from OpenGL.GL import * #for definition of points from OpenGL.GLU import * from OpenGL.GLUT import * #for visualization in a window import numpy as np AMOUNT = 10 DIMENSION = 3 def changePoints(points): for i in range(0, 3*AMOUNT): x = random.uniform(-1.0, 1.0) points[i]= points[i]*x print(points) return points def displayPoints(points): vbo=GLuint(0) # init the Buffer in Python! glGenBuffers(1, vbo) # generate a buffer for the vertices glBindBuffer(GL_ARRAY_BUFFER, vbo) #bind the vertex buffer glBufferData(GL_ARRAY_BUFFER,sys.getsizeof(points), points, GL_STREAM_DRAW) glBindBuffer(GL_ARRAY_BUFFER, vbo) #bind the vertex buffer glEnableClientState(GL_VERTEX_ARRAY) # enable Vertex Array glVertexPointer(DIMENSION, GL_FLOAT,0, ctypes.cast(0, ctypes.c_void_p)) glBindBuffer(GL_ARRAY_BUFFER, vbo) #bind the vertex buffer glDrawArrays(GL_POINTS, 0, AMOUNT) glDisableClientState(GL_VERTEX_ARRAY) # disable the Vertex Array glDeleteBuffers(1, vbo) ##creates Points def Point(): points = np.arange(AMOUNT*3) np.ascontiguousarray(points, dtype = np.float32) points = changePoints(points) #Visualization displayPoints(points) ##clears the color and depth Buffer, call Point() and swap the buffers of the current window def display(): glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) Point() glutSwapBuffers() def main(): ##initials GLUT glutInit(sys.argv) #sets the initial display mode (selects a RGBA mode window; selects a double buffered window; selects a window with a depth buffer) glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE | GLUT_DEPTH) #defines the size of the Window glutInitWindowSize(800, 1600) #creates a window with title glutCreateWindow(b'…
tagged with: glut

http://stackoverflow.com/comment/90949645
type: AnswerComment
comment on: http://stackoverflow.com/a/52000273
score: 0
type: Comment
has text: So, if I do something like `os.path.exists("/home/myProject/testFolder/")`, it should be O(1) ?

http://stackoverflow.com/comment/92070592
type: QuestionComment
comment on: http://stackoverflow.com/q/52001964
has text: @Dalen I want to perform both the tasks together find the mappings and also remove those elements from entities_list whose mapping are not found and return both the list what is the best optimal way to perform this kindly tell me with coding example TIA!
score: 0
type: Comment

http://stackoverflow.com/comment/90959862
score: 0
type: Comment
type: QuestionComment
has text: Maybe only one of them has the lock on the log file, the others can not access it, that's why you only see the first one. Maybe they run In reverse order and you only see the last one. Are all of them writing to the same file? Try changing the log file to be specific to each test.
comment on: http://stackoverflow.com/q/52005076

http://stackoverflow.com/comment/91056492
has text: This solution successfully keeps the label intact, however, the push-btn gets overlapped on top of the label. How do I keep the two apart?
score: 0
comment on: http://stackoverflow.com/a/52052029
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/91160976
score: 0
type: AnswerComment
type: Comment
has text: @WillNess Yes, it was fun. As for the dot, this can easily be replaced by `\cdot{}` or `\times{}`.
comment on: http://stackoverflow.com/a/52094135

http://stackoverflow.com/comment/95361778
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52097168
type: Comment
has text: I guess it probably isn't and I've been over looking it maybe . Is there a way to cast it as such, so I can check if this is the issue ?

http://stackoverflow.com/comment/91052764
comment on: http://stackoverflow.com/a/52048660
type: AnswerComment
has text: I got one is `https://smtgvs.weathernews.jp/s/topics/img/201807/201807300285_sns_img_A.jpg?1532940869"> <meta name="twitter:image" content="https://smtgs.weathernews.jp/s/topics/img/201807/201807300285_sns_img_A.jpg?1532940869`, how can I only get `https://smtgvs.weathernews.jp/s/topics/img/201807/201807300285_sns_img_A.jpg`?
score: 0
type: Comment

http://stackoverflow.com/q/52045496
type: Question
has answer: http://stackoverflow.com/a/52047651
tagged with: python-rq
answer count: 1
downvote count: 0
favorite count: 0
tagged with: redis
type: UnansweredQuestion
tagged with: python
score: 2
has body: I have two kinds of jobs: ones that I want to run in serial and ones that I want to run concurrently in parallel. However I want the parallel jobs to get scheduled in serial (if you're still following). That is: Do A. Wait for A, do B. Wait for B, do 2+ versions of C all concurrently. My thought it to have 2 redis queues, a serial_queue that has just one worker on it. And a parallel_queue which has multiple workers on it. serial_queue.schedule( scheduled_time=datetime.utcnow(), func=job_a, ...) serial_queue.schedule( scheduled_time=datetime.utcnow(), func=job_b, ...) def parallel_c(): for task in range(args.n_tasks): queue_concurrent.schedule( scheduled_time=datetime.utcnow(), func=job_c, ...) serial_queue.schedule( scheduled_time=datetime.utcnow(), func=parallel_c, ...) But this setup currently, gives the error that AttributeError: module '__main__' has no attribute 'schedule_fetch_tweets' . How can I package this function properly for python-rq?
upvote count: 2
has title: Schedule a redis job that schedules another redis job with python-rq

http://stackoverflow.com/a/52055967
answers question: http://stackoverflow.com/q/52054905
has body: I think you're looking to do something like this, with date ranges: from webapp.models import Information start_of_day_date = ... now_date ... p = Information.objects.filter( dat__range=(start_of_day_date, now_date), ) for i in p: print(p) For a good explanation on how to set start_of_day_date and now_date, see this post: Determine start and end time of current day (UTC -&gt; EST -&gt; UTC) ; Python Good luck!
type: Answer
upvote count: 1
has comment: http://stackoverflow.com/comment/91074534
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/91068729
downvote count: 0
has comment: http://stackoverflow.com/comment/91068798
accepted answer of: http://stackoverflow.com/q/52054905
score: 1
has comment: http://stackoverflow.com/comment/91076326

http://stackoverflow.com/a/52711081
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52108417
score: 10
answers question: http://stackoverflow.com/q/52108417
type: AcceptedAnswer
has body: This blog post mentioned in the comments above contains an incredibly fast vectorized function for cross-correlation, covariance, and regression for multi-dimensional data in Python. It produces all of the regression outputs I need, and does so in milliseconds as it relies entirely on simple vectorised array operations in xarray. May 2024 update: I've updated the function to ensure it function correctly accounts for different numbers of NaN values in each pixel, and to correctly calculate P-values for different alternative hypotheses (thanks big-zhao!): def xr_regression(x, y, lag_x=0, lag_y=0, dim="time", alternative="two-sided"): """ Takes two xr.Datarrays of any dimensions (input data could be a 1D time series, or for example, have three dimensions e.g. time, lat, lon), and returns covariance, correlation, coefficient of determination, regression slope, intercept, p-value and standard error, and number of valid observations (n) between the two datasets along their aligned first dimension. Datasets can be provided in any order, but note that the regression slope and intercept will be calculated for y with respect to x. Inspired by: https://hrishichandanpurkar.blogspot.com/2017/09/vectorized-functions-for-correlation.html Parameters ---------- x, y : xarray DataArray Two xarray DataArrays with any number of dimensions, both sharing the same first dimension lag_x, lag_y : int, optional Optional integers giving lag values to assign to either of the data, with lagx shifting x, and lagy shifting y with the specified lag amount. dim : str, optional An optional string giving the name of the dimension on which to align (and optionally lag) datasets. The default is 'time'. alternative : string, optional Defines the alternative hypothesis. Default is 'two-sided'. The following options are available: * 'two-sided': slope of the regression line is nonzero * 'less': slope of the regression line is less than zero * 'greater': slope of the regression line is greater than zero Re…
upvote count: 10
type: Answer

http://stackoverflow.com/a/52106497
has comment: http://stackoverflow.com/comment/94443594
type: Answer
upvote count: 4
has comment: http://stackoverflow.com/comment/91164023
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52105707
has comment: http://stackoverflow.com/comment/126823377
has body: My personal take is that input() function should be avoided at all costs when learning python: (a) it diverts you from structuring code in a modular way, (b) it is rarely used to applications - the interfaces are usually command line arguments or direct function calls. The code you supply is a bit hard to follow, even though I appreciate it is linked to COBOL style and culture. The best thing to do is to devise your problem into smaller subtasks and test how they work in separation. This way you will know where your problem is, and it would be easier to focus your question (and attention of people answering). My understanding is that the core idea of your script is calculating monthly payments and loan amortisation. Consider following code: # FIXME: missing compound interest def perdiem(amount, rate): return (amount * rate) / 365 def days_per_month(month, year): if month in [1, 3, 5, 7, 8, 10, 12]: return 31 elif month in [4, 6, 9, 11]: return 30 elif month == 2: if (year % 4) == 0: return 29 else: return 28 else: raise ValueError('month expected', month) def next_month(month, year): if month == 12: next_month = 1 next_year = year + 1 else: next_month = month + 1 next_year = year return next_month, next_year def monthly_interest(principal, days, rate): return perdiem(principal, rate) * days def monthly_principal(monthly_payment, current_interest_payment): return monthly_payment - current_interest_payment def yield_expected_payment_schedule(start_year, start_month, initial_amount, rate, duration_in_years, monthly_payment): year = start_year month = start_month amount = initial_amount for t in range(duration_in_years * 12 + 1): days = days_per_month(month, year) interest_due = monthly_interest(amount, days, rate) if amount &gt; 0: yield {'balance at month start': amount, 'interest due': monthly_interest(amount, days, rate), 'year': year, 'month': month } amount = amount - (monthly_payment - interest_due) month, year = next_month(month, year) if __name__ == '__main__':…
answers question: http://stackoverflow.com/q/52105707
type: AcceptedAnswer
score: 4

http://stackoverflow.com/comment/91076326
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52055967
type: AnswerComment
has text: in [28]: p = information.objects.filter( dat__range=(datetime.date(2018, 8, 22), datetime.date(2018, 8, 28)), ) In [29]: p Out[29]: <QuerySet []> --- is that any mistake in configuring the modules.py. I will make uplaod the modules.py in the question. could you please tell me what is worng.. thanks

http://stackoverflow.com/q/52016192
has comment: http://stackoverflow.com/comment/90982550
has comment: http://stackoverflow.com/comment/90982521
has answer: http://stackoverflow.com/a/52016447
upvote count: 3
answer count: 3
has comment: http://stackoverflow.com/comment/90982581
has title: Python3 check digit algorithm
possible better answer: http://stackoverflow.com/a/52016447
tagged with: algorithm
tagged with: check-digit
has body: I'm learning to wrap my head around programming and have been given the following task: The ISBN (International Standard Book Number) is made out of 10 digits. z1z2z3z4z5z6z7z8z9z10 The last digit z10 is a check-digit. It's made like this: First, you create a kind of cross-sum with this formula: s = 1 * z1 + 2 * z2 + 3 * z3 + 4 * z4 + 5 * z5 + 6 * z6 + 7 * z7 + 8 * z8 + 9 * z9 The check-digit z10 is the remainder of the integer division of s divided by 11. For the remainder 10 you write x or X. Example: For the ISBN 3826604237 you get the check-digit 7. Calculation: 1*3+2*8+3*2+4*6+5*6+6*0+7*4+8*2+9*3 = 150 The remainder of the division of 150 and 11 is 7. The code-solution given is as followed: # isbn.py number = int(input("Please enter a 9-digit number: ")) z9 = number % 10 number = number//10 z8 = number % 10 number = number//10 z7 = number % 10 number = number//10 z6 = number % 10 number = number//10 z5 = number % 10 number = number//10 z4 = number % 10 number = number//10 z3 = number % 10 number = number//10 z2 = number % 10 number = number//10 z1 = number sum = z1+2*z2+3*z3+4*z4+5*z5+6*z6+7*z7+8*z8+9*z9 checkdigit = sum%11 print("\nCheckdigit:", checkdigit) My question simply is: How does it work? Why do I have to calculate "number // 10" and "number % 10" and this all the time? Is there a name for this kind of algorithm, and if so, how is it called? I'd appreciate any kind of answer for this and if it seems like the easiest thing for you and you feel like I'm wasting your time, I'm sorry. So far I understood pretty much anything I've learned thus far learning python, but this task seemed a bit hard (it was in a very early chapter of the book I'm studying on work) and I got stuck and didn't get this out of my head. Thank you in advance and have a nice day!
has comment: http://stackoverflow.com/comment/90982768
has answer: http://stackoverflow.com/a/52016389
downvote count: 4
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90982745
has comment: http://stackoverflow.com/comment/90982721
has comment: http://stackoverflow.com/comment/90982692
favorite count: 0
has answer: http://stackoverflow.com/a/52016456
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/90982563
type: Question
tagged with: python
accepted answer: http://stackoverflow.com/a/52016389
score: -1

http://stackoverflow.com/a/51989736
has comment: http://stackoverflow.com/comment/90941644
answers question: http://stackoverflow.com/q/51989384
has comment: http://stackoverflow.com/comment/91079875
has comment: http://stackoverflow.com/comment/90929133
has body: There is an issue with the threading logic of your program. You should move the while(True) loops to the thread workers, and only start your threads once. As it stands, your code can only send/receive one message every 10 seconds. Server: import socket import threading def get(s): while True: tm = s.recv(1024) print("\nReceived: ",tm.decode('ascii')) def set_(s): while True: i=input("\nEnter : ") s.send(i.encode('ascii')) serversocket = socket.socket() host = socket.gethostname() port = 9981 serversocket.bind((host,port)) serversocket.listen(1) clientsocket,addr = serversocket.accept() t1=threading.Thread( target = get , args = (clientsocket,) ) t1.start() t2=threading.Thread( target = set_ , args = (clientsocket,) ) t2.start() Client: import socket import threading def get(s): while True: tm = s.recv(1024) print("\nReceived: ",tm.decode('ascii')) def set_(s): while True: i=input("\nEnter : ") s.send(i.encode('ascii')) s = socket.socket() host = socket.gethostname() port = 9981 s.connect((host,port)) t1=threading.Thread( target = get , args = (s,) ) t2=threading.Thread( target = set_ , args = (s,) ) t1.start() t2.start() You'll need to handle closing the sockets differently, and the enter/received prints get out of sync after the first message due to the multithreaded nature of the program, but the input is still waiting.
score: 4
has comment: http://stackoverflow.com/comment/90929180
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/91115023
upvote count: 4

http://stackoverflow.com/q/52053792
tagged with: http://stackoverflow.com/tag/json
has comment: http://stackoverflow.com/comment/91097951
downvote count: 1
type: Question
upvote count: 0
answer count: 1
tagged with: python-2.7
score: -1
favorite count: 0
tagged with: python-3.x
has body: I have have a table in a database, one column of which includes some JSON. In each row the individual JSON will be slightly different. Each will include some of the attributes of the JSON, but none will include them all. For example { "testAssignmentName": "RhubarbRhubarbRhubarbRhubarbRhubarbRhubarbRhubarbRhubarb" } and { "testSkill": { "testProfileId": 72, "educationalLevelId": 11 }, "primaryPooltrial": { "mainTestSkill": { "testSkill": { "testProfileId": 72, "educationalLevelId": 11 }, "trialDefinition": { "trial": 99.0, "trialFrequencyId": 1 } }, "additionalTestSkills": [], "results": [{ "resultTypeId": 4, "resultAmount": 20.0, "resultFrequencyId": 2 } ] } } and { "requirements": "RhubarbRhubarbRhubarbRhubarbRhubarbRhubarbRhubarbRhubarb" } and { "requirements": "RhubarbRhubarbRhubarbRhubarbRhubarbRhubarbRhubarbRhubarb", "testSkill": { "testProfileId": 21, "educationalLevelId": 17 }, "primaryPooltrial": { "mainTestSkill": { "testSkill": { "testProfileId": 21, "educationalLevelId": 17 } }, "results": [] } } and { "testAssignmentName": "Rhubarb Rhubarb Rhubarb Rhubarb Rhubarb Rhubarb ", "requirements": "RhubarbRhubarbRhubarbRhubarbRhubarbRhubarbRhubarb" } Is there one piece of code that will allow me to extract the overall structure so I can parse the JSON without missing any of the attributes in a later part of the code? Thanks
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/52054184
tagged with: python
has comment: http://stackoverflow.com/comment/91057813
has title: Determine JSON Structure with Python

http://stackoverflow.com/comment/91192280
has text: InvalidURI at /marblesapp/testing/ ParseResult(scheme='https', netloc='rinkeby.infura.io', path='/xxxxxxxxxxxxxxx', params='', query='', fragment='') isn't a valid URI
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/52105828
type: Comment

http://stackoverflow.com/comment/90938011
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51973307
type: Comment
has text: Thanks Matt, I'm gonna try this so I'll have it in the toolbox.

python-2.7
tags question: http://stackoverflow.com/q/52072784
tags question: http://stackoverflow.com/q/52022266
tags question: http://stackoverflow.com/q/52053590
tags question: http://stackoverflow.com/q/52029918
tags question: http://stackoverflow.com/q/52095897
tags question: http://stackoverflow.com/q/52046446
tags question: http://stackoverflow.com/q/52079774
tags question: http://stackoverflow.com/q/52092078
tags question: http://stackoverflow.com/q/52058846
tags question: http://stackoverflow.com/q/52111328
tags question: http://stackoverflow.com/q/52017724
tags question: http://stackoverflow.com/q/52021989
tags question: http://stackoverflow.com/q/52100734
tags question: http://stackoverflow.com/q/51975342
tags question: http://stackoverflow.com/q/52056572
tags question: http://stackoverflow.com/q/51982456
tags question: http://stackoverflow.com/q/52106616
tags question: http://stackoverflow.com/q/51996718
tags question: http://stackoverflow.com/q/52109055
tags question: http://stackoverflow.com/q/52053884
tags question: http://stackoverflow.com/q/52078738
tags question: http://stackoverflow.com/q/52061688
tags question: http://stackoverflow.com/q/52083986
tags question: http://stackoverflow.com/q/51982898
tags question: http://stackoverflow.com/q/52095282
tags question: http://stackoverflow.com/q/51978612
tags question: http://stackoverflow.com/q/51981089
tags question: http://stackoverflow.com/q/52085921
tags question: http://stackoverflow.com/q/52079081
tags question: http://stackoverflow.com/q/52045325
tags question: http://stackoverflow.com/q/51972554
tags question: http://stackoverflow.com/q/52050527
tags question: http://stackoverflow.com/q/52067847
tags question: http://stackoverflow.com/q/52048849
tags question: http://stackoverflow.com/q/52090461
tags question: http://stackoverflow.com/q/52053792
tags question: http://stackoverflow.com/q/51980540
tags question: http://stackoverflow.com/q/52047425
tags question: http://stackoverflow.com/q/52090959
tags question: http://stackoverflow.com/q/52031324
tags question: http://stackoverflow.com/q/52050149
tags question: http://stackoverflow.com/q/52074329
tags question: http://stackoverflow.com/q/51994368
tags question: http://stackoverflow.com/q/52109153
tags question: http://stackoverflow.com/q/52014473
tags question: http://stackoverflow.com/q/52048291
tags question: http://stackoverflow.com/q/51997542
tags question: http://stackoverflow.com/q/52008622
tags question: http://stackoverflow.com/q/52023783
tags question: http://stackoverflow.com/q/52004433
tags question: http://stackoverflow.com/q/51980503
tags question: http://stackoverflow.com/q/51998100
tags question: http://stackoverflow.com/q/52061214
tags question: http://stackoverflow.com/q/52022178
tags question: http://stackoverflow.com/q/51959179
tags question: http://stackoverflow.com/q/52091844
tags question: http://stackoverflow.com/q/52072381
tags question: http://stackoverflow.com/q/52041076
tags question: http://stackoverflow.com/q/52010060
tags question: http://stackoverflow.com/q/52097896
tags question: http://stackoverflow.com/q/52089202
tags question: http://stackoverflow.com/q/52025193
tags question: http://stackoverflow.com/q/51966866
tags question: http://stackoverflow.com/q/52090952
tags question: http://stackoverflow.com/q/52029529
tags question: http://stackoverflow.com/q/52000891
tags question: http://stackoverflow.com/q/51958496
tags question: http://stackoverflow.com/q/51977320
tags question: http://stackoverflow.com/q/52029037
tags question: http://stackoverflow.com/q/51973611
tags question: http://stackoverflow.com/q/51993884
tags question: http://stackoverflow.com/q/52079229
tags question: http://stackoverflow.com/q/52079640
tags question: http://stackoverflow.com/q/52027330
tags question: http://stackoverflow.com/q/52046552
tags question: http://stackoverflow.com/q/52058007
tags question: http://stackoverflow.com/q/52054353
tags question: http://stackoverflow.com/q/51970356
tags question: http://stackoverflow.com/q/52096844
tags question: http://stackoverflow.com/q/52049467

http://stackoverflow.com/a/51994367
type: Answer
has comment: http://stackoverflow.com/comment/90938610
answers question: http://stackoverflow.com/q/51994328
has comment: http://stackoverflow.com/comment/90938852
has comment: http://stackoverflow.com/comment/90938458
has comment: http://stackoverflow.com/comment/90938533
has comment: http://stackoverflow.com/comment/90938948
has comment: http://stackoverflow.com/comment/90938638
has comment: http://stackoverflow.com/comment/90938697
score: 0
has body: Your indentaion is off, everything to be done for else needs to be on the same indentation level. Idented by two " ": else: print(" ") only one " ": time.sleep(1) Also, do your importing once at the start of the code, not repeatedly. # start of program import time

http://stackoverflow.com/q/52096260
has answer: http://stackoverflow.com/a/52096342
accepted answer: http://stackoverflow.com/a/52096342
tagged with: python
has body: I am developing an data extractor using regular expression in python. I stuck somewhere my other code is running in which I created in regex but the this code which is mentioned below: regex code: regexCode='^about_company:\n[\s\S]+?[A-Z]:' The above code is not working properly when I run in python I think , I made a mistake because the regex code is running properly here Expected output: The output should look like this is terminal of pycharm sorry for links,I cannot put the pics directly because of reputation issues Python Code: import re filename = open('textFile.txt','r') rege = '^about_company:[\s\S]+?[A-Z]:|ABOUT COMPANY:[\s\S]+?[A-Z]:' for data in filename: matches = re.findall(rege, data, re.MULTILINE) if matches: print(matches) When I tried to print the data by storing the data into text then it worked but when I tried to read the data from the file it shows the empty lists. Text file is same as in the regex101's link. I need solution of this please please help
type: AnsweredQuestion
has title: Need to get the expected output in python(Problem explained in description)
downvote count: 1
type: Question
score: 0
upvote count: 1
answer count: 1
tagged with: regex
favorite count: 0
tagged with: python-3.x

http://stackoverflow.com/comment/91026352
comment on: http://stackoverflow.com/a/52037555
score: 0
type: AnswerComment
type: Comment
has text: Although it is a good answer, someting must be wrong with the labels. The labels are not working fine, it does not match the proper range.

http://stackoverflow.com/q/51976665
type: AnsweredQuestion
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/90903494
type: Question
has comment: http://stackoverflow.com/comment/90903606
linked to: http://stackoverflow.com/q/1263451
has comment: http://stackoverflow.com/comment/90904111
accepted answer: http://stackoverflow.com/a/51976897
has comment: http://stackoverflow.com/comment/90903555
answer count: 2
tagged with: class-method
downvote count: 0
has answer: http://stackoverflow.com/a/51976824
tagged with: decorator
has comment: http://stackoverflow.com/comment/90903595
has body: I am new to decorators and believe I understand their purpose/the general gist of them for the most part. Unfortunately, I am having some issues with this decorator and its usage in a class. I am trying to populate a dictionary _profile_dict = {} with a new key created by profile + str(&lt;counter value&gt;). I'd rather not instantiate the class and set it to a variable in my if __name__ == '__main' statement so I am trying to execute the class with the create_profiles function. Here is my code, _profile_dict = {} class Profile: def __init__(self): self.first_name = input('first name: ') self.last_name = input('last name: ') self.email = input('email: ') self.address1 = input('primary address: ') self.address2 = input('secondary address: ') self.city = input('city: ') self.country = input('country: ') self.province = input('province: ') self.zip = input('zip: ') self.phone = input('phone number:') self.cc_name = input('Name on credit card: ') self.cc_num = input('Credit card number: ') self.exp_month = input('card expiration month: ') self.exp_year = input('card expiration year: ') self.cvv = input('cvv: ') self.json_obj = {"utf8": "✓", "_method": "", "authenticity_token": "", "previous_step": "", "checkout[email]": self.email, "checkout[buyer_accepts_marketing]": 1, "checkout[shipping_address][first_name]": self.first_name, "checkout[shipping_address][last_name]": self.last_name, "checkout[shipping_address][address1]": self.address1, "checkout[shipping_address][address2]": self.address2, "checkout[shipping_address][city]": self.city, "checkout[shipping_address][country]": self.country, "checkout[shipping_address][province]": self.province, "checkout[shipping_address][zip]": self.zip, "checkout[shipping_address][phone]": self.phone, "step": ""} def counter(self, func): def wrapper(): wrapper.counter += 1 return func(wrapper.counter) wrapper.counter = 0 return wrapper @counter def _populate_profile_dict(self, count): profile = 'profile' _profile_dict[profile + str(co…
has comment: http://stackoverflow.com/comment/90904232
favorite count: 0
possible better answer: http://stackoverflow.com/a/51976824
tagged with: python
has title: how can I make these counter decorator work for my in class method
has answer: http://stackoverflow.com/a/51976897

http://stackoverflow.com/comment/91078691
comment on: http://stackoverflow.com/q/52064141
type: Comment
type: QuestionComment
has text: Are those values in a list?
score: 0

http://stackoverflow.com/q/51957369
has body: I am new to Python and it's workings. I am wanting to simply create a variable called 'code' and fill this variable with the method i have made. Here is the code codeLength = 4 code = GenerateCode() print(code) def GenerateCode(code): symbols = ['A', 'B', 'C', 'D', 'E', 'F'] random.shuffle(symbols) del symbols[(symbols.count - codeLength)] code = symbols return code So the method should pick 4 letters from the array symbols be randomising it then removing 2. I want the letters at the end to be the variable 'code' Thanks
type: Question
has title: Set variable by running a function
score: 0
answer count: 1
has answer: http://stackoverflow.com/a/51957464
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/90865290
has comment: http://stackoverflow.com/comment/90865393
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51957464
has comment: http://stackoverflow.com/comment/90866094
has comment: http://stackoverflow.com/comment/90865348

http://stackoverflow.com/comment/91035706
score: 1
type: AnswerComment
has text: I like the generator approach for the short-circuiting, I think `np.where` adds unneeded overhead when `~(df.index < idx)` could be used.
comment on: http://stackoverflow.com/a/52042429
type: Comment

http://stackoverflow.com/comment/94900360
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/54032131
has text: Hey Tuyo, if you have an update or edit for your answer, you should put it in the actual answer, not a comment.

unicode
tags question: http://stackoverflow.com/q/52034523
tag name: unicode
type: Tag
tags question: http://stackoverflow.com/q/51957941
tags question: http://stackoverflow.com/q/52034621
tags question: http://stackoverflow.com/q/52027683
tags question: http://stackoverflow.com/q/52111328
tags question: http://stackoverflow.com/q/52106616
tags question: http://stackoverflow.com/q/52017226
tags question: http://stackoverflow.com/q/52101568
tags question: http://stackoverflow.com/q/51958906

http://stackoverflow.com/comment/91137869
has text: Thanks! It should act as another layer, 'cause it passes tensors. I don't understand "another layer". The comment when the author calls the defined function "predict" is "# prediction BEFORE-SOFTMAX of the model" (in the l2_attack.py). BTW, Class MNISTModel is defined in the "setup_mnist.py". The full code is at github "https://github.com/carlini/nn_robust_attacks".
score: 0
comment on: http://stackoverflow.com/a/52086256
type: AnswerComment
type: Comment

http://stackoverflow.com/a/52094518
has comment: http://stackoverflow.com/comment/91150785
has comment: http://stackoverflow.com/comment/91150146
type: AcceptedAnswer
downvote count: 0
has body: In my example, data is: df= pd.DataFrame({'name': {0: 'x', 1: 'x', 2: 'x', 3: 'y'}, 'time_cost': {0: '28800000, 250', 1: '39600000, 300', 2: '61200000, 250', 3: '72000000, 0'}}) Step 1. You can use something like this to get result: def split_function(n): return n.split(',') df['time_cost'] = df.time_cost.apply(split_function) Output: name time_cost 0 x [28800000, 250] 1 x [39600000, 300] 2 x [61200000, 250] 3 y [72000000, 0] Step 2. If you want two different columns in your DataFrame you can use: df.time_cost.apply(pd.Series) Output: 0 1 0 28800000 250 1 39600000 300 2 61200000 250 3 72000000 0 Step 3. And then join them: df = df.join(df.time_cost.apply(pd.Series)) Output: name time_cost 0 1 0 x [28800000, 250] 28800000 250 1 x [39600000, 300] 39600000 300 2 x [61200000, 250] 61200000 250 3 y [72000000, 0] 72000000 0 And then you can use drop to drop "time_cost" column and rename to rename new columns if you like. Is it what you want? I hope it will be helpful. UPD: Step 4. If you want grouped by name, you can use this: df[0] = df[0].astype(int) df[1] = df[1].astype(int) def concat_function_0(df): return np.array(df[0]) def concat_function_1(df): return np.array(df[1]) df = pd.DataFrame([df.groupby('name').apply(concat_function_1), df.groupby('name').apply(concat_function_0)]).T It isn't pythonic, but it works = ) Output: name 0 1 x [250, 300, 250] [28800000, 39600000, 61200000] y [0] [72000000] UPD: Step 5. For your result, after first step use this: def df_to_array(df): return list(df.time_cost) result = df.groupby('name').apply(df_to_array).values Output: [[['28800000', ' 250'], ['39600000', ' 300'], ['61200000', ' 250']] [['72000000', ' 0']]]
type: Answer
has comment: http://stackoverflow.com/comment/91149356
has comment: http://stackoverflow.com/comment/91150207
accepted answer of: http://stackoverflow.com/q/52086208
upvote count: 1
answers question: http://stackoverflow.com/q/52086208
score: 1

http://stackoverflow.com/q/52061699
has answer: http://stackoverflow.com/a/52061738
tagged with: pandas
answer count: 1
favorite count: 0
duplicate of: http://stackoverflow.com/q/49834883
tagged with: python
score: 2
type: AnsweredQuestion
downvote count: 0
linked to: http://stackoverflow.com/q/49834883
type: Question
accepted answer: http://stackoverflow.com/a/52061738
has title: Create a Pandas scatter plot, where one of the axes is the index
tagged with: matplotlib
has body: If I have a data frame, where I want to create a scatter plot of a column against the index, is there a way simpler than using matplotlib directly, or create a list out of the index, etc? Something like this: df.plot.scatter(x='index', y='price') I am assuming that this won't work, because an index might consist of multiple series and Pandas won't know which to draw upon, without further indication.
upvote count: 2

http://stackoverflow.com/q/52086726
has body: I am fairly new to Django and also JS/Jquery. I am trying to generate a pdf view of my HTML template, upon clicking the "Approve" Button. I have also written a js/jquery script within the same template to generatea pdf and instead I'm redirected to my homepage; just as I have defined it to do so in the corresponding view method. I'm wondering now why it does not run the js/jquery script and keeps referring to my view method and also what can I do to make it go through the script and convert the page to PDF and downloads it for the user, after hitting "Approve" Button. Many thanks for your smart comments ! My Template &lt;!DOCTYPE html&gt; {% load staticfiles %} &lt;html&gt; &lt;head&gt; &lt;meta charset="utf-8" /&gt; &lt;link rel="stylesheet" href="{% static 'css/quote_letter_est.css' %}"&gt; &lt;script src="https://code.jquery.com/jquery-1.12.3.min.js"&gt;&lt;/script&gt; &lt;script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/0.9.0rc1/jspdf.min.js"&gt; &lt;/script&gt; &lt;title&gt;Estimate Quote Letter&lt;/title&gt; &lt;script&gt; var doc = new jsPDF(); var specialElementHandlers = { '#editor': function (element, renderer) { return true; } }; $('#Approve').click(function () { doc.fromHTML($('#content').html(), 15, 15, { 'width': 170, 'elementHandlers': specialElementHandlers }); doc.save('sample-file.pdf'); }); &lt;/script&gt; &lt;/head&gt; &lt;div id="content"&gt; &lt;body bgcolor="#ffffff" border="1"&gt; &lt;form action="http://{{host}}:{{port}}/label/approve001" method="Get"&gt; {%csrf_token%} {% block content %} {% if cust_data %} {% for row in cust_data %} &lt;table id = "print-friendly" class="print-friendly" style="width:80%; cellspacing:0;"&gt; &lt;td colspan="8" align="left" valign="top" &gt;{{ row.contact_fname }}&amp;nbsp;{{ row.contact_lname }}&lt;br&gt;We trust that the following estimate meets with your approval and we look forward to working with you.&lt;br&gt;&lt;br&gt; &lt;/td&gt; &lt;th colspan="2" align="left" style="width:300px; height:25px…
type: Question
score: 0
has title: Django: The HTML template fails to be converted to PDF
answer count: 1
has answer: http://stackoverflow.com/a/52090220
tagged with: jquery
tagged with: python
tagged with: pdf-generation
accepted answer: http://stackoverflow.com/a/52090220
tagged with: django
has comment: http://stackoverflow.com/comment/91127486
type: AnsweredQuestion
tagged with: javascript

http://stackoverflow.com/comment/95388729
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52108586
has text: I'd imagine it'd be python 3.5, since it's default for Ubuntu. The problem is, it's still system-wide python. Also, your solution is not really a solution. You just call python executable with a full path, but you still don't use virtual environment. So to install pip package you will need to use full path for your pip as well. Like: `/home/ubuntu/anaconda3/envs/ijackweb/bin/pip3.6 install -r requirements.txt` which is the same as not using virtual environment at all.
score: 0

http://stackoverflow.com/comment/91075470
has text: My bad, sorry. There should be no `.strip()`
type: Comment
comment on: http://stackoverflow.com/a/52060277
score: 0
type: AnswerComment

http://stackoverflow.com/a/51994015
answers question: http://stackoverflow.com/q/51992098
has body: Some tips that may fix your problem. 1- Do feature extraction before creating tensorflow graph. For example, if you create TfIDF feature vector, you can do it in preprocess step and save numpy for input of the graph. input, label = feature_extractor(x, y) 2- Remove unnecessary session.run(). For example, when you call Optimizer it automatically call x_transformed. transformed_x = session.run(input) 3- Use tf.data (Dataset API) in a better way. It is unnecessary to call sess.run(next_element). Because next_element is part of your graph.
type: Answer
has comment: http://stackoverflow.com/comment/90944594
score: 0

http://stackoverflow.com/a/60524715
answers question: http://stackoverflow.com/q/52094320
score: 6
type: Answer
upvote count: 6
downvote count: 0
has body: The previous answer by LCT covers most of what should be said here, however I think it is possible to incorporate dask='parallelized' with multiple outputs like you get from scipy.stats.linregress. The trick here is to stack the multiple outputs into one array and then output that, you'll also have to use the output_core_dims kwarg to specify that the DataArray output from the apply_ufunc() call will have an extra dimension now: def new_linregress(x, y): # Wrapper around scipy linregress to use in apply_ufunc slope, intercept, r_value, p_value, std_err = stats.linregress(x, y) return np.array([slope, intercept, r_value, p_value, std_err]) # return a new DataArray stats = xr.apply_ufunc(new_linregress, ds[x], ds[y], input_core_dims=[['year'], ['year']], output_core_dims="parameter", vectorize=True, dask="parallelized", output_dtypes=['float64'], output_sizes={"parameter": 5}, ) N.B. This approach currently only works with dask='parallelized' if you have dask&lt;2.0, but it seems to work fine for multiple outputs if you have something else like dask='allowed'. Have a look at this Github issue for more detail. Hope it helps! Edit: I've been informed that the dask&lt;2.0 issue has been rectified as long as you have xarray&gt;=0.15.0 ! So can use dask='parallelized' now to speed things up. :)
has comment: http://stackoverflow.com/comment/109723453

http://stackoverflow.com/q/51962502
downvote count: 2
tagged with: pandas
has answer: http://stackoverflow.com/a/51962610
accepted answer: http://stackoverflow.com/a/51962610
answer count: 1
tagged with: scikit-learn
favorite count: 0
tagged with: python
type: AnsweredQuestion
upvote count: 0
has title: Initialize training set in Pandas with Python
type: Question
has comment: http://stackoverflow.com/comment/90875323
has body: I'm doing some research on Random Forests algorithm and build a classifier with the instruction from this post I have the following segment of code import pandas as pd import numpy as np # Import train_test_split function from sklearn.model_selection import train_test_split data=pd.DataFrame({ 'sepal length':iris.data[:,0], 'sepal width':iris.data[:,1], 'petal length':iris.data[:,2], 'petal width':iris.data[:,3], 'species':iris.target} X=data'sepal length', 'sepal width', 'petal length', 'petal width' # Features y=data['species'] # Labels # Split dataset into training set and test set X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3) # 70% training and 30% test I'm using iris dataset imported from sklearn. However, whenever I run this code I have the following error: File "&lt;ipython-input-11-71013f105652&gt;", line 12 X=data'sepal length', 'sepal width', 'petal length', 'petal width' # Features ^ SyntaxError: invalid syntax I think that this error is because of the fact that I have initialised X list which acted as Feature the wrong way. THE PROBLEM is that it was a typo in the code
score: -2

http://stackoverflow.com/q/52064831
has comment: http://stackoverflow.com/comment/91080191
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91080347
accepted answer: http://stackoverflow.com/a/52065018
possible better answer: http://stackoverflow.com/a/66546684
upvote count: 1
has answer: http://stackoverflow.com/a/66546684
type: Question
has comment: http://stackoverflow.com/comment/91080441
score: 1
has comment: http://stackoverflow.com/comment/91080243
has body: I have a .csv file with both string and integer - containing columns. I need to use numpy.loadtxt method to import the matrix formed from the specified columns. How can I do that? Right now I am trying to do the following: data = np.loadtxt(open(path_to_data, "rb"), delimiter=",", skiprows=1, usecols=[1:]) Basically trying to read all columns but first, but it is giving an error: SyntaxError: invalid syntax Because such syntax is not allowed: usecols=[1:]
tagged with: numpy
has comment: http://stackoverflow.com/comment/91080709
answer count: 2
downvote count: 0
has answer: http://stackoverflow.com/a/52065018
favorite count: 0
has comment: http://stackoverflow.com/comment/91080302
has title: numpy.loadtxt: load a range of columns

http://stackoverflow.com/comment/90922948
has text: Can we do the same thing in a simple manner. Not too complex and big as you've mentioned above @Vishvajit Pathak
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51980554

http://stackoverflow.com/comment/91009121
type: Comment
comment on: http://stackoverflow.com/a/52028667
type: AnswerComment
has text: Hmm, it's weird I'm I did everything you said but I keep on getting a 404 error even though the user does exist...
score: 0

http://stackoverflow.com/comment/91116835
has text: sure I will. I realised that i was not using the correct terms so will make it clearer next time.
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52080984

http://stackoverflow.com/comment/91160413
type: Comment
comment on: http://stackoverflow.com/a/52102944
type: AnswerComment
has text: @HackPy If you're trying to be efficient, I can tell you that the standard library is going be significantly slower than pandas at this task.
score: 0

http://stackoverflow.com/q/52094052
tagged with: python
has comment: http://stackoverflow.com/comment/91138164
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52094167
has title: Why is my nested for loop ending early? (python)
possible better answer: http://stackoverflow.com/a/52094167
type: Question
tagged with: nested-loops
has comment: http://stackoverflow.com/comment/91138419
linked to: http://stackoverflow.com/q/11364533
score: 0
answer count: 2
tagged with: for-loop
has answer: http://stackoverflow.com/a/52094106
accepted answer: http://stackoverflow.com/a/52094106
has body: first_name = input("Please enter your first name: ").capitalize() start_inner = int(input("Hi {}, please enter the start value for the inner loop: ".format(first_name))) end_inner = int(input("Please enter the end value for the inner loop: ")) start_outer = int(input("Please enter the start value for the outer loop: ")) end_outer = int(input("Please enter the end value for the outer loop: ")) for outer in range(start_outer, end_outer): for inner in range(start_inner, end_inner): print("{:^2} {:^2}".format(outer, inner)) If I were to put 1(start_inner), 3(end_inner), 1(start_outer), 2(end_outer) I should get: 1 1 1 2 1 3 2 1 2 2 2 3 Instead i get: 1 1 1 2 Any help is appreciated thanks.

http://stackoverflow.com/q/52037382
possible better answer: http://stackoverflow.com/a/52037433
has answer: http://stackoverflow.com/a/52043620
accepted answer: http://stackoverflow.com/a/52037459
has title: Beautiful soup module error(html parser)
downvote count: 0
score: 1
type: AnsweredQuestion
tagged with: http://stackoverflow.com/tag/html
favorite count: 0
tagged with: beautifulsoup
has comment: http://stackoverflow.com/comment/91025005
type: Question
answer count: 3
has answer: http://stackoverflow.com/a/52037459
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/52037433
has body: I use beautifulsoup to find the number of pages on a webpage however when I write my code: #!/usr/bin/env python # -*- coding: utf-8 -*- import urllib2 import requests import BeautifulSoup soup = BeautifulSoup(response.text) pages = soup.select('div.pagination a') a = int(pages[-2].text) print a It gives the following error: Traceback (most recent call last): File "C:/Users/HangaarLab/Desktop/sonartik/sonartik.py", line 13, in soup = BeautifulSoup(response.text) TypeError: 'module' object is not callable In another computer the code runs but it gives this warning: UserWarning: No parser was explicitly specified, so I'm using the best available HTML parser for this system ("html.parser"). This usually isn't a problem, but if you run this code on another system, or in a different virtual environment, it may use a different parser and behave differently.The code that caused this warning is on line 14 of the file C:/Users/Ar�elik/Desktop/sikayet/klo.py. To get rid of this warning, pass the additional argument 'features="html.parser"' to the BeautifulSoup constructor. I need the code to work in the computer that gives the first error. What should I do?

http://stackoverflow.com/q/51966498
has body: Question: Given DataFrame b, how can I replace the values of multiple columns, with one value, through boolean mask column identification? What works, but I don't want: b.iloc[:, 2:6] = "someConstantValue" What doesn't work, but I want: b.iloc[:, 2:6][b["columnA"] == "someCondition"]] = "someConstantValue" Thanks for your time!
tagged with: python
score: 2
type: AnsweredQuestion
upvote count: 2
type: Question
tagged with: indexing
has title: Pandas: Replace values of multiple columns using boolean masks
has answer: http://stackoverflow.com/a/51966513
tagged with: dataframe
possible better answer: http://stackoverflow.com/a/51966616
has answer: http://stackoverflow.com/a/51966616
answer count: 2
downvote count: 0
favorite count: 0
tagged with: pandas
accepted answer: http://stackoverflow.com/a/51966513

class
tags question: http://stackoverflow.com/q/52099692
tags question: http://stackoverflow.com/q/52090027
tags question: http://stackoverflow.com/q/52003818
tags question: http://stackoverflow.com/q/52045772
tags question: http://stackoverflow.com/q/52070098
tags question: http://stackoverflow.com/q/51980675
tags question: http://stackoverflow.com/q/52029457
tags question: http://stackoverflow.com/q/52011401
tags question: http://stackoverflow.com/q/51979302
tags question: http://stackoverflow.com/q/52059072
tags question: http://stackoverflow.com/q/52028235
tags question: http://stackoverflow.com/q/52093459
tags question: http://stackoverflow.com/q/52003643
tags question: http://stackoverflow.com/q/52026038
tags question: http://stackoverflow.com/q/52025639
tags question: http://stackoverflow.com/q/52081551
tags question: http://stackoverflow.com/q/52103181
tags question: http://stackoverflow.com/q/52015991
tags question: http://stackoverflow.com/q/52036357
tags question: http://stackoverflow.com/q/52019063
tags question: http://stackoverflow.com/q/52032139
tags question: http://stackoverflow.com/q/51969610
type: Tag
tags question: http://stackoverflow.com/q/51995423
tags question: http://stackoverflow.com/q/52005653
tags question: http://stackoverflow.com/q/51998940
tags question: http://stackoverflow.com/q/52020410
tag name: class
tags question: http://stackoverflow.com/q/52105186
tags question: http://stackoverflow.com/q/52043575
tags question: http://stackoverflow.com/q/52079895
tags question: http://stackoverflow.com/q/52048687
tags question: http://stackoverflow.com/q/52022790
tags question: http://stackoverflow.com/q/52110144
tags question: http://stackoverflow.com/q/52013486
tags question: http://stackoverflow.com/q/52009301
tags question: http://stackoverflow.com/q/52086900
tags question: http://stackoverflow.com/q/52010287
tags question: http://stackoverflow.com/q/52014619
tags question: http://stackoverflow.com/q/51980787
tags question: http://stackoverflow.com/q/52079399
tags question: http://stackoverflow.com/q/52013260
tags question: http://stackoverflow.com/q/52029320

http://stackoverflow.com/q/52103441
answer count: 2
has title: Summing multiple lists stored in dataframe
has body: I have a dataframe with multiple lists stored as: I have two dataframes as: df1.ix[1:3] DateTime Col1 Col2 2018-01-02 [1, 2] [11, 21] 2018-01-03 [3, 4] [31, 41] I want to sum the lists in the df1 to get: DateTime sumCol 2018-01-02 [12, 23] 2018-01-03 [34, 45] I tried numpy.sum(df1, axis=1) but that causes list concatenation instead of sum. Edit: My original dataframe has more than 2 columns.
downvote count: 0
favorite count: 0
accepted answer: http://stackoverflow.com/a/52103824
tagged with: pandas
possible better answer: http://stackoverflow.com/a/52103575
has answer: http://stackoverflow.com/a/52103575
tagged with: python-3.x
upvote count: 3
tagged with: python
type: AnsweredQuestion
score: 3
has answer: http://stackoverflow.com/a/52103824
tagged with: dataframe
type: Question

http://stackoverflow.com/q/52098116
favorite count: 0
score: 8
has title: gdb.execute blocks all the threads in python scripts
tagged with: multithreading
accepted answer: http://stackoverflow.com/a/52228186
tagged with: python
type: AnsweredQuestion
has body: I am scripting GDB with Python 2.7. I am simply stepping instructions with gdb.execute("stepi"). If the debugged program is idling and waiting for user interaction, gdb.execute("stepi") doesn't return. If there is such a situation, I want to stop the debugging session without terminating gdb. To do so, I create a thread that will kill the debugged process if the current instruction ran for more than x seconds: from ctypes import c_ulonglong, c_bool from os import kill from threading import Thread from time import sleep import signal # We need mutable primitives in order to update them in the thread it = c_ulonglong(0) # Instructions counter program_exited = c_bool(False) t = Thread(target=check_for_idle, args=(pid,it,program_exited)) t.start() while not program_exited.value: gdb.execute("si") # Step instruction it.value += 1 # Threaded function that will kill the loaded program if it's idling def check_for_idle(pid, it, program_exited): delta_max = 0.1 # Max delay between 2 instructions, seconds while not program_exited.value: it_prev = c_ulonglong(it.value) # Previous value of instructions counter sleep(delta_max) # If previous instruction lasted for more than 'delta_max', kill debugged process if (it_prev.value == it.value): # Process pid has been retrieved before kill(pid, signal.SIGTERM) program_exited.value = True print("idle_process_end") However, gdb.execute is pausing my thread... Is there another way to kill the debugged process if it is idling?
type: Question
tagged with: gdb-python
tagged with: gdb
downvote count: 0
has answer: http://stackoverflow.com/a/52228186
upvote count: 8
answer count: 1

http://stackoverflow.com/q/51962956
type: Question
has body: I'm trying to read a collection of XML files from a GCS bucket and process them where each element in the collection is a string representing the whole file but I can't find a decent example on how to accomplish this, nor can I understand it from the Apache Beam documentation which is mainly about the Java version. My current pipeline looks like this: p = beam.Pipeline(options=PipelineOptions(pipeline_args)) (p | 'Read from a File' &gt;&gt; beam.io.Read(training_files_folder) | 'String To BigQuery Row' &gt;&gt; beam.Map(lambda s: data_ingestion.parse_method(s)) | 'Write to BigQuery' &gt;&gt; beam.io.Write( beam.io.BigQuerySink( known_args.output, schema='title:STRING,text:STRING,id:STRING', create_disposition=beam.io.BigQueryDisposition.CREATE_IF_NEEDED, write_disposition=beam.io.BigQueryDisposition.WRITE_TRUNCATE))) p.run().wait_until_finish() And the error message I'm receiving is: File "C:\Program Files\JetBrains\PyCharm Community Edition 2018.2.1\helpers\pydev\pydevd.py", line 1664, in &lt;module&gt; main() File "C:\Program Files\JetBrains\PyCharm Community Edition 2018.2.1\helpers\pydev\pydevd.py", line 1658, in main globals = debugger.run(setup['file'], None, None, is_module) File "C:\Program Files\JetBrains\PyCharm Community Edition 2018.2.1\helpers\pydev\pydevd.py", line 1068, in run pydev_imports.execfile(file, globals, locals) # execute the script File "C:/Users/Tomer/PycharmProjects/hyperpartisan/cloud-version/data_ingestion.py", line 135, in &lt;module&gt; run() File "C:/Users/Tomer/PycharmProjects/hyperpartisan/cloud-version/data_ingestion.py", line 130, in run p.run().wait_until_finish() File "C:\Users\Tomer\anaconda\envs\hyperpartisan\lib\site-packages\apache_beam\runners\direct\direct_runner.py", line 421, in wait_until_finish self._executor.await_completion() File "C:\Users\Tomer\anaconda\envs\hyperpartisan\lib\site-packages\apache_beam\runners\direct\executor.py", line 398, in await_completion self._executor.await_completion() File "C:\Users\Tomer\…
tagged with: google-cloud-dataflow
has title: Read a set of xml files using Google Cloud DataFlow python sdk
answer count: 1
downvote count: 0
linked to: http://stackoverflow.com/q/45920895
favorite count: 0
has answer: http://stackoverflow.com/a/51973738
tagged with: python
type: AnsweredQuestion
score: 3
accepted answer: http://stackoverflow.com/a/51973738
upvote count: 3

http://stackoverflow.com/a/51986582
has comment: http://stackoverflow.com/comment/90922802
has body: You have a few places in your code where you forgot self. But the cause of your main error is that you need to pass the image name as a keyword arg. Here's a repaired version of your code. from tkinter import * import time from PIL import Image,ImageFilter from PIL import ImageTk class alien(object): def __init__(self): self.root = Tk() self.canvas = Canvas(self.root, width=400, height=400) self.canvas.pack() self.cardPath = Image.open('bubble.png') self.resCard = self.cardPath.resize((100, 100)) self.CardVar = ImageTk.PhotoImage(self.resCard) self.alien1 = self.canvas.create_oval(20, 260, 120, 360, outline='white', fill='blue') self.alien2 = self.canvas.create_image(100, 100, image=self.CardVar, anchor=CENTER) self.canvas.pack() self.root.after(0, self.animation) self.root.mainloop() def animation(self): track = 0 while True: x = 5 y = 0 if track == 0: for i in range(51): time.sleep(0.025) self.canvas.move(self.alien1, x, y) self.canvas.move(self.alien2, x, y) self.canvas.update() track = 1 print("check") else: for i in range(51): time.sleep(0.025) self.canvas.move(self.alien1, -x, y) self.canvas.move(self.alien2, -x, y) self.canvas.update() track = 0 print(track) alien() BTW, it's not a good idea to use time.sleep in GUI programs. It puts everything to sleep, so the GUI cannot update itself, or respond to any user input. It would be better to reorganize your code so that animation uses the .after method. Here's a version of the animation method that doesn't use sleep. You need to add self.count = 0 to the __init__ method. def animation(self): y = 0 x = 5 if self.count &lt; 50 else -5 self.count = (self.count + 1) % 100 self.canvas.move(self.alien1, x, y) self.canvas.move(self.alien2, x, y) self.root.after(25, self.animation)
has comment: http://stackoverflow.com/comment/90924404
has comment: http://stackoverflow.com/comment/90925007
type: Answer
answers question: http://stackoverflow.com/q/51986128
has comment: http://stackoverflow.com/comment/90922898
has comment: http://stackoverflow.com/comment/90924135
has comment: http://stackoverflow.com/comment/90924872
has comment: http://stackoverflow.com/comment/90923877
has comment: http://stackoverflow.com/comment/90924061
downvote count: 0
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/90925420

http://stackoverflow.com/q/51974807
score: 0
answer count: 2
tagged with: pandas
has title: Split every row in data frame and add value to each element avoiding NaN
has answer: http://stackoverflow.com/a/51974980
possible better answer: http://stackoverflow.com/a/51975355
tagged with: python
has answer: http://stackoverflow.com/a/51975355
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51974980
has body: the question originates from here: Split every row in df and add value to each element here is updated df: df = pd.DataFrame({'user_index': [3590,63, 15], 'movie_index': [1514,563, 9], 'genre_index':['10|12|17|35', '4|2|1|8', None], 'cast_index':['46|534', None, '9|27']}) to get the desired dataframe in which to every element would be added a value, I try: offset_dct = {'user_index': 2, 'genre_index': 5} df.astype(str).fillna('').apply(lambda x: [ [int(z) + offset_dct.get(x.name, 0) for z in y.split('|') if z is not None else []] for y in x]) but it returns me an error: ValueError: ("invalid literal for int() with base 10: 'nan'", 'occurred at index genre_index') if there were no 'NaN', this code would work perfectly: offset_dct = {'user_index': 2, 'genre_index': 5} df = df.fillna('').astype(str).apply(lambda x: [ [int(z) + offset_dct.get(x.name, 0) for z in y.split('|')] for y in x]) the problem is in constructing a list comprehension for ignoring NaN I think.. any help to solve would be very appreciated!
type: Question
linked to: http://stackoverflow.com/q/51972968

http://stackoverflow.com/a/52017705
score: 0
has comment: http://stackoverflow.com/comment/90985700
has comment: http://stackoverflow.com/comment/90985735
has comment: http://stackoverflow.com/comment/90986177
type: Answer
answers question: http://stackoverflow.com/q/52017524
has body: A possibility is to use numpy.append: import numpy as np rows = [[[1, 2, 3], [4]], [[5, 6], [7, 8]]] result = np.array([np.append(value[0], value[1:]) for value in rows]) print(result) Output [[1 2 3 4] [5 6 7 8]] The function numpy.append flattens value[1:]. One alternative is to use concatenate and ravel: rows = [[[1], [2], [3]], [[4], [5], [6]]] result = np.array([np.concatenate(value).ravel() for value in rows]) print(result) Output [[1 2 3] [4 5 6]] The concatenate function join a sequence of arrays and np.ravel returns a contiguous flattened array. You could change np.ravel by np.flatten.

http://stackoverflow.com/comment/91005351
comment on: http://stackoverflow.com/q/52027499
score: 0
type: Comment
type: QuestionComment
has text: @Dark Using `head(1)` instead of `first()` indeed seems to resolve the issue!

http://stackoverflow.com/comment/90942075
score: 0
comment on: http://stackoverflow.com/a/51995897
type: AnswerComment
has text: I'm getting an `IndexError: unsupported iterator index` error when I'm trying it on my dataset. I'm just looking at a column filled with `np.datetime64` values
type: Comment

http://stackoverflow.com/q/51958626
tagged with: operating-system
tagged with: python
upvote count: 6
type: Question
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51961000
tagged with: pyside
has answer: http://stackoverflow.com/a/69782871
has title: Why does QFileDialog use slash instead of backslash?
answer count: 2
tagged with: qfiledialog
downvote count: 0
possible better answer: http://stackoverflow.com/a/69782871
tagged with: windows-10
has body: Why "\" and "/" are mixed? os.getcwd() emits backslash string. On the other hand, QFileDialog emits forward slash string. Why? Example Please execute this sample code. from PySide import QtGui from PySide import QtCore import sys import os class DirectoryPrinter(QtGui.QWidget): def __init__(self,parent=None): super(DirectoryPrinter,self).__init__(parent=None) self.filedialog_pushbutton = QtGui.QPushButton("filedialog",self) self.connect(self.filedialog_pushbutton,QtCore.SIGNAL("clicked()"),self.filename_getter) def filename_getter(self): print("from os.getcwd()",os.getcwd()) filename = QtGui.QFileDialog.getOpenFileName(self,"Select your file",os.path.expanduser("~"))[0] print("from QFileDialog",filename) def main(): try: QtGui.QApplication([]) except Exception as e: print(22,e) directoryprinter = DirectoryPrinter() directoryprinter.show() sys.exit(QtGui.QApplication.exec_()) if __name__ == "__main__": main() Result (on my occasion) from os.getcwd(): J:\ from QFileDialog: C:/Users/******/setup.py
score: 6
favorite count: 0
accepted answer: http://stackoverflow.com/a/51961000

http://stackoverflow.com/a/52009785
downvote count: 0
score: 1
accepted answer of: http://stackoverflow.com/q/52006499
answers question: http://stackoverflow.com/q/52006499
upvote count: 1
type: AcceptedAnswer
type: Answer
has body: yes its mandatory to install browser and its compatible driver on client machine Below image will clear how it works

http://stackoverflow.com/comment/90962641
type: Comment
comment on: http://stackoverflow.com/q/52006097
score: 0
has text: Jumped to conclusions, sorry!
type: QuestionComment

http://stackoverflow.com/q/52056772
tagged with: python-3.x
tagged with: postgresql
has body: Assuming the following SQL Alchemy models: likes = db.Table('likes', db.Column('from_id', db.Integer, db.ForeignKey('user.id'), primary_key=True), db.Column('to_id', db.Integer, db.ForeignKey('user.id'), primary_key=True) ) class User(db.Model): id = db.Column(db.Integer, primary_key=True, autoincrement=True) liked_by = db.relationship('User', secondary=likes, foreign_keys=likes.c.to_id, lazy='subquery') likes = db.relationship('User', secondary=likes, foreign_keys=likes.c.from_id, lazy='subquery') What's the fastest and easiest way to add many like relationship between many User objects in a way that won't fail if duplicates are attempted? My closest solution is: x = [ {'from_id': 1, 'to_id': 2}, {'from_id': 2, 'to_id': 3}, {'from_id': 1, 'to_id': 3}, ... ] stmt = likes.insert().values(x) session.execute(stmt) session.commit() But this entire transaction will fail if, for example 1 -&gt; 2 already exists. Is there any way to execute this statement in a way that will add new rows in the likes table and won't fail on existing rows? The solution should be performant (i.e. support a bulk insertion). Database is PostgreSQL 10.x if a non-generic answer is needed.
tagged with: python
has title: Inserting many-to-many associations via through table in SQL Alchemy
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/52056973
has comment: http://stackoverflow.com/comment/91064731
upvote count: 1
has comment: http://stackoverflow.com/comment/91066086
tagged with: sqlalchemy
type: Question
has answer: http://stackoverflow.com/a/52056973
answer count: 1
downvote count: 0
score: 1
favorite count: 0

netcdf
tags question: http://stackoverflow.com/q/51996642
type: Tag
tags question: http://stackoverflow.com/q/51975333
tag name: netcdf
tags question: http://stackoverflow.com/q/52097744
tags question: http://stackoverflow.com/q/52046282

http://stackoverflow.com/comment/91060647
type: AnswerComment
comment on: http://stackoverflow.com/a/52055097
score: 0
type: Comment
has text: @MitchG you will have to create it for the first time I will make edits for that

http://stackoverflow.com/q/51972197
score: -3
has answer: http://stackoverflow.com/a/51972450
has title: How to store the indices into one variable
upvote count: 0
tagged with: string
favorite count: 0
type: Question
tagged with: python
downvote count: 3
answer count: 1
has body: This is my code: sub = ['great to have','good to have'] my_string =''' s ="" for i in sub: ii = my_string.lower().find(i) my_string[ii:] How to store the indexes into variable s?
tagged with: indexing
type: UnansweredQuestion

http://stackoverflow.com/comment/90905908
type: AnswerComment
score: 0
has text: you don't really need to check $f1
type: Comment
comment on: http://stackoverflow.com/a/51977993

http://stackoverflow.com/a/52045749
has comment: http://stackoverflow.com/comment/91080990
score: 1
accepted answer of: http://stackoverflow.com/q/52043027
has comment: http://stackoverflow.com/comment/91082560
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/91081424
has body: You did not specify your input, but since your code expects an obj and not a key, I assume the root level of your YAML is a sequence and not mapping. If you want to get the comments after each element (i.e nr 1 and the last) you can do: import ruamel.yaml yaml_str = """\ - one # nr 1 - two - three # the last """ yaml = ruamel.yaml.YAML() data = yaml.load(yaml_str) for idx, obj in enumerate(data): comment_token = data.ca.items.get(idx) if comment_token is None: continue print(repr(comment_token[0].value)) which gives: '# nr 1\n' '# the last\n' You might want to strip of the leading octothorpe and trailing newline. Please note that this works with the current version (0.15.61), but there is no guarantee it might not to change.
type: Answer
has comment: http://stackoverflow.com/comment/91081939
has comment: http://stackoverflow.com/comment/91082743
answers question: http://stackoverflow.com/q/52043027
upvote count: 1
has comment: http://stackoverflow.com/comment/91081566

http://stackoverflow.com/a/52038598
type: Answer
score: 2
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52038190
answers question: http://stackoverflow.com/q/52038190
upvote count: 2
has body: virtualenv has --no-site-packages option turned on by default, with or without this option makes no difference: --no-site-packages DEPRECATED. Retained only for backward compatibility. Not having access to global site-packages is now the default behavior. see more on its doc. you could re-try with --system-site-packages option.
type: AcceptedAnswer

http://stackoverflow.com/q/52064975
has answer: http://stackoverflow.com/a/52091776
upvote count: 4
tagged with: apache-spark-sql
downvote count: 0
tagged with: pyspark
type: UnansweredQuestion
has body: I am trying to create a new dataframe that has the averages of every 60 observations coming from the old dataframe. Here is the code I implemented in pandas: new_df = old_df.groupby(old_df.index // 60).mean() I am struggling with how to do this same thing in databricks using pyspark.
type: Question
favorite count: 0
tagged with: aggregation
answer count: 2
tagged with: python
has title: pyspark aggregating every n rows
has answer: http://stackoverflow.com/a/76952168
score: 4

http://stackoverflow.com/q/52026707
type: Question
upvote count: 2
tagged with: pivot-table
tagged with: python
tagged with: lambda
downvote count: 1
has comment: http://stackoverflow.com/comment/91004164
answer count: 0
tagged with: dataframe
type: UnansweredQuestion
has title: Python DataFrame Pivot table background color change based on condition
tagged with: pandas
score: 1
has comment: http://stackoverflow.com/comment/91043767
favorite count: 0
has body: i'm very new to python program i want to change background color in pivot table result.color changes condition based on other column and if Flag_Status column have more than one value color should be white. &lt;pre&gt; Source Data JobID,Name,Flag_Statge,Runid,Value 'JOB1','Q1','L1',1,200 'JOB1','Q1','L1',1,300 'JOB1','Q1','L4',1,214 'JOB1','Q1','L2',1,364 'JOB1','Q2','L1',1,214 'JOB1','Q3','L3',1,176 'JOB1','Q4','L2',1,82 'JOB1','Q1','L2',2,201 'JOB1','Q2','L1',2,224 'JOB1','Q3','L4',2,196 'JOB1','Q4','L1',2,182 'JOB1','Q1','L3',3,201 'JOB1','Q2','L1',3,224 'JOB1','Q2','L1',3,189 'JOB1','Q3','L2',3,196 'JOB1','Q4','L3',3,182 import pandas as pd import numpy as np def fstatus(fbgcolor): return { 'L1': 'red', 'L2': 'green', 'L3': 'blue', 'L4': 'yellow' }[fbgcolor] sf = pd.read_excel(r'attachedexcel_filepath\PivotExam.xlsx') df = pd.DataFrame(sf) df = df.pivot_table(values=['Value'],index =['JobID','Name'],columns=['Runid'],aggfunc=np.average) sdf = df.pivot_table(values=['Flag_Statge'],index =['JobID','Name'],columns=['Runid'],aggfunc={'Flag_Statge': lambda x: ','.join(x.unique())}) def bgcolorformat(row): ret = ["" for _ in row.index] ret[row.index.get_loc('Flag_Statge')]= sdf['Flag_Statge'].apply(lambda x: fstatus(x)) df.style.apply(bgcolorformat, axis=1) based on sdf resultwise we can apply the color format. i have attached output result file. can you explain lambda function list &amp; looping. Source Data and Expected Result set:
has comment: http://stackoverflow.com/comment/91003600

http://stackoverflow.com/q/52043903
upvote count: 0
tagged with: ubuntu
type: Question
has answer: http://stackoverflow.com/a/52044458
tagged with: python
score: -2
favorite count: 0
has body: So I am running django on my Ubuntu instance. I am new to using ubuntu but I am running this very sensitive server where I can not afford to allow it to crash. I plan on making some changes to some py and html files but was wondering what the following steps would be to allow for a smooth update. I am running Django, uwsgi, Nginx and Supervisord. My partner had left with very little notes who would usually be in charge of this all.
downvote count: 2
tagged with: django
answer count: 1
type: UnansweredQuestion
has title: Making changes to Python and DJango files on Ubuntu
tagged with: uwsgi

http://stackoverflow.com/comment/91137573
comment on: http://stackoverflow.com/q/52093695
score: 3
type: Comment
has text: Post the full code where you create the class instance and call the functions. Allow others to reproduce the error/problem
type: QuestionComment

http://stackoverflow.com/comment/90912915
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51981528
has text: This seems like a job for regular expressions (except maybe the "all zeros" part, for which it might be easier to add a separate check afterwards).
score: 0

http://stackoverflow.com/comment/90996006
comment on: http://stackoverflow.com/q/52022551
score: 0
has text: That INSERT command should have failed, with an error message that `password` is not a recognized column. (As @RaymondNijland pointed out, that table contains a `password_md5` column, not a `password` column.)
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91019177
type: Comment
comment on: http://stackoverflow.com/q/52034569
has text: @Raunaq Jain My method 2 is better than slicing. `g2dict = dict(i for i in g2)` . But if I need use multiprocessing , it has to produce multiple copys of `g2dict`.
score: 0
type: QuestionComment

http://stackoverflow.com/a/52022915
has comment: http://stackoverflow.com/comment/90997126
score: 0
answers question: http://stackoverflow.com/q/52022867
type: Answer
has comment: http://stackoverflow.com/comment/90996153
has body: Maybe: c=np.array([[sum(b.tolist())+y for i in range(len(x))] for y,x in enumerate(a.tolist())]) c[np.isnan(a)]=np.nan print(c) Output: [[ nan 2. 2.] [ nan 3. 3.] [ nan 4. nan]]

http://stackoverflow.com/a/52074876
downvote count: 0
upvote count: 39
type: AcceptedAnswer
has body: It seems like you have a list of tensors. For each tensor you can see its size() (no need to convert to list/numpy). If you insist, you can convert a tensor to numpy array using numpy(): Return a list of tensor shapes: &gt;&gt; [t.size() for t in my_list_of_tensors] Returns a list of numpy arrays: &gt;&gt; [t.numpy() for t in my_list_of_tensors] In terms of performance, it is always best to avoid casting of tensors into numpy arrays, as it may incur sync of device/host memory. If you only need to check the shape of a tensor, use size() function.
score: 39
accepted answer of: http://stackoverflow.com/q/52074153
type: Answer
answers question: http://stackoverflow.com/q/52074153

http://stackoverflow.com/q/52101988
tagged with: split
tagged with: pandas
downvote count: 0
answer count: 1
has body: I have a Numpy array as a list of lists with dimension of n by 4 (row, column). I am trying to separate the data from each individual list instance into four separate arrays each containing all the information from a single column so I can add it to a pandas data frame. From this: [[126 188 166 1] [111 173 149 1] [ 81 119 123 2] [ 83 122 124 2] [ 84 122 124 2] [255 255 255 3] [255 255 255 3] [255 255 255 3]] To this: bBand = [126,111,81,...,255] gBand = [188,173,119,...,255] rBand = [166,149,123,...,255] class = [1,1,2,...,3] Current Code: MasterList = np.arrray([[126, 188, 166, 1],[111, 173, 149, 1],[ 81, 119, 123, 2],[ 83, 122, 124, 2],[ 84, 122, 124, 2],[255, 255, 255, 3],[255, 255, 255, 3],[255, 255, 255, 3]]) print(MasterList) columns = ["bBand","gBand","rBand","class"] df = pd.DataFrame(MasterList.reshape(-1, len(MasterList)),columns=columns)
has comment: http://stackoverflow.com/comment/91154824
favorite count: 0
tagged with: python
score: 2
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52102114
upvote count: 2
type: Question
has title: Split Numpy Array into Arrays of each column
accepted answer: http://stackoverflow.com/a/52102114
tagged with: numpy

http://stackoverflow.com/q/52101881
type: Question
has answer: http://stackoverflow.com/a/52102026
upvote count: 3
tagged with: pandas
answer count: 1
tagged with: string
has body: I have a dataframe with mixed string and float/int values in column 'k': &gt;&gt;&gt; df a b k 0 1 a q 1 2 b 1 2 3 c e 3 4 d r When I do this to remove any whitespaces from all columns: df.apply(lambda x: x.str.strip() if x.dtype == "object" else x) It converts the integer 1 to a NaN: a b k 0 1 a q 1 2 b NaN 2 3 c e 3 4 d r How can I overcome this?
favorite count: 0
has title: Pandas: Strip white spaces from columns with mixed string-float values
tagged with: python
type: AnsweredQuestion
score: 3
downvote count: 0
accepted answer: http://stackoverflow.com/a/52102026

http://stackoverflow.com/comment/91041860
score: 0
has text: Thank you so much for this-- you're right. Django hasn't actually been making any of my migrations, so I built a couple of the tables manually to it's specification and that worked. I tried running the django-admin makemigrations, but I'm getting a modulenotfound error for my site. Ah well. Next challenge.
type: Comment
comment on: http://stackoverflow.com/a/52036094
type: AnswerComment

http://stackoverflow.com/q/51972126
has title: filtering in python for elastic search
accepted answer: http://stackoverflow.com/a/51972385
answer count: 1
downvote count: 0
favorite count: 0
tagged with: python-3.x
tagged with: elasticsearch
tagged with: python
has body: I am trying to filter out the elastic search query to create a pandas dataframe. I have two columns "type" and "api" in the dataframe on which iam applying filter. When I am applying one column as condition it is working fine..:- result_dict = es.search(index="logstash-2018.08.11-alias", body={"from": 0, "size": 10000,"query": {"term" : {"type":"vx_apache_json"}}}) But when i am applying multiple condition like below :- result_dict = es.search(index="logstash-2018.08.11-alias", body={"from": 0, "size": 1000,"queries": [ { "term" : {"type" :"vx_apache_json"}}, { "term" : {"api" :"viv_signin.php"}} ]}) I am getting the below error :- RequestError: RequestError(400, 'parsing_exception', 'Unknown key for a START_ARRAY in [queries].') Can someone help me here like how i can put multiple filtering in elastic search.
type: AnsweredQuestion
score: 1
has answer: http://stackoverflow.com/a/51972385
upvote count: 1
type: Question
tagged with: elastic-stack
tagged with: python-2.7

http://stackoverflow.com/q/51982436
tagged with: python-3.x
has title: OpenGL - Render same scene from different angles without redrawing everything
has answer: http://stackoverflow.com/a/51982645
has body: I have a scene that I'm trying to render in all directions (later stitched together, outside OpenGL). Currently for creating each frame - I redraw the entire scene 4 times (front, right, back, left). Can I somehow just render the 4 cubes together without redrawing the entire scene 4 times? Here is a sample code that I use (Specifically I use PyOpenGL - But that doesn't really matter): import cv2 import numpy as np from OpenGL.GL import * from OpenGL.GLU import * from OpenGL.GLUT import * import glfw # Draws some model (The real code draws a much more complicated model) def draw_model(): glBegin(GL_QUADS) glColor3f(1.0, 1.0, 1.0) glVertex(10, 10, 0); glVertex(10, 10, 3); glVertex(10, -10, 3); glVertex(10, -10, 0) glColor3f(1.0, 1.0, 0) glVertex(-10, 10, 0); glVertex(-10, 10, 3); glVertex(-10, -10, 3); glVertex(-10, -10, 0) glColor3f(1.0, 0, 1.0) glVertex(10, 10, 0); glVertex(10, 10, 3); glVertex(-10, 10, 3); glVertex(-10, 10, 0) glColor3f(0, 1.0, 0) glVertex(10, -10, 0); glVertex(10, -10, 3); glVertex(-10, -10, 3); glVertex(-10, -10, 0) glEnd() # Reads the pixels to NP def get_display_pixels(rendered_image_width, rendered_image_height): data = glReadPixels(0, 0, rendered_image_width, rendered_image_height, OpenGL.GL.GL_RGB, OpenGL.GL.GL_UNSIGNED_BYTE) return np.frombuffer(data, dtype=np.uint8).reshape(rendered_image_height, rendered_image_width, 3)[::-1] DISPLAY_WIDTH = 900 DISPLAY_HEIGHT = 900 glfw.init() glfw.window_hint(glfw.VISIBLE, False) window = glfw.create_window(DISPLAY_WIDTH, DISPLAY_HEIGHT, "some window", None, None) glfw.make_context_current(window) gluPerspective(90, (DISPLAY_WIDTH / DISPLAY_HEIGHT), 0.01, 30) glEnable(GL_TEXTURE_2D) glEnable(GL_DEPTH_TEST) glDepthFunc(GL_LEQUAL) position = (0, 3, 1) # Get cube 1 glPushMatrix() glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) gluLookAt(*position, 1, 4, 1, 0, 0, 1) draw_model() cube1 = get_display_pixels(DISPLAY_WIDTH, DISPLAY_HEIGHT) glPopMatrix() # Get cube 2 glPushMatrix() glClear(GL_COLOR_BUFFER_BIT…
upvote count: 1
tagged with: python
type: AnsweredQuestion
tagged with: opengl
score: 1
tagged with: pyopengl
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/52034713
tagged with: scene
downvote count: 0
has comment: http://stackoverflow.com/comment/90915878
possible better answer: http://stackoverflow.com/a/51982645
favorite count: 0
accepted answer: http://stackoverflow.com/a/52034713

http://stackoverflow.com/q/52014444
favorite count: 0
has answer: http://stackoverflow.com/a/62037963
tagged with: python
tagged with: folium
downvote count: 0
tagged with: geojson
type: AnsweredQuestion
score: 1
has body: I'm having trouble modifying a code snippet from the second TimestampedGeoJson example in the Plugins example notebook. The duration parameter is described as the "period of time which the features will be shown on the map after their time has passed. If None, all previous times will be shown." Take the case below with two polygons import folium from folium.plugins import TimestampedGeoJson m = folium.Map(location=[52.467697, -2.548828], zoom_start=6) polygon_1 = { 'type': 'Feature', 'geometry': { 'type': 'MultiPolygon', 'coordinates': [(( (-2.548828, 51.467697), (-0.087891, 51.536086), (-1.516113, 53.800651), (-6.240234, 53.383328), ),)], }, 'properties': { 'style': { 'color': 'blue', }, 'times': ['2015-07-22T00:00:00', '2015-08-22T00:00:00', '2015-09-22T00:00:00', '2015-10-22T00:00:00', '2015-11-22T00:00:00', '2015-12-22T00:00:00'] } } polygon_2 = { 'type': 'Feature', 'geometry': { 'type': 'MultiPolygon', 'coordinates': [(( (-3.548828, 50.467697), (-1.087891, 50.536086), (-2.516113, 52.800651), (-7.240234, 52.383328), ),)], }, 'properties': { 'style': { 'color': 'yellow', }, 'times': ['2015-07-22T00:00:00', '2015-08-22T00:00:00'] } } TimestampedGeoJson( {'type': 'FeatureCollection', 'features': [polygon_1, polygon_2]}, period='P1M', duration='P1M', auto_play=False, loop=False, loop_button=True, date_options='YYYY/MM/DD', ).add_to(m) m The first polygon is active from July to December so I expect it to be drawn for all time periods; the second polygon is active only in July and August so it should be drawn up until one month after its last month: so July, August and September. Instead what I see is that both polygons are drawn in the first period, disappear in the second, then the second polygon is drawn in September and disappears again in October. To be clear: Expected +-----------+----------+----------+ | Month | Polygon1 | Polygon2 | +-----------+----------+----------+ | July | X | X | | August | X | X | | September | X | X | | October | X | | | November | X | …
accepted answer: http://stackoverflow.com/a/62037963
type: Question
has title: TimestampedGeoJson duration parameter causes polygons to disappear
upvote count: 1
answer count: 1

http://stackoverflow.com/a/52054669
has comment: http://stackoverflow.com/comment/98771448
has comment: http://stackoverflow.com/comment/98769538
has body: The idea would be to let your functions plot to an axes. Either you provide this axes as argument to the function or you let it take the current axes. import matplotlib.pyplot as plt import numpy as np def func1(ax=None): ax = ax or plt.gca() line, = ax.plot (np.arange(0.0, 5.0, 0.1)) return line def func2(ax=None): ax = ax or plt.gca() line, = ax.plot (np.arange(0.0, 5.0, 0.02)) return line fig, (ax1,ax2) = plt.subplots(ncols=2) func1(ax1) func2(ax2) plt.show()
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/52054491
score: 13
upvote count: 13

http://stackoverflow.com/q/51990546
tagged with: python
has answer: http://stackoverflow.com/a/51990750
has comment: http://stackoverflow.com/comment/90931120
has comment: http://stackoverflow.com/comment/90931283
score: -1
tagged with: django-views
downvote count: 1
has comment: http://stackoverflow.com/comment/90930797
type: Question
has title: DjangoRestFramework - How to update fields in model
tagged with: django-models
has comment: http://stackoverflow.com/comment/90930839
upvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/90930892
has body: I am using Django user model and also extended with my own profile model for some other data.When i want to update user data which is in Profile Model It doesn't get updated because all the user id,username,email,password reside in user model while the fields which are needed to get updated are in profile model.I have used this approach, all it does is takes inputs and displays the response but does not show any change in User Data when viewing it as a whole. models.py class Profile(models.Model): user = models.OneToOneField(User,related_name='profile',on_delete=models.CASCADE) location = models.CharField(max_length=30,blank=True) friends_count = models.PositiveIntegerField(default=0) profile_pic = models.FileField(upload_to='profile_pics/',blank=True,null=True) def natural_key(self): return (self.user.username,) views.py class UserCreateAPIViewSet(viewsets.ModelViewSet,mixins.UpdateModelMixin): """"A View which handles Creating and Updating User Profile""" serializer_class = UserProfileCreateSerializer queryset = User.objects.all() authentication_classes = (TokenAuthentication,) permission_classes = (permissions.UpdateOwnProfile,) filter_backends = (filters.SearchFilter,) search_fields = ('username','email',) class UserUpdateAPI(generics.GenericAPIView,mixins.UpdateModelMixin): """Update User Profile Data""" permission_classes = (permissions.UpdateOwnProfile,) authentication_classes = (TokenAuthentication,) queryset = Profile.objects.all() serializer_class = ProfileUpdateSerializer def put(self,request,*args,**kwargs): return self.partial_update(request,*args,**kwargs) urls.py url(r'^user-update/(?P&lt;pk&gt;\d+)/$',views.UserUpdateAPI.as_view(),name="user-update"), router = DefaultRouter() router.register(r'profile',views.UserCreateAPIViewSet) serializers.py class UserProfileCreateSerializer(serializers.ModelSerializer): """"A serializer for user data request""" location = serializers.CharField(source='profile.location') friends_count = serializers.IntegerField(so…
tagged with: django-rest-framework
favorite count: 0
type: UnansweredQuestion
tagged with: django

http://stackoverflow.com/comment/91066108
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52057927
has text: your frame always starts from **1** ?
score: 0

http://stackoverflow.com/q/52049906
tagged with: python
has comment: http://stackoverflow.com/comment/91050312
type: AnsweredQuestion
downvote count: 3
upvote count: 1
has answer: http://stackoverflow.com/a/52049965
tagged with: loops
has comment: http://stackoverflow.com/comment/91050350
type: Question
has answer: http://stackoverflow.com/a/52049940
accepted answer: http://stackoverflow.com/a/52049965
score: -2
possible better answer: http://stackoverflow.com/a/52049940
has title: Python does not start the for loop with another index
answer count: 3
linked to: http://stackoverflow.com/q/17498407
has body: This is the code. if __name__ == '__main__': n = int(input()) i=4 for i in range(n): print(i) I want it to print from 4 to n values, but it always starts printing from 0. In C++, the value for i would start from 4 but in Python3, it always starts from 0.
has answer: http://stackoverflow.com/a/52049942
has comment: http://stackoverflow.com/comment/91050272
favorite count: 0
duplicate of: http://stackoverflow.com/q/17498407
tagged with: python-3.x

http://stackoverflow.com/comment/91151723
has text: @SanDiego can you write clearly what do you expect from the program? from your file `hey.txt` what do you want to remove?
comment on: http://stackoverflow.com/q/52088299
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/51984470
downvote count: 0
has comment: http://stackoverflow.com/comment/90918718
type: Answer
accepted answer of: http://stackoverflow.com/q/51984323
has comment: http://stackoverflow.com/comment/90918762
upvote count: 3
answers question: http://stackoverflow.com/q/51984323
score: 3
has comment: http://stackoverflow.com/comment/91276409
has body: You can use next with a generator expression and split by a specific character to reflect the structure of your strings: foolist = ['123-asd','234-asd','345-asd'] res = next(i for i, j in enumerate(foolist) if '123' in j.split('-')[0]) # 0 If there can be multiple matches, you can use a list comprehension: res = [i for i, j in enumerate(foolist) if '123' in j.split('-')[0]] # [0] For equality, you should use j.split('-')[0]] == '123' as your condition instead. Note on print within a comprehension It's good practice to avoid print in a list comprehension, as it will return None. You will notice that, while your terminal will print the indices it finds, you are also building a list of None items with length equal to the number of matches. For all intents, that list has no use. If you are only interested in printing items, you can use a for loop with a generator expression: for idx in (i for i, j in enumerate(foolist) if '123' in j.split('-')[0]): print(idx)
has comment: http://stackoverflow.com/comment/91276513
type: AcceptedAnswer

http://stackoverflow.com/a/51989043
answers question: http://stackoverflow.com/q/51988762
upvote count: 2
has body: Notice this will be O(m*n) method , create a new key for merge df1['Newkey']=1 df2['Newkey']=1 df2.reset_index(inplace=True) mergefilterdf=df1.merge(df2).\ loc[lambda x : (x['start_date']&lt;=x['index'])&amp;(x['end_date']&gt;=x['index'])] mergefilterdf.groupby(['start_date','end_date']).value.sum() Out[331]: start_date end_date 2018-01-01 2018-01-31 17 Name: value, dtype: int64
downvote count: 0
type: Answer
score: 2

http://stackoverflow.com/comment/90895803
score: 0
type: Comment
comment on: http://stackoverflow.com/q/51971570
type: QuestionComment
has text: @juanpa.arrivillaga thanks! Turns out you can not eval `ast.literall_eval('f\'{y}\'')` which keeps it safe

selenium
tags question: http://stackoverflow.com/q/52002958
tags question: http://stackoverflow.com/q/52073181
tags question: http://stackoverflow.com/q/52082207
tags question: http://stackoverflow.com/q/52021047
tags question: http://stackoverflow.com/q/52002135
tags question: http://stackoverflow.com/q/52049929
tags question: http://stackoverflow.com/q/52026079
tags question: http://stackoverflow.com/q/52063354
tags question: http://stackoverflow.com/q/52017950
tags question: http://stackoverflow.com/q/51973860
tags question: http://stackoverflow.com/q/52112188
tags question: http://stackoverflow.com/q/51966346
tags question: http://stackoverflow.com/q/51998266
tags question: http://stackoverflow.com/q/52079180
tags question: http://stackoverflow.com/q/51967309
tags question: http://stackoverflow.com/q/52013284
tags question: http://stackoverflow.com/q/51996181
tags question: http://stackoverflow.com/q/51958242
tags question: http://stackoverflow.com/q/52084458
tags question: http://stackoverflow.com/q/51987761
tags question: http://stackoverflow.com/q/51989493
tags question: http://stackoverflow.com/q/51986354
tags question: http://stackoverflow.com/q/51964400
tags question: http://stackoverflow.com/q/52087021
tags question: http://stackoverflow.com/q/51986258
tags question: http://stackoverflow.com/q/52007095
tags question: http://stackoverflow.com/q/51970555
tags question: http://stackoverflow.com/q/52035719
tags question: http://stackoverflow.com/q/52001607
tags question: http://stackoverflow.com/q/52082123
tags question: http://stackoverflow.com/q/52069009
tags question: http://stackoverflow.com/q/52079496
tags question: http://stackoverflow.com/q/52040993
tags question: http://stackoverflow.com/q/52010016
tags question: http://stackoverflow.com/q/52109323
tags question: http://stackoverflow.com/q/51977550
tags question: http://stackoverflow.com/q/52084252
tags question: http://stackoverflow.com/q/52063107
tags question: http://stackoverflow.com/q/52009771
tags question: http://stackoverflow.com/q/51996121
tags question: http://stackoverflow.com/q/51994821
tags question: http://stackoverflow.com/q/52033607
tags question: http://stackoverflow.com/q/52058628
tags question: http://stackoverflow.com/q/52089380
tags question: http://stackoverflow.com/q/52110934
tags question: http://stackoverflow.com/q/52013628
tags question: http://stackoverflow.com/q/52025396
tags question: http://stackoverflow.com/q/52067414
tags question: http://stackoverflow.com/q/52022841
tags question: http://stackoverflow.com/q/52013464
tags question: http://stackoverflow.com/q/51976238
tag name: selenium
tags question: http://stackoverflow.com/q/52095282
tags question: http://stackoverflow.com/q/52005385
tags question: http://stackoverflow.com/q/52109777
tags question: http://stackoverflow.com/q/52087684
tags question: http://stackoverflow.com/q/52103552
tags question: http://stackoverflow.com/q/52009351
tags question: http://stackoverflow.com/q/52074680
tags question: http://stackoverflow.com/q/52063068
tags question: http://stackoverflow.com/q/52074398
tags question: http://stackoverflow.com/q/52007065
tags question: http://stackoverflow.com/q/51958574
tags question: http://stackoverflow.com/q/52010624
tags question: http://stackoverflow.com/q/52045120
tags question: http://stackoverflow.com/q/52055518
tags question: http://stackoverflow.com/q/52033155
tags question: http://stackoverflow.com/q/52084739
tags question: http://stackoverflow.com/q/52101431
tags question: http://stackoverflow.com/q/52028121
tags question: http://stackoverflow.com/q/52074660
tags question: http://stackoverflow.com/q/52045083
tags question: http://stackoverflow.com/q/52066226
tags question: http://stackoverflow.com/q/51978412
tags question: http://stackoverflow.com/q/52111479
tags question: http://stackoverflow.com/q/52006499
tags question: http://stackoverflow.com/q/51988165
tags question: http://stackoverflow.com/q/51970470
type: Tag
tags question: http://stackoverflow.com/q/52083981

http://stackoverflow.com/a/52068512
upvote count: 2
has comment: http://stackoverflow.com/comment/91087433
has comment: http://stackoverflow.com/comment/91087619
has comment: http://stackoverflow.com/comment/91087444
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52068447
has comment: http://stackoverflow.com/comment/91093000
has body: Python's isfile and isdir may help: import os path = r'c:\users\name\desktop\project\input_samples' if os.path.isfile(path): # it's a file, do something with it pass elif os.path.isdir(path): # it's a directory for xyz_file in os.listdir(path): if xyz_file.endswith('xyz'): # (operations of function here) pass else: raise RuntimeError("Not supported entry")
answers question: http://stackoverflow.com/q/52068447
type: Answer
has comment: http://stackoverflow.com/comment/91087352
has comment: http://stackoverflow.com/comment/91087839
score: 2

http://stackoverflow.com/q/52020720
type: Question
answer count: 1
downvote count: 0
tagged with: python
favorite count: 0
has body: Are there any toolbox or package in Julia which is similar to the data acquisition toolbox of Matlab? In Python I encountered Pyserial. Are there more?
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/52021751
tagged with: julia
score: 3
has title: Data acquisition package/toolbox in Julia or Python
upvote count: 3

http://stackoverflow.com/q/52040118
linked to: http://stackoverflow.com/q/43095739
upvote count: 1
has comment: http://stackoverflow.com/comment/91030867
favorite count: 0
type: UnansweredQuestion
tagged with: python
has body: It seems I'm doing something wrong with numpy's searchsorted. It always gives me the highest index (285) for any number greater than the smallest number (~0.001) of ratios.values. However if inserted at this position, it would clearly break the existing ordering within ratios.values. &gt;&gt;&gt; ratios = df.activity.value_counts(normalize=True) &gt;&gt;&gt; np.searchsorted(ratios.values, 0.06) 285 &gt;&gt;&gt; np.searchsorted(ratios.values, 0.006) 285 &gt;&gt;&gt; np.searchsorted(ratios.values, 0.001) 0 For 0.06 I'd expect the index 1 to be returned, since 0.06 should be placed in between the first and second element of ratios.values.
has title: Numpy searchsorted not working as expected
answer count: 0
downvote count: 0
score: 1
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/91031277

http://stackoverflow.com/q/52059567
tagged with: python-2.7
score: 0
has body: I am getting a multi-gigabyte json file from an S3 bucket and need to convert the json file into a python dictionary. How can this be done in python 2.7?
linked to: http://stackoverflow.com/q/2400643
type: UnansweredQuestion
tagged with: bigdata
has comment: http://stackoverflow.com/comment/91069732
tagged with: python
has comment: http://stackoverflow.com/comment/91069544
has title: How to parse a multi-gigabyte JSON file - Python
answer count: 0
tagged with: http://stackoverflow.com/tag/json
has comment: http://stackoverflow.com/comment/91089761
has comment: http://stackoverflow.com/comment/91069523
type: Question
has comment: http://stackoverflow.com/comment/91069655
has comment: http://stackoverflow.com/comment/91069708
tagged with: amazon-s3
has comment: http://stackoverflow.com/comment/91069522

http://stackoverflow.com/q/51969578
has comment: http://stackoverflow.com/comment/90902065
has comment: http://stackoverflow.com/comment/111105806
tagged with: convex-optimization
tagged with: cvxpy
downvote count: 0
has comment: http://stackoverflow.com/comment/95845955
favorite count: 0
has body: def PPNM_model(a,E, beta): p = E.shape[1] x = E*a x = sum(x,beta*cp.square(x)) return x def PPNM_model_cvxpy(a,E,beta): first = E*a second = beta*cp.square(first) third = sum(first,second) return third def construct_ppnm_model(x_in,A,E, x_LMM, a_lmm): p = E.shape[1] d = E.shape[0] N = A.shape[0] x = np.zeros(shape=(N,d), dtype=np.float64) a_ppnm = np.zeros(shape=(N,p), dtype=np.float64) beta_ppnm = np.zeros(shape=(N,1), dtype=np.float64) current_lmm = cp.Variable(p) current_beta = cp.Variable() b_min = 0 b_max = 100 all_zeros = np.squeeze(np.zeros(shape=(N,1), dtype=np.double)) sum_to_one_vector=np.ones(shape=(1,p),dtype=np.double) for i in np.arange(0, N): x_in_temp = x_in[i,:].astype(np.double) current_lmm.value=a_lmm[i,] objective = cp.Minimize(cp.sum_squares((PPNM_model_cvxpy(current_lmm, E, current_beta)) - x_in_temp)) constraints = [current_lmm &gt;= 0, current_lmm &lt;= 1, current_beta &gt;= b_min, current_beta &lt;= b_max, sum_to_one_vector*current_lmm == 1] prob = cp.Problem(objective, constraints) result = prob.solve() a_ppnm[i,:]=current_lmm.value beta_ppnm[i] = current_beta.value current_vector = PPNM_model(a_ppnm[i,:], E, current_beta.value) x[i,:]=current_vector return x, a_ppnm, beta_ppnm In this problem, matrix A is of shape (10000, 4) which is (total pixels, endmembers), E is of shape (198, 4) :(spectral bands, endmembers) and x is of shape (10000, 198) :( pixels, spectral bands) When I call the construct_ppnm_model like this: x_ppnm, a_ppnm, beta_ppnm = construct_ppnm_model(hsi_2d, A, E, x_LMM, a_lmm) I get the following error message: NotImplementedError: Strict inequalities are not allowed.
upvote count: 2
type: UnansweredQuestion
tagged with: python
score: 2
answer count: 0
has title: CVXPY error: "NotImplementedError: Strict inequalities are not allowed"
type: Question

http://stackoverflow.com/comment/90951893
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51992539
has text: Could you post the output of the two print statements there?
score: 0

http://stackoverflow.com/comment/91021079
has text: What is your aim with saving an empty list to an empty file, and then reading it back?
comment on: http://stackoverflow.com/q/52035453
type: QuestionComment
type: Comment
score: 2

http://stackoverflow.com/q/52087029
type: UnansweredQuestion
has body: How can I convert pandas string column into string series without text getting trimmed? s = pd.Series('Data was not intuitive and too difficult for our marketing team to use. Big-Data has been a huge improvement.') When convert Series into string. It gets trimmed. d = s.to_string(index=False) d = 'Sprinklr was not intuitive and too difficult f...' I want to use this series to count words in it. But getting trimmed is coming in my way.
has comment: http://stackoverflow.com/comment/91124350
tagged with: python
has title: How can I convert pandas string column into string series without text getting trimmed?
has comment: http://stackoverflow.com/comment/91124380
has comment: http://stackoverflow.com/comment/91124375
answer count: 0
type: Question
has comment: http://stackoverflow.com/comment/91124339
has comment: http://stackoverflow.com/comment/91149975
tagged with: series
score: 0
has comment: http://stackoverflow.com/comment/91131138
tagged with: pandas

http://stackoverflow.com/q/52037383
answer count: 0
type: UnansweredQuestion
tagged with: python
tagged with: magic-methods
has title: __getattr__ on Exception subclass
type: Question
upvote count: 2
downvote count: 2
tagged with: inheritance
has comment: http://stackoverflow.com/comment/91132132
favorite count: 0
score: 0
linked to: http://stackoverflow.com/q/3155436
tagged with: custom-exceptions
duplicate of: http://stackoverflow.com/q/3155436
has comment: http://stackoverflow.com/comment/91131201
has body: So I'm (of course) writing a library that interacts with an API, and the API can sometimes return errors. I came up with a context manager to catch dynamic errors, but I'd like to do something a little quicker: class APIError(Exception): def __getattr__(self, name): setattr(self, name, type(name, (APIError,), {})) return getattr(self, name) What I'd then like to do is something like this: try: ... except APIError.knownerrorcode: ...handle... However, this doesn't work - the __getattr__ doesn't apply to the class itself. The workaround is to do this: try: ... except APIError().knownerrorcode: ...handle... but this is ugly and normally wouldn't make sense - you can't catch exception instances, only classes, but APIError() obviously creates an instance. To solve that problem, I added APIError = APIError() after the class declaration, and then the second example worked fine. However, after that change, this failed: try: ... except APIError: ...handle... because APIError is now an instance and cannot be directly caught. The following doesn't work properly either: class APIError(Exception): @classmethod def __getattr__(cls, name): setattr(cls, name, type(name, (cls,), {})) return getattr(cls, name) because the decorator converts it into a normal method: &gt;&gt;&gt; APIError.knownerrorcode Traceback (most recent call last): File "&lt;pyshell#75&gt;", line 1, in &lt;module&gt; APIError.knownerrorcode AttributeError: type object 'APIError' has no attribute 'knownerrorcode' &gt;&gt;&gt; APIError.__getattr__('knownerrorcode') &lt;class '__main__.knownerrorcode'&gt; I've also tried metaclasses: class meta(type): def __getattr__(self, name): setattr(self, name, type(name, (APIError,), {})) return getattr(self, name) class APIError(Exception, meta): pass but the second declaration results in a TypeError: Traceback (most recent call last): File "&lt;pyshell#66&gt;", line 1, in &lt;module&gt; class APIError(Exception, meta): TypeError: multiple bases have instance lay-out conflict…
has comment: http://stackoverflow.com/comment/91131114

http://stackoverflow.com/q/51970877
type: UnansweredQuestion
upvote count: 1
tagged with: python
has body: I have a Python app that I use locally that needs to be launched via pipenv run python3 appname.py in order to load virtual environment with installed dependencies. This is all on macOS. What I want to achieve is to be able to run this app from anywhere with $ appname [args]. So what I did was: add #!/usr/bin/env pipenv run python3 to appname.py; make that file executable with chmod +x appname.py; make symlink with ln -s /path/to/appname.py ~/.bin/appname; put ~/.bin on my $PATH. Now when I launch $ appname, pipenv creates a new virtual environment in the ~/.bin folder and complains about missing dependencies, all instead of following through into the actual location of the script. Is there a way to overcome this? Or maybe a better way to achieve what I want?
score: 1
type: Question
tagged with: pipenv
has comment: http://stackoverflow.com/comment/95154556
linked to: http://stackoverflow.com/q/48451402
tagged with: shebang
has title: Running pipenv environment via $PATH symlink to executable .py file
tagged with: symlink
has comment: http://stackoverflow.com/comment/101155662
answer count: 1
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/51986874

http://stackoverflow.com/a/51964263
score: 12
has comment: http://stackoverflow.com/comment/120709776
type: Answer
answers question: http://stackoverflow.com/q/51964001
has comment: http://stackoverflow.com/comment/120709436
accepted answer of: http://stackoverflow.com/q/51964001
has comment: http://stackoverflow.com/comment/90879391
upvote count: 12
downvote count: 0
has comment: http://stackoverflow.com/comment/120697731
type: AcceptedAnswer
has body: There are two issues here: Your generator expression allows you to lazily iterate dataframe objects. You can't export a generator expression to an Excel file. Your sheet_name parameter is a constant. To export to multiple worksheets, you need to specify a different name for each worksheet. You can use a simple for loop for this purpose: writer = pd.ExcelWriter('out.xlsx', engine='xlsxwriter') df_from_each_file = (pd.read_csv(f) for f in all_files) for idx, df in enumerate(df_from_each_file): df.to_excel(writer, sheet_name='data{0}.csv'.format(idx)) writer.save() Your worksheets will be named data0.csv, data1.csv, etc. If you need the filename as your sheet name, you can restructure your logic and use the os module to extract the filename from path: import os writer = pd.ExcelWriter('out.xlsx', engine='xlsxwriter') for f in all_files: df = pd.read_csv(f) df.to_excel(writer, sheet_name=os.path.basename(f)) writer.save()

http://stackoverflow.com/q/51991089
tagged with: python
has title: Generate many curl commands through binary file
type: AnsweredQuestion
has body: I have a binary data file called image_info_binary.data, and I'd like to download many FITS images based on the information in the lines of this file. If I load this file into Python with the pickle module and print a single element, I get this: import pickle with open('image_info_binary', 'rb') as f: img_info = pickle.load(f) print(img_info[0]) Outputs this string: Object #: 2000073.0 Counter #: 2 Scan ID: 0245 Frame #: 167 Band #: 3 Image Link: http://....fits... #long url There are about 50,000 of these elements, each with different object #, counter #, fits image URL, etc. I would like to go through each of these elements and download each FITS image as: {int(object number)}_{three digit counter}_w{band}.fits. For example, I would want the downloaded image of the above example to be 2000073_002_w3.fits. What is the best way to do this? I know if I was just downloading one image I could simply execute curl -o 2000073_002_w3.fits "url", for example. I'm not sure if generating many of these curl statements is the best way to do this or not. If I could just run a command in the terminal, that'd be great, but I could also use Python (but I feel like a subprocess would probably be slow). Thank you!
has comment: http://stackoverflow.com/comment/90931906
type: Question
accepted answer: http://stackoverflow.com/a/51991476
has comment: http://stackoverflow.com/comment/90931977
score: 0
tagged with: linux
tagged with: binaryfiles
answer count: 1
tagged with: download
has comment: http://stackoverflow.com/comment/90932057
has answer: http://stackoverflow.com/a/51991476
tagged with: pickle

http://stackoverflow.com/a/51958809
upvote count: 1
downvote count: 1
answers question: http://stackoverflow.com/q/51958696
has body: If you want to be compatible with Python of version prior to 3.5 or don't want the overhead of using regex, you can use the following dict comprehension instead: t = ['id', 'hostname', 'personality', 'action', 'operational', 'availability'] l = ['| 1 | hostname_1 | master | unlocked | enabled | available |', '| 2 | hostname_2 | slave | unlocked | enabled | available |', '| 3 | hostname_3 | slave | unlocked | enabled | available |'] print({t[0]: {i[0]: dict(zip(t[1:], i[1:])) for i in [[v.strip() for v in i.strip('|').split('|')] for i in l]}}) This outputs: {'id': {'1': {'hostname': 'hostname_1', 'personality': 'master', 'action': 'unlocked', 'operational': 'enabled', 'availability': 'available'}, '2': {'hostname': 'hostname_2', 'personality': 'slave', 'action': 'unlocked', 'operational': 'enabled', 'availability': 'available'}, '3': {'hostname': 'hostname_3', 'personality': 'slave', 'action': 'unlocked', 'operational': 'enabled', 'availability': 'available'}}}
score: 0
has comment: http://stackoverflow.com/comment/90868162
type: AcceptedAnswer
type: Answer
accepted answer of: http://stackoverflow.com/q/51958696

http://stackoverflow.com/q/51958177
accepted answer: http://stackoverflow.com/a/51958422
upvote count: 3
tagged with: matplotlib
downvote count: 1
type: Question
answer count: 2
has title: Unable to remove yticks from pyplot subplots
has answer: http://stackoverflow.com/a/51958422
favorite count: 0
possible better answer: http://stackoverflow.com/a/51958243
has answer: http://stackoverflow.com/a/51958243
tagged with: python
has body: I created a subplot using matplotlib.pyplot. Even as I set the tick labels to empty using: plt.xticks([ ]) plt.yticks([ ]) How can I remove these? I am new to Python and any help on the matter is appreciated.
score: 2
type: AnsweredQuestion

http://stackoverflow.com/q/52101888
tagged with: pandas
answer count: 0
type: UnansweredQuestion
tagged with: python
has body: I am able to develop a code with the help of experts from StackOverflow. However, I got stuck in adding new attributes from 'numpy.polyfit' function and export the data to a data frame. My Requirements: 1.Add Intercept, rvalue, pvalue, stderr in addition to slope (from ployfit function) Import the data into core data frame. Sample Code: year = [1993, 1994, 1995, 1993, 1994, 1995] category =['rev', 'rev', 'exp', 'exp', 'net', 'net'] values = [200, 250, 42, 32, 9, 4] df1 = pd.DataFrame({'year': year, 'category': category,'values': values}) cats = df1.category.unique().tolist() slopes = [np.polyfit(df1.loc[df1.category == cat, "year"], df1.loc[df1.category == cat, "values"], 1)[0] for cat in cats] for cat, slope in zip(cats, slopes): print("{} slope/trend: {:.3f}".format(cat, slope)) Thank you so much.
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/91156299
has comment: http://stackoverflow.com/comment/91160112
has title: numpy.polyfit data export into Python pandas.core.frame
score: 0

http://stackoverflow.com/a/60268912
type: Answer
answers question: http://stackoverflow.com/q/52095337
score: 5
upvote count: 5
has body: Here is my solution: import matplotlib.pyplot as plt x1 = [1,2,3,4,5,6,7,8,9] x2= [0,1,0,0,1,0,1,1,0] x3= range(-10,0) # frameon=False removes frames # fig, (ax1,ax2, ax3) = plt.subplots(nrows=3, sharex=True, subplot_kw=dict(frameon=False)) fig, (ax1,ax2, ax3) = plt.subplots(nrows=3, sharex=True) # remove vertical gap between subplots plt.subplots_adjust(hspace=.0) ax1.grid() ax2.grid() ax3.grid() ax1.plot(x1) ax2.plot(x2) ax3.plot(x3) Without frames subplot_kw=dict(frameon=False):
downvote count: 0

http://stackoverflow.com/q/51991503
linked to: http://stackoverflow.com/q/16439301
answer count: 1
has comment: http://stackoverflow.com/comment/90933782
tagged with: inheritance
favorite count: 0
tagged with: defaultdict
has title: Can't pickle recursive nested defaultdict
has comment: http://stackoverflow.com/comment/90998154
tagged with: pickle
tagged with: python
has answer: http://stackoverflow.com/a/52026436
accepted answer: http://stackoverflow.com/a/52026436
score: 2
upvote count: 3
has comment: http://stackoverflow.com/comment/90994992
downvote count: 1
has comment: http://stackoverflow.com/comment/90934008
type: AnsweredQuestion
type: Question
has body: I have a recursive nested defaultdict class defined as from collections import defaultdict class NestedDict(defaultdict): def __init__(self): super().__init__(self.__class__) sitting in a nested_dict.py file. When I try to pickle it, e.g. import pickle from nested_dict import NestedDict d = NestedDict() pickle.loads(pickle.dumps(d)) I get TypeError: __init__() takes 1 positional argument but 2 were given. What's exactly happening here?

http://stackoverflow.com/comment/90887845
type: Comment
has text: Have you tried finding out what attributes/methods the `cell.Characters` objects have? Either through documentation or `dir(cell.Characters)`.
score: 0
comment on: http://stackoverflow.com/q/51968724
type: QuestionComment

http://stackoverflow.com/comment/90876019
score: 0
has text: @Alex No. As mentioned in another comment, function returns normalized eigenvectors. Scipy docs also mentions about normalized eigenvectors.
comment on: http://stackoverflow.com/q/51962506
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52017438
has comment: http://stackoverflow.com/comment/90985211
favorite count: 0
has comment: http://stackoverflow.com/comment/90984939
tagged with: python-3.x
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/csv
has comment: http://stackoverflow.com/comment/90984968
tagged with: python
has comment: http://stackoverflow.com/comment/90984957
has body: I have an app that allows a user to update an excel(.xlsx) or csv (.csv) file. I use pandas.read_excel and pandas.read_csv to read the files. This works great for numeric values. However when a column has 80%, it is parsed as 0.8. Is there a way of ignoring percentages when reading the csv or the excel files? So that a cell with 80% is parsed as 80 in the dataframe. I have thought of checking if all the values in the dataframe are less than 1 but it will introduce a bug because if the user inputs zeros in the excel file (which is possible), it will be interpreted as percentage which will make it be multiplied by 100.
has comment: http://stackoverflow.com/comment/90984886
score: 2
downvote count: 0
has answer: http://stackoverflow.com/a/52017707
has comment: http://stackoverflow.com/comment/90985140
tagged with: excel
has comment: http://stackoverflow.com/comment/90985096
type: Question
has comment: http://stackoverflow.com/comment/90985310
has comment: http://stackoverflow.com/comment/90985022
has comment: http://stackoverflow.com/comment/90985814
upvote count: 2
has comment: http://stackoverflow.com/comment/90985192
has comment: http://stackoverflow.com/comment/90985328
tagged with: pandas
has title: Pandas - How to ignore percentages in read_excel and read_csv
answer count: 1
has comment: http://stackoverflow.com/comment/90985303

http://stackoverflow.com/comment/90995302
comment on: http://stackoverflow.com/a/52022465
type: Comment
score: 0
type: AnswerComment
has text: hi i added the question, sorry to bother you

http://stackoverflow.com/a/52017457
has comment: http://stackoverflow.com/comment/90985037
type: Answer
has comment: http://stackoverflow.com/comment/90985219
accepted answer of: http://stackoverflow.com/q/52017226
downvote count: 0
answers question: http://stackoverflow.com/q/52017226
score: 1
has comment: http://stackoverflow.com/comment/90985181
has comment: http://stackoverflow.com/comment/90985944
has body: When you merge your title and subject into the string you have to make the second piece raw again r''' bla bla '''+ str(title) + r''' bla bla''' The second "r" is missing, twice in your example. You should consider merging using str.format().
upvote count: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/90990795

http://stackoverflow.com/comment/94876000
type: Comment
score: 0
has text: Very well written!
type: AnswerComment
comment on: http://stackoverflow.com/a/54019712

http://stackoverflow.com/comment/91093869
type: QuestionComment
type: Comment
has text: Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/178999/discussion-between-mohit-and-vineeth-sai).
comment on: http://stackoverflow.com/q/52070514
score: 0

http://stackoverflow.com/q/52089678
has answer: http://stackoverflow.com/a/52089969
tagged with: pandas
upvote count: 1
has answer: http://stackoverflow.com/a/52089940
favorite count: 0
has title: How to add custom strings to legend of count_value plots in pandas?
linked to: http://stackoverflow.com/q/42466708
type: UnansweredQuestion
tagged with: python
has body: I have a dataframe column on which I applied value_counts to find number of occurances of each entity. I am trying to plot it as a bar graph. It plot with each entity on the x-axis and their count on y-axis. How can I add a legend so that each entity on x axis will be mapped to a string. The result of the value_counts is like this: df.Column.value_counts() 10.0 1094 2154.0 697 23.0 202 I need a legend which will replace my entities with strings. 10 - Alpha 2154 - Beta 23 - Gamma The number of entities may vary. I have a list of strings for each entity. So I am looking to replace my entities by strings from the list. I want to replace it only on the legend. The graph should have entities on x-axis and the legend should have equivalent strings from the list.
downvote count: 0
score: 1
tagged with: matplotlib
type: Question
answer count: 2

http://stackoverflow.com/comment/91159820
type: QuestionComment
has text: Why use a `defaultdict(bool)` instead of a set?
type: Comment
comment on: http://stackoverflow.com/q/52104310
score: 4

http://stackoverflow.com/a/52027825
answers question: http://stackoverflow.com/q/52001694
downvote count: 0
has body: In the snippet given the issue is that Quart has no werkzeug logger, it has quart.app and quart.serving so the likely equivalent is to do logging.getLogger('quart.serving').setLevel(logging.ERROR) Note, this question was asked as a Quart issue, and I am the Quart author.
type: Answer
upvote count: 1
score: 1

http://stackoverflow.com/comment/91161559
type: Comment
score: 0
type: AnswerComment
has text: @curious_cosmo, no, this solves the ram issue. `arr` is memmapped so assignments to it will be written to disk.
comment on: http://stackoverflow.com/a/52103968

http://stackoverflow.com/comment/90987038
has text: Normally you'd probably use `git` for version control. There's no need to keep updating module names for each change, the imports generally stay the same and the contents of those modules are updated in a reversible way
type: Comment
comment on: http://stackoverflow.com/q/52018403
score: 1
type: QuestionComment

http://stackoverflow.com/comment/91021453
type: Comment
type: QuestionComment
has text: @SashaTsukanov both with return 0 and without it cause the program to crashes. if i remove the return 0 statement when the program doesn't crash i need to CTRL+C to close it while with return 0 i get press enter to close and that's why i keep it
comment on: http://stackoverflow.com/q/52035388
score: 0

http://stackoverflow.com/comment/91151558
has text: Here's some resources that contain the answers to your questions: [Modules](https://docs.python.org/3/tutorial/modules.html) is about structuring python projects, [Multithreading](https://www.tutorialspoint.com/python/python_multithreading.htm) is about running multiple sections of your code at once, and [os.system](https://docs.python.org/2/library/os.html#os.system) tells you how to start another program separately from your main program.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52099449

http://stackoverflow.com/a/52081512
type: Answer
answers question: http://stackoverflow.com/q/52081174
score: 0
has body: A solution a little bit easier to understand if that's something you want, with no dependencies. a = '01/08/2017' b = '28/08/2017' c = ['01/08/2017', '20/08/2017', '21/08/2017', '22/08/2017', '23/08/2017', '24/08/2017', '25/08/2020', '26/08/2020', '27/08/2020', '28/08/2020'] a = a.split("/") #break requirements into components b = b.split("/") answerList = [] # form the final list structure for i in range(0, len(c)): #iterate through all of c cHolder = c[i].split("/") #break c into components componentValidator = 0 # simple all-or-nothing counter for j in range(3): # go through every component if (int(a[j]) &lt;= int(cHolder[j]) &lt;= int(b[j])): # check ranges componentValidator = componentValidator + 1 # for each component if componentValidator == 3: # if all correct answerList.append(c[i]) # add to final answers print(answerList) # print final answers Output: ['01/08/2017', '20/08/2017', '21/08/2017', '22/08/2017', '23/08/2017', '24/08/2017']

http://stackoverflow.com/a/52043112
type: Answer
upvote count: 2
downvote count: 1
score: 1
has body: Use re.search Ex: import re revenue = "Revenue;;Item,Johnver,Vanston,Danbree,Vansey,Mundyke;Tea,190,140,1926,14,143;Coffee,325,19,293,1491,162;Water,682,14,852,56,659;Milk,829,140,609,120,87;;Expenses;;Item,Johnver,Vanston,Danbree,Vansey,Mundyke;Tea,120,65,890,54,430;Coffee,300,10,23,802,235;Water,50,299,1290,12,145;Milk,67,254,89,129,76;;" revenue = re.search(r"(?&lt;=Revenue;;).*(?=;E)", revenue) print(revenue.group()) Output: Item,Johnver,Vanston,Danbree,Vansey,Mundyke;Tea,190,140,1926,14,143;Coffee,325,19,293,1491,162;Water,682,14,852,56,659;Milk,829,140,609,120,87;
answers question: http://stackoverflow.com/q/52043077
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/52043077

http://stackoverflow.com/comment/91074909
type: Comment
comment on: http://stackoverflow.com/a/52049609
score: 0
type: AnswerComment
has text: Ah, that makes sense! Thank you! This kind of works, but for some reason I'm getting a gap of 3-4 '0' cells rather than the expected 5. Maybe I'm defining the constraints wrong?

http://stackoverflow.com/a/73517776
answers question: http://stackoverflow.com/q/52075131
score: 0
type: Answer
has body: Nice and effective solution given by @MikeS; thanks ! Nowadays, I would reformulate it as follows: from django.core.cache import cache from django.template.loader import render_to_string @register.simple_tag def user_info(context, username, size=40): html = cache.get(username) if not html: user = User.objects.get(pk=username) html = render_to_string( 'app/user_info.html', { 'user': user, 'size': size, } ) cache.set(username, html, timeout=60) return html

http://stackoverflow.com/a/52339259
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51974845
score: 6
type: Answer
upvote count: 6
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/51974845
has body: You have to overload Gtk.TreeDragSource.do_row_draggable(). class MyTreeStore (Gtk.TreeStore): # ... def do_row_draggable(self, path): # do your decision here return True # draggable return False # NOT draggable

http://stackoverflow.com/a/52045268
type: AcceptedAnswer
downvote count: 0
has body: The initialisation of the K-Means algorithm is not deterministic. If you're using scikit-learn's KMeans, then you can either provide your own initialisation (init=...), or you can provide a random seed, so that the same random numbers are generated every time (random_state=42).
type: Answer
accepted answer of: http://stackoverflow.com/q/52045202
answers question: http://stackoverflow.com/q/52045202
score: 4
upvote count: 4

http://stackoverflow.com/q/52108019
tagged with: python
linked to: http://stackoverflow.com/q/51657805
favorite count: 0
tagged with: docker-image
has title: installing scikit-learn Docker image problem
upvote count: 3
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/67947327
has body: im trying to install scikit-learn with docker image! its failed and here is the error: ImportError: Numerical Python (NumPy) is not installed. scikit-learn requires NumPy &gt;= 1.8.2. Installation instructions are available on the scikit-learn website: http://scikit-learn.org/stable/install.html Failed building wheel for scikit-learn but in logs just before of scikit-learn pip trying to isntall numpy==1.9.0 and log says its DONE, I even try to install with : scikit-learn[alldeps]==0.19.1 but nothing is changed! same error my hole docker image is working well without scikit-learn, my app is running except the scikit-learn parts! I tried to change the version and install the last version: scikit-learn[alldeps] and its ok but I have some incompatibility in my application I need to use the 0.19.1 version, not 0.19.2! ps: my requirements.txt file is working in my python3 venv (mac and ubuntu)!!!
tagged with: dockerfile
score: 3
has comment: http://stackoverflow.com/comment/91166922
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/91169232
downvote count: 0
tagged with: scikit-learn
has comment: http://stackoverflow.com/comment/91178106
answer count: 1

http://stackoverflow.com/q/51997932
downvote count: 0
favorite count: 0
tagged with: docker
has title: Run python test inside docker and get the exit code outside on host machine
tagged with: python
upvote count: 6
type: UnansweredQuestion
score: 6
has answer: http://stackoverflow.com/a/51998215
tagged with: teamcity
has comment: http://stackoverflow.com/comment/90945109
type: Question
has comment: http://stackoverflow.com/comment/90945079
has body: I have this docker compose file version: "2" services: abc_python_test: build: "python" container_name: "abc-python-test" volumes: - "../:/abc/" working_dir: "/abc" command: "sh -c 'python3 -m unittest tests/calculator.py'" I have a following Makefile test: cp config/config-$(env).cfg config/config.cfg docker-compose -f environment/test.yml up --build I run this Makefile in one of a build step we have in our CI. Problem is, the test run and fails, the python3 process get the exit code 1. However, once the python3 process get finished the container gets down. But my host machine shows the status code 0. This leads to get my build pass even the tests are failing. How can I forward this python3 exit code to my main process so that it knows that the tests got failed. Thanks PS: We have old docker compose version that doesn't come with the --exit-code-from flag
tagged with: docker-compose
tagged with: continuous-integration
answer count: 1

http://stackoverflow.com/comment/91070095
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52059849
has text: you can think about what you would do if you have 100 coefficients.
score: 0

http://stackoverflow.com/q/52034485
has comment: http://stackoverflow.com/comment/91020000
has comment: http://stackoverflow.com/comment/91018974
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91022678
has comment: http://stackoverflow.com/comment/91019726
has comment: http://stackoverflow.com/comment/91025812
has comment: http://stackoverflow.com/comment/91022561
has comment: http://stackoverflow.com/comment/91018911
has comment: http://stackoverflow.com/comment/91025258
answer count: 0
has comment: http://stackoverflow.com/comment/91022484
has comment: http://stackoverflow.com/comment/91026800
linked to: http://stackoverflow.com/q/2022031
has comment: http://stackoverflow.com/comment/91022224
has comment: http://stackoverflow.com/comment/91020555
has comment: http://stackoverflow.com/comment/91025997
has comment: http://stackoverflow.com/comment/91019188
has comment: http://stackoverflow.com/comment/91026643
type: Question
has comment: http://stackoverflow.com/comment/91019844
has comment: http://stackoverflow.com/comment/91023238
tagged with: python
has body: I have the this code (Python 3.5): datarALL = [] with ThreadPoolExecutor(max_workers=os.cpu_count()) as executor: futh = [(executor.submit(self.getdata2, page, hed, data, apifolder,additional)) for page in pages] for data in as_completed(futh): datarALL = datarALL + data.result() return datarALL This creates threads, execute a function and combine the results to a list. When I execute on small scale it works great but when the number of pages is large the scripts writes: Killed When I monitor it using htop i see the Killed is due to memory problems. I tried to convert the datarALL = datarALL + data.result() to writing on a file so each finished thread will have the results on disk rather than on the memory. This is what I did: with ThreadPoolExecutor(max_workers=os.cpu_count()) as executor: futh = [(executor.submit(self.getdata2, page, hed, data, apifolder, additional)) for page in pages] for data in as_completed(futh): datarALL = [data.result()] with open("test.txt", "wb") as fp: pickle.dump(datarALL, fp) with open("test.txt", "rb") as fp: # Unpickling b = pickle.load(fp) return b But the memory isn't cleared and the script still killed. What can I so to solve such problem? I need this script to support handling unknown amount of data. Edit: adding getdata2 code: def getdata2(self, page, hed, data, apifolder, additional): tries = 10 for n in range(tries): try: value_limit = self.config._page_limit # limit of records allowed per page value_offset = page * value_limit datarALL = [] url = 'http://www.mywebsite.com/{2}?WithTotal=true&amp;cultureid=2&amp;offset={0}&amp;limit={1}{3}'.format( value_offset, value_limit, apifolder, additional) print ("Generate page: #{0} run #{1} with URL: {2}".format(page, n, url)) responsedata = requests.get(url, data=data, headers=hed, verify=False) if responsedata.status_code == 200: # 200 for successful call responsedata = responsedata.text jsondata = json.loads(responsedata) if "results" in jsondata: if jsondata["results"]: datarALL =…
has comment: http://stackoverflow.com/comment/91020069
has comment: http://stackoverflow.com/comment/91019153
has comment: http://stackoverflow.com/comment/91021803
score: 0
has title: script killed due to lack of memory
has comment: http://stackoverflow.com/comment/91018957
has comment: http://stackoverflow.com/comment/91019345
has comment: http://stackoverflow.com/comment/91022608
has comment: http://stackoverflow.com/comment/91019309
has comment: http://stackoverflow.com/comment/91023600

http://stackoverflow.com/q/51999199
type: Question
has comment: http://stackoverflow.com/comment/92834800
has answer: http://stackoverflow.com/a/51999781
upvote count: 2
answer count: 2
linked to: http://stackoverflow.com/q/50374139
favorite count: 0
has body: I am trying to crop images (thousands of images) on button click bellow is my code! @background(schedule=5) def initialize(): allimages = [] number = 0 if not os.path.exists('thumbnails'): os.makedirs('thumbnails') path = '/Users/shoaibrafa/Data/*.jpg' for image in glob.glob(path): print(image,"=====",number) im = Image.open(image) im.thumbnail((512, 512), Image.ANTIALIAS) im.save("thumbnails/" + os.path.basename(image), "JPEG") number = number + 1 but I face two problems: when clicking the button from the template gives Object of type 'WSGIRequest' is not JSON serializable error! if I call the method initialize() directly when the page loads the background task starts cropping the images, but when the all images are cropped it starts again from beginning cropping the images and continues for ever. What I need is to crop the images and end the background task. bellow is my template: {% extends 'layout.html' %} {% block title %} Login {% endblock %} {% block content %} Initialize... {% endblock %} thanks in advance
has comment: http://stackoverflow.com/comment/90947748
type: UnansweredQuestion
has title: How to run Django background task only once
tagged with: django
tagged with: python
score: 2
downvote count: 0
tagged with: background-task
has answer: http://stackoverflow.com/a/52963860
has comment: http://stackoverflow.com/comment/90948245

http://stackoverflow.com/comment/90890197
score: 0
type: Comment
type: QuestionComment
has text: posting the relevant-to-the question code would help us help you. Also, as a sidenote, keep in mind that your functions do not `return` anything so far.
comment on: http://stackoverflow.com/q/51969836

http://stackoverflow.com/comment/91031025
comment on: http://stackoverflow.com/q/52040264
has text: @floydya it's mutable so it doesn't matter, though it's bad practice
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52106040
has comment: http://stackoverflow.com/comment/91172459
answer count: 0
score: 1
upvote count: 1
tagged with: scrapy
has body: Well lets say you wanted to crawl the spider....and does exist with the same class another text...how can i say to create new column like ProductNr+1 each time does exist same element? Here's the code: import scrapy class CarbotSpider(scrapy.Spider): name = 'CarBot' start_urls = [ 'https://www.car.gr/parts/view/13073027-suspension-steering-springs-optimal-germany', 'https://www.car.gr/parts/view/7877992-suspension-steering-lowering-springs', 'https://www.car.gr/parts/view/7751931-suspension-steering-regulated-suspension', ] def parse(self, response): self.log('I Just Visited: ' + response.url) for content in response.css('div.bgcolor'): row = content.css('div.row') table1 = row.css('table.table.table-striped.table-condensed') item = { 'CurrentUrl' : response.url, 'Title' : content.css('span.p_t.title-inside::text').extract(), 'Price' : row.css('span.p_p::text').extract(), 'BrandName' : row.css('span[itemprop="brand"] &gt; span[itemprop="name"]::text').extract(), 'Model' : row.css('li &gt; span[itemprop="model"]::text').extract(), 'ReleaseDate' : row.css('li &gt; span[itemprop="releaseDate"]::text').extract(), 'ToDate' : row.css('li[itemprop="isAccessoryOrSparePartFor"]::text').extract(), 'NumberPage' : row.css('h3.details-header::text')[0].extract(), 'URL' : row.css('td[itemprop="url"]::text').extract(), 'Thumpnail' : row.css('img.img-thumbnail::attr(src)').extract(),} if row.css('td[itemprop="productID"]'): item['ProductNr1'] = row.css('td[itemprop="productID"]::text').extract() item['ProductNr2'] = row.css('td[itemprop="productID"]::text')[1].extract() item['ProductNr3'] = row.css('td[itemprop="sku"]::text').extract() yield item
type: Question
has title: Python - Scrapy add new columns each time exist same element
downvote count: 0
favorite count: 0
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/q/52093998
has comment: http://stackoverflow.com/comment/91137970
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91139182
has title: Unable to strptime formatting for this format 2018-07-26 12:52:18.679605-07:53
has body: I am using Python version 3.5. I am formatting the string 2018-07-26 12:52:18.679605-07:53 using this datetime.datetime.strptime(2018-07-26 12:52:18.679605-07:53, "%Y-%m-%d %H:%M:%S.%f%z") But it keeps on giving this error time data '2018-07-26 12:52:18.679605-07:53' does not match format '%Y-%m-%d %H:%M:%S.%f-%Z' Please help.
has comment: http://stackoverflow.com/comment/91138149
tagged with: date
has comment: http://stackoverflow.com/comment/91138116
type: Question
has comment: http://stackoverflow.com/comment/91138256
has answer: http://stackoverflow.com/a/52094939
score: 0
tagged with: strptime
answer count: 1
tagged with: python

http://stackoverflow.com/a/52104089
answers question: http://stackoverflow.com/q/52075515
type: Answer
has body: Python threads, how do Event and Queue work together? They don't. You can use Events without queues and queues without Events, there's no dependency on each other. Your example just happens to use both. My friend argues that sole purpose of Event is to block the main thread until the other thread performs set operation. Is that true? Calling .wait() on an Event-object will block any calling thread until the internal flag is .set(). If you look at the source for Event, you'll find that Events just consist of a Condition variable with a lock and a boolean flag + methods to handle and communicate (to waiting threads) state changes of that flag. class Event: """Class implementing event objects. Events manage a flag that can be set to true with the set() method and reset to false with the clear() method. The wait() method blocks until the flag is true. The flag is initially false. """ def __init__(self): self._cond = Condition(Lock()) self._flag = False ... How can we watch thread execution? A simple method would be to apply some sort of utility function that prints out what you're interested in, for example: def print_info(info=""): """Print calling function's name and thread with optional info-text.""" calling_func = sys._getframe(1).f_code.co_name thread_name = threading.current_thread().getName() print(f"&lt;{thread_name}, {calling_func}&gt; {info}", flush=True) Another possibility would be to use logging like in this answer. Not sure what Beazly wanted to demonstrate with the code you showed, but it deems a little over-engineered to me for this simple task. Involving Events here on top is unnecessary when you already use a queue. You can initialize thread termination by passing a sentinel-value. Here's a simplified version of your example with sentinel ('STOP') and some info-prints with print_info from above: import sys import time import threading from queue import Queue class Actor(threading.Thread): def __init__(self): super().__init__(target=self.run) self.queue…
accepted answer of: http://stackoverflow.com/q/52075515
upvote count: 4
type: AcceptedAnswer
downvote count: 0
score: 4

python-requests
tags question: http://stackoverflow.com/q/52100377
tags question: http://stackoverflow.com/q/52107447
tags question: http://stackoverflow.com/q/52006968
tags question: http://stackoverflow.com/q/52084829
tags question: http://stackoverflow.com/q/52017598
tags question: http://stackoverflow.com/q/52043378
type: Tag
tags question: http://stackoverflow.com/q/52060402
tags question: http://stackoverflow.com/q/52032661
tags question: http://stackoverflow.com/q/52044489
tags question: http://stackoverflow.com/q/52087546
tags question: http://stackoverflow.com/q/52068920
tags question: http://stackoverflow.com/q/52109055
tags question: http://stackoverflow.com/q/51973067
tags question: http://stackoverflow.com/q/52013628
tags question: http://stackoverflow.com/q/51987299
tags question: http://stackoverflow.com/q/51992959
tags question: http://stackoverflow.com/q/52067255
tags question: http://stackoverflow.com/q/51997608
tags question: http://stackoverflow.com/q/51968109
tags question: http://stackoverflow.com/q/52064626
tags question: http://stackoverflow.com/q/51986077
tags question: http://stackoverflow.com/q/51968850
tags question: http://stackoverflow.com/q/52096961
tags question: http://stackoverflow.com/q/52073538
tags question: http://stackoverflow.com/q/52099923
tags question: http://stackoverflow.com/q/52033281
tags question: http://stackoverflow.com/q/52059566
tags question: http://stackoverflow.com/q/52099417
tags question: http://stackoverflow.com/q/52067425
tags question: http://stackoverflow.com/q/51976294
tags question: http://stackoverflow.com/q/52103302
tags question: http://stackoverflow.com/q/52048112
tags question: http://stackoverflow.com/q/52048303
tags question: http://stackoverflow.com/q/52040904
tag name: python-requests
tags question: http://stackoverflow.com/q/51957005
tags question: http://stackoverflow.com/q/52019531
tags question: http://stackoverflow.com/q/51977245
tags question: http://stackoverflow.com/q/52065496
tags question: http://stackoverflow.com/q/52082496
tags question: http://stackoverflow.com/q/51991891
tags question: http://stackoverflow.com/q/51991069

http://stackoverflow.com/a/52100453
has comment: http://stackoverflow.com/comment/91186480
has comment: http://stackoverflow.com/comment/91157599
score: 4
type: AcceptedAnswer
downvote count: 1
accepted answer of: http://stackoverflow.com/q/52096473
upvote count: 5
answers question: http://stackoverflow.com/q/52096473
type: Answer
has comment: http://stackoverflow.com/comment/91167589
has comment: http://stackoverflow.com/comment/91190949
has body: You want the .update() method: query = User.update(validated=True).where(User.username.in_(usernames_to_update)) query.execute() Edit: so you want to conditionally set the value during an update. You can use the Case helper. Untested: some_value_1 = 'foo' some_value_2 = 'bar' case_stmt = Case(User.type, [ ('type_1', some_value_1), ('type_2', some_value_2)]) query = User.update(some_field=case_stmt).where(User.username.in_(list_of_usernames)) query.execute() Docs can be found here: http://docs.peewee-orm.com/en/latest/peewee/api.html#Case

http://stackoverflow.com/q/52050755
favorite count: 0
tagged with: python
has answer: http://stackoverflow.com/a/52050797
type: AnsweredQuestion
upvote count: 0
has body: I want to ignore "Not Found: /api" and return all GET and POST calls within the last n seconds entered Below is how my log file looks: Not Found: /api [22/Aug/2018 10:07:14] "GET /api HTTP/1.1" 404 2318 Not Found: /api [22/Aug/2018 10:30:30] "GET /api HTTP/1.1" 404 2318 Not Found: /api [22/Aug/2018 10:30:33] "GET /api HTTP/1.1" 404 2318 [22/Aug/2018 10:37:08] "POST /api/entity/ HTTP/1.1" 201 83 [22/Aug/2018 10:37:40] "GET /api/entity/ HTTP/1.1" 200 412 [22/Aug/2018 10:37:41] "POST /api/datasets/ HTTP/1.1" 201 115
has title: Retrieve records from a log file for last n seconds in python
tagged with: file
tagged with: logging
type: Question
has comment: http://stackoverflow.com/comment/91051707
score: -2
possible better answer: http://stackoverflow.com/a/52050797
answer count: 2
downvote count: 2
has answer: http://stackoverflow.com/a/52051226
accepted answer: http://stackoverflow.com/a/52051226
has comment: http://stackoverflow.com/comment/91052096

http://stackoverflow.com/q/52008104
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/52013678
tagged with: timeout
has title: coreutils timeout in a bash script not transparent for the application
has comment: http://stackoverflow.com/comment/90973215
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/52013678
has comment: http://stackoverflow.com/comment/90970566
has body: I have an issue with executing application via /usr/bin/timeout in a bash script. In this specific case this is a simple python fabric script (fabric version 1.14) In order to install this version of fabric library run: pip install "fabric&lt;2" There is no reproduction with new fabric 2.x. Shell script causing issue: [root@testhost:~ ] $ cat testNOK.sh #!/bin/bash timeout 10 ./test.py echo "RETCODE=$?" [root@testhost:~ ] $ ./testNOK.sh [localhost] run: echo Hello! RETCODE=124 [root@testhost:~ ] $ Similar script (without timeout) working fine [root@testhost:~ ] $ cat testOK.sh #!/bin/bash ./test.py echo "RETCODE=$?" [root@testhost:~ ] $ ./testOK.sh [localhost] run: echo Hello! [localhost] out: Hello! [localhost] out: RETCODE=0 [root@testhost:~ ] $ Manual execution from bash commandline with timeout working fine: [root@testhost:~ ] $ timeout 10 ./test.py &amp;&amp; echo "RETCODE=$?" [localhost] run: echo Hello! [localhost] out: Hello! [localhost] out: RETCODE=0 [root@testhost:~ ] $ Python2.7 test.py script [root@testhost:~ ] $ cat test.py #!/usr/bin/python from fabric.api import run, settings with settings(host_string='localhost', user='root', password='XXXXX'): run('echo Hello!') [root@testhost:~ ] $ I have observed the same behavior on different Linux distributions. Now the question is why application executed via timeout within bash script behaves in a different way and what would be the best solution to this issue?
tagged with: terminal
score: 0
tagged with: linux
tagged with: bash
has comment: http://stackoverflow.com/comment/90969330
has comment: http://stackoverflow.com/comment/90968966
possible better answer: http://stackoverflow.com/a/52008195
has answer: http://stackoverflow.com/a/52008195
tagged with: python

http://stackoverflow.com/q/51981630
tagged with: python-3.x
has answer: http://stackoverflow.com/a/51981749
has title: How can I do a better curve fitting with a gaussian function like this?
tagged with: curve-fitting
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90913276
accepted answer: http://stackoverflow.com/a/51981749
type: Question
tagged with: gaussian
score: 4
upvote count: 4
downvote count: 0
answer count: 1
has body: I have data and I am fitting the data with a gaussian curve fitting. The blue bullets are my data. The gaussian starts at zero and look like the red curve. But I want something, that looks more like the green curve. All gaussian curve fitting examples I found at the internet starts at zero. Maybe there is another function that can change the starting y value or something like that? Here's my code so far: import matplotlib.pyplot as plt from scipy.optimize import curve_fit import numpy as np import os import csv path = 'Proben Bilder v06 results' filename = '00_sumListe.csv' # read csv file with scale data x = [] y = [] with open(os.path.join(path, filename), 'r') as csvfile: sumFile = csv.reader(csvfile, delimiter=',') for row in sumFile: id = float(row[0]) sumListe = -float(row[1]) x = np.append(x, id) y = np.append(y, sumListe) y = y-min(y) # x = np.arange(10) # y = np.array([0, 1, 2, 3, 4, 5, 4, 3, 2, 1]) # weighted arithmetic mean (corrected - check the section below) mean = sum(x * y) / sum(y) sigma = np.sqrt(sum(y * (x - mean)**2) / sum(y)) def gauss(x, a, x0, sigma): # x0 = mü return a * np.exp(-(x - x0)**2 / (2 * sigma**2)) popt, pcov = curve_fit(gauss, x, y, p0=[max(y), mean, sigma]) # plt.gca().invert_yaxis() plt.plot(x, y, 'b+:', label='data') plt.plot(x, gauss(x, *popt), 'r-', label='fit') plt.legend() plt.title('Fig. 3 - Fit for Time Constant') plt.xlabel('steps') plt.ylabel('mean value') plt.show() My data is a bit to big to write it here... I can't load it up or can I? Does anyone have a better idea?
favorite count: 0

http://stackoverflow.com/q/52110162
tagged with: pandas
answer count: 1
favorite count: 0
has title: How do I filter out random sample from dataframe in which there are different sample size for each value, in python?
has body: I have to filter out random sample from Data on which: 'a' should have 6 values, 'b' should have 4 values and 'c' should have 7 values randomly. Data Value a 1 a 2 a 3 a 4 a 5 a 6 a 7 a 8 a 9 a 10 b 1 b 2 b 3 b 4 b 5 b 6 b 7 b 8 b 9 c 1 c 2 c 3 c 4 c 5 c 6 c 7 c 8 I want output as: Data Value a 3 a 5 a 7 a 2 a 4 a 9 b 3 b 5 b 7 b 8 c 1 c 3 c 4 c 5 c 6 c 7 c 9
upvote count: 2
tagged with: sample
tagged with: python
type: AnsweredQuestion
score: 2
type: Question
has answer: http://stackoverflow.com/a/52110478
accepted answer: http://stackoverflow.com/a/52110478
downvote count: 0
tagged with: random

http://stackoverflow.com/comment/90875907
score: 0
type: QuestionComment
type: Comment
has text: python version?
comment on: http://stackoverflow.com/q/51962662

http://stackoverflow.com/comment/91026100
type: Comment
type: QuestionComment
has text: I am not sure but please try this once : `a = ' who is Shaka Khan' print tuple(a,)`
comment on: http://stackoverflow.com/q/52037765
score: 0

http://stackoverflow.com/q/52047126
score: 7
has title: Convolutional neural network architectures with an arbitrary number of input channels (more than RGB)
tagged with: image-processing
has comment: http://stackoverflow.com/comment/91045351
has comment: http://stackoverflow.com/comment/91045625
tagged with: tensorflow
type: Question
linked to: http://stackoverflow.com/q/51995977
downvote count: 0
has body: I am very new to image recognition with CNNs and currently using several standard (pre-trained) architectures available within Keras (VGG and ResNet) for image classification tasks. I am wondering how one can generalise the number of input channels to more than 3 (instead of standard RGB). For example, I have an image which was taken through 5 different (optic) filters and I am thinking about passing these 5 images to the network. So, conceptually, I need to pass as an input (Height, Width, Depth) = (28, 28, 5), where 28x28 is the image size and 5 - the number of channels. Any easy way to do it with ResNet or VGG please?
has comment: http://stackoverflow.com/comment/130334978
tagged with: keras
has answer: http://stackoverflow.com/a/54873735
upvote count: 7
accepted answer: http://stackoverflow.com/a/54873735
answer count: 1
favorite count: 0
tagged with: python
type: AnsweredQuestion
tagged with: conv-neural-network
has comment: http://stackoverflow.com/comment/91045434

http://stackoverflow.com/comment/91146627
has text: I will look more into it but I figure a quick and dirty way of doing it but won't be as clean as using loops. I will do some more test!
type: Comment
comment on: http://stackoverflow.com/a/52097863
type: AnswerComment
score: 1

http://stackoverflow.com/q/51970789
favorite count: 0
tagged with: command
has comment: http://stackoverflow.com/comment/90893628
has comment: http://stackoverflow.com/comment/90893604
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/90893605
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90893971
has answer: http://stackoverflow.com/a/51975059
has body: After cloning a Django application, I went to install the virtual environment in terminal. I entered the folder and typed: pip install -r requirements.txt but got the error: -bash: pip: command not found
score: 1
tagged with: pip
upvote count: 1
type: Question
accepted answer: http://stackoverflow.com/a/51975059
has title: Unable install requirements.txt
has comment: http://stackoverflow.com/comment/90892065
has comment: http://stackoverflow.com/comment/90893720
has comment: http://stackoverflow.com/comment/90892051
answer count: 1
downvote count: 0
tagged with: virtualenv

http://stackoverflow.com/comment/91113732
type: QuestionComment
comment on: http://stackoverflow.com/q/52078244
has text: Don´t do 12000 find_one queries, do 1 query to bring all that exist with $in operator
score: 0
type: Comment

http://stackoverflow.com/comment/90887525
type: QuestionComment
has text: Hi Sujit, the list comprehension should be `flattened_list = [y for y in x for x in production companies]` although this would just give you individual characters of each string, so I do not know what you would accomplish with this.
comment on: http://stackoverflow.com/q/51968542
score: 0
type: Comment

http://stackoverflow.com/a/52043068
type: Answer
answers question: http://stackoverflow.com/q/52042695
downvote count: 0
has comment: http://stackoverflow.com/comment/91037031
has comment: http://stackoverflow.com/comment/91037162
score: 1
upvote count: 1
has body: If you send a message "@SomeRole" discord sends it as plain text, the same way if you "@mention" a person, it does the same thing. This is also the case if you sent ":thinking:" it would just send the text. This code will mention a specific user, based on their ID: user = message.guild.members.find("id", "201909896357216256"); await message.guild.send(`${user} is the best!`); If you know the name of your role, and are fine with hard-coding it modRole = msg.channel.server.roles.mention('name', 'Moderator') bot.sendMessage(msg, modRole.mention() + " is anyone here?") To expand on @pkqxdd's if you send "\@SomeRole" yourself (ie, not the bot), you will get the role id. You can then do a similar thing to the code above, by id instead of by name.

http://stackoverflow.com/comment/90966684
comment on: http://stackoverflow.com/a/52007323
score: 0
type: AnswerComment
type: Comment
has text: Do you want to use the pip version in your virtualenv from **outside** your virtualenv???

http://stackoverflow.com/q/52099839
tagged with: https
type: Question
answer count: 1
has answer: http://stackoverflow.com/a/52240940
tagged with: ssl-certificate
has body: I created both certificate file and key file by: openssl req -newkey rsa:2048 -nodes -keyout ho-madad.1.pem -out ho-madad.2.pem I received both file successfuly. I put both files at root of my Python project. In PyCharm I have this code: import os import tornado.ioloop import tornado.web import tornado.httpserver import http.server class MainHandler(tornado.web.RequestHandler): def prepare(self): if self.request.protocol == "http": self.redirect("https://%s" % self.request.full_url() [len("http://"):], permanent=True) def get(self): self.write("Hello, world") application = tornado.web.Application([ (r"/t", MainHandler), ]) http_server = tornado.httpserver.HTTPServer(application, ssl_options = { "certfile": os.path.join("ho-madad.2.pem"), "keyfile": os.path.join("ho-madad.1.pem"), } ) if __name__ == '__main__': http_server.listen(443) tornado.ioloop.IOLoop.instance().start() But when I am running from browser with https://ho-madad/t I am receiving this error: handle: &lt;Handle BaseAsyncIOLoop._handle_events(356, 1)&gt; Traceback (most recent call last): File &gt;"C:\Users\nisim\AppData\Local\Programs\Python\Python36\Lib\asyncio\events.py", line 145, in _run self._callback(*self._args) File "C:\Users\nisim\Documents\EPM&gt;ServerSideCode\EmpServerSide\venv\lib\site-ackages\tornado\platform\asyncio.py", line 122, in _handle_events handler_func(fileobj, events) File "C:\Users\nisim\Documents\EPM &gt;ServerSideCode\EmpServerSide\venv\lib\site-packages\tornado\stack_context.py", line 300, in null_wrapper return fn(*args, **kwargs) File "C:\Users\nisim\Documents\EPM &gt;ServerSideCode\EmpServerSide\venv\lib\site-packages\tornado\netutil.py", line &gt;262, in accept_handler callback(connection, address) File "C:\Users\nisim\Documents\EPM &gt;ServerSideCode\EmpServerSide\venv\lib\site-packages\tornado\tcpserver.py", line &gt;263, in _handle_connection do_handshake_on_connect=False) File "C:\Users\nisim\Documents\EPM &gt;ServerSideCode\EmpServerSide\venv\lib\site-packages\to…
has title: SSL (https) in python tornado
score: 0
upvote count: 1
favorite count: 0
type: UnansweredQuestion
tagged with: python
downvote count: 1
tagged with: tornado

http://stackoverflow.com/q/52044423
has comment: http://stackoverflow.com/comment/91039754
has comment: http://stackoverflow.com/comment/91040015
tagged with: while-loop
type: Question
has comment: http://stackoverflow.com/comment/91041624
has comment: http://stackoverflow.com/comment/91039737
tagged with: python
has comment: http://stackoverflow.com/comment/91040324
has comment: http://stackoverflow.com/comment/91040936
has comment: http://stackoverflow.com/comment/91039956
score: 0
has body: After I build and run the code, "Enter word: " is output once and that's it. Stays blank after entering any word. What am I missing? Here's the code: word = "cool" guess = " " while guess != word: guess = input("Enter word: ") print("you win!")
has comment: http://stackoverflow.com/comment/91039689
answer count: 1
has answer: http://stackoverflow.com/a/52045582
has comment: http://stackoverflow.com/comment/91040990
has comment: http://stackoverflow.com/comment/91039857
type: UnansweredQuestion
has title: While loop is not working as expected
linked to: http://stackoverflow.com/q/10604409
has comment: http://stackoverflow.com/comment/91040357
has comment: http://stackoverflow.com/comment/91041039
has comment: http://stackoverflow.com/comment/91040997
has comment: http://stackoverflow.com/comment/91040362
has comment: http://stackoverflow.com/comment/91040341
has comment: http://stackoverflow.com/comment/91039927
has comment: http://stackoverflow.com/comment/91040627

http://stackoverflow.com/comment/91071537
comment on: http://stackoverflow.com/a/52052194
type: AnswerComment
has text: Done. Marked answer as useful as it solved my problem.
score: 0
type: Comment

http://stackoverflow.com/q/51972807
score: 1
has comment: http://stackoverflow.com/comment/90896216
tagged with: stacked
has comment: http://stackoverflow.com/comment/90896182
type: Question
downvote count: 0
tagged with: pandas
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/51973651
type: UnansweredQuestion
upvote count: 1
tagged with: python
has title: Align stacked bar charts usind pandas
has body: I'm trying to align all of the stacked bar charts having the same index. What's the best way of doing this? This is my code so far: xantho99 = [545/60, 6/60, 1688/60, 44/60] buch99 = [51/60, 2/60, 576/60, 7/60] myco99 = [519/60, 9/60, 889/60, 28/60] cory99 = [247/60, 5/60, 1160/60, 28/60] xantho90 = [545/60, 8/60, 989/60, 27/60] buch90 = [51/60, 3/60, 523/60, 5/60] myco90 = [519/60, 11/60, 802/60, 32/60] cory90 = [247/60, 7/60, 899/60, 27/60] xanthouc = [545/60, 0/60, 5407/60, 193/60] buchuc = [51/60, 0/60, 1014/60, 20/60] mycouc = [519/60, 0/60, 4644/60, 101/60] coryuc = [247/60, 0/60, 2384/60, 77/60] df = pd.DataFrame([xantho, xantho99, xantho90, buch, buch99, buch90, myco, myco99, myco90, cory, cory99, cory90], columns=['Prodigal', 'Cd-hit', 'PSOT', 'Zusammenführen'], index=["X", "X","X", "B", "B","B", "M", "M","M", "C", "C","C"]) df.columns.name = "Abschnitt" current_palette = "blue", "green", "red", "yellow" ax = df.plot.bar(stacked=True, title="Zeitbedarf der einzelnen Abschnitte (Xanthomonas)", xlim=(0, sum(xantho)*1.1), color=current_palette, rot=0) ax.set_xlabel("Zeit in Stunden") Thank You!

http://stackoverflow.com/q/52002542
has comment: http://stackoverflow.com/comment/90959530
tagged with: uwsgi
has answer: http://stackoverflow.com/a/52009145
linked to: http://stackoverflow.com/q/4256107
upvote count: 2
score: 0
downvote count: 2
tagged with: bash
has comment: http://stackoverflow.com/comment/90954209
answer count: 1
has comment: http://stackoverflow.com/comment/90954853
tagged with: flask
favorite count: 0
linked to: http://stackoverflow.com/q/9506437
tagged with: python
type: AnsweredQuestion
has body: Application Details: Ubuntu 16.04 + flask + nginx + uwsgi I am trying to execute a bash command from flask application. @app.route('/hello', methods=('GET', 'POST')) def hello(): os.system('mkdir my_directory') return "Hello" The above code run successfully but doesn't create any directory. Also it creates directory on my local which doesn't have any nginx level setup. I also tried following ways: subprocess.call(['mkdir', 'my_directory']) # Throws Internal server error subprocess.call(['mkdir', 'my_directory'],shell=True) # No error but directory not created subprocess.Popen(['mkdir', 'my_directory']) # Throws Internal server error subprocess.Popen(['mkdir', 'my_directory'],shell=True) # No error but directory not created Do I need any nginx level configuration changes.
has comment: http://stackoverflow.com/comment/90955528
has comment: http://stackoverflow.com/comment/90954288
accepted answer: http://stackoverflow.com/a/52009145
type: Question
has comment: http://stackoverflow.com/comment/90955353
has comment: http://stackoverflow.com/comment/90954326
tagged with: nginx
has title: Executing bash commands from flask application

http://stackoverflow.com/comment/91076469
type: QuestionComment
has text: The issue https://github.com/klen/mixer/issues/98 is still open.
score: 0
comment on: http://stackoverflow.com/q/52059605
type: Comment

http://stackoverflow.com/comment/91142252
type: QuestionComment
has text: Take a look at this post https://medium.com/greyatom/why-how-and-when-to-scale-your-features-4b30ab09db5e
score: 0
comment on: http://stackoverflow.com/q/52096046
type: Comment

http://stackoverflow.com/comment/91167451
has text: Possible duplicate of [beyond top level package error in relative import](https://stackoverflow.com/questions/30669474/beyond-top-level-package-error-in-relative-import)
comment on: http://stackoverflow.com/q/52108309
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/90906210
type: QuestionComment
score: 2
has text: There are nine capturing groups in your regex, therefore there are nine groups in each result from `.findall()`. If you don't want all those groups, change them to non-capturing groups - `(?:...)` instead of `(...)`. Or just remove the parentheses entirely, if they're not actually needed for anything.
comment on: http://stackoverflow.com/q/51978160
type: Comment

http://stackoverflow.com/comment/90949244
type: QuestionComment
has text: So the question is more, what do you want to display? One item, or *all* titems, and in case it is one item, how will you determine *which* item?
comment on: http://stackoverflow.com/q/52000052
score: 0
type: Comment

http://stackoverflow.com/a/52073775
has comment: http://stackoverflow.com/comment/91097426
answers question: http://stackoverflow.com/q/52072773
has comment: http://stackoverflow.com/comment/91098341
has comment: http://stackoverflow.com/comment/91097854
type: Answer
has comment: http://stackoverflow.com/comment/91098388
upvote count: 1
has comment: http://stackoverflow.com/comment/91097561
has body: import pandas from openpyxl import load_workbook book = load_workbook('foo.xlsx') writer = pandas.ExcelWriter('foo.xlsx', engine='openpyxl') writer.book = book writer.sheets = dict((ws.title, ws) for ws in book.worksheets) df.to_excel(writer, "file5",index=False) writer.save() Sheetname can be whatever you want to keep ex: file5
score: 1
has comment: http://stackoverflow.com/comment/91098292
has comment: http://stackoverflow.com/comment/91098222
has comment: http://stackoverflow.com/comment/91097732
downvote count: 0

http://stackoverflow.com/comment/91023341
type: Comment
has text: 1st method seems to be working but I have this problem `ValueError: Error when checking input: expected dense_9_input to have shape (233,) but got array with shape (234,)`. I think parameters of `model()` should be adapted. I've edited the above code to include the `model()` function code.
comment on: http://stackoverflow.com/a/51989379
score: 0
type: AnswerComment

http://stackoverflow.com/q/52068920
linked to: http://stackoverflow.com/q/22715036
possible better answer: http://stackoverflow.com/a/53396910
downvote count: 0
has comment: http://stackoverflow.com/comment/91088074
type: AnsweredQuestion
score: 2
accepted answer: http://stackoverflow.com/a/52070962
tagged with: http://stackoverflow.com/tag/html
favorite count: 0
has answer: http://stackoverflow.com/a/52070105
tagged with: beautifulsoup
type: Question
upvote count: 2
has comment: http://stackoverflow.com/comment/91090124
has comment: http://stackoverflow.com/comment/91088255
tagged with: web-scraping
tagged with: python
tagged with: python-requests
has title: python requests & beautifulsoup bot detection
has comment: http://stackoverflow.com/comment/91088561
has comment: http://stackoverflow.com/comment/91088218
has answer: http://stackoverflow.com/a/53396910
has body: I'm trying to scrape all the HTML elements of a page using requests &amp; beautifulsoup. I'm using ASIN (Amazon Standard Identification Number) to get the product details of a page. My code is as follows: from urllib.request import urlopen import requests from bs4 import BeautifulSoup url = "http://www.amazon.com/dp/" + 'B004CNH98C' response = urlopen(url) soup = BeautifulSoup(response, "html.parser") print(soup) But the output doesn't show the entire HTML of the page, so I can't do my further work with product details. Any help on this? EDIT 1: From the given answer, It shows the markup of the bot detection page. I researched a bit &amp; found two ways to breach it : I might need to add a header in the requests, but I couldn't understand what should be the value of header. Use Selenium. Now my question is, do both of the ways provide equal support?
answer count: 3
has comment: http://stackoverflow.com/comment/91088379
has answer: http://stackoverflow.com/a/52070962

http://stackoverflow.com/comment/91122769
has text: What is the code that you've tried and gave you an error?
type: QuestionComment
comment on: http://stackoverflow.com/q/52086185
score: 0
type: Comment

http://stackoverflow.com/comment/91036452
comment on: http://stackoverflow.com/a/52042421
type: AnswerComment
has text: @NealMcBeal Could you type `pip list | grep celery` in the same terminal and see if you get celery mentioned?
score: 0
type: Comment

http://stackoverflow.com/comment/91033690
type: QuestionComment
has text: What version of pandas do you have? Looks like this problem: https://pandas.pydata.org/pandas-docs/version/0.22/remote_data.html
comment on: http://stackoverflow.com/q/52041488
score: 3
type: Comment

http://stackoverflow.com/q/52103283
type: AnsweredQuestion
score: 3
downvote count: 0
type: Question
tagged with: instrumentation
tagged with: prometheus
has title: Is there an arg to set other endpoint in start_http_server (prometheus_client) instead of /?
tagged with: flask
upvote count: 3
accepted answer: http://stackoverflow.com/a/52111953
answer count: 1
has body: I'm building a Flask application and I would like to know if there is an arg on module start_http_server (from prometheus_client) that allow me to set a specific metrics endpoint instead /. Thanks!
favorite count: 0
has answer: http://stackoverflow.com/a/52111953
tagged with: python

http://stackoverflow.com/comment/90874975
score: 0
comment on: http://stackoverflow.com/a/51962392
has text: One thing is you only ever append integers to the list in your attempt, but you want a list of lists, so you have to make a distinct list as you iterate through each element of a.
type: Comment
type: AnswerComment

python-collections
type: Tag
tags question: http://stackoverflow.com/q/52001019
tag name: python-collections

http://stackoverflow.com/a/51972935
answers question: http://stackoverflow.com/q/51972610
type: Answer
has body: places = [" "] * 9 print(places[8] + "|" + places[7] + "|" + places[6] + "\n" + places[5] + "|" + places[4] + "|" + places[3] + "\n" + places[2] + "|" + places[1] + "|" + places[0] + "\n") This is what you're looking for. The problem was that "\n" only works in print statements.
score: 0

http://stackoverflow.com/a/52092234
upvote count: 5
type: AcceptedAnswer
downvote count: 0
has body: Use merge with outer join and indicator parameter: df = test_1.merge(test_2, how='outer', indicator=True) print (df) Feb Jan Mar account _merge 0 200 150 140 Jones LLC both 1 210 200 215 Alpha Co both 2 90 50 95 Blue Inc right_only And then filter only right_only rows by boolean indexing: only2 = df[df['_merge'] == 'right_only'] print (only2) Feb Jan Mar account _merge 2 90 50 95 Blue Inc right_only Thanks @Jon Clements for one line solution with callback: only2 = test_1.merge(test_2, how='outer', indicator=True)[lambda r: r._merge == 'right_only'] print (only2) Feb Jan Mar account _merge 2 90 50 95 Blue Inc right_only Or use query: only2 = test_1.merge(test_2, how='outer', indicator=True).query("_merge == 'right_only'")
score: 5
type: Answer
accepted answer of: http://stackoverflow.com/q/52092078
has comment: http://stackoverflow.com/comment/91134380
answers question: http://stackoverflow.com/q/52092078

http://stackoverflow.com/comment/91053604
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52051522
has text: Did you try `(Long_d, Long_m, Long_s)`?

http://stackoverflow.com/q/51992912
type: AnsweredQuestion
downvote count: 0
has body: I'm trying to convert my dataframe columns to arrays. For example, I have a dataframe that looks like this: Total Price Carrier 2 3 C 1 5 D I'd like to convert the columns to arrays like this: [[2, 1], [3,5], ['C','D]] I do not want the column names. I've tried doing this: df["all"] = 1 df.groupby("all")"Total","Price", "Carrier".apply(list) However, I get something like this ["Total", "Price", "Carrier"] and is an object and not an array. How can I convert all columns to arrays?
type: Question
upvote count: 2
tagged with: pandas
has answer: http://stackoverflow.com/a/51992965
accepted answer: http://stackoverflow.com/a/51992965
answer count: 1
tagged with: python
favorite count: 0
has title: Converting dataframe columns to arrays
score: 2

flask
tags question: http://stackoverflow.com/q/51963780
tags question: http://stackoverflow.com/q/52089608
tags question: http://stackoverflow.com/q/52055490
tags question: http://stackoverflow.com/q/52100065
tags question: http://stackoverflow.com/q/51958714
tags question: http://stackoverflow.com/q/52006230
tags question: http://stackoverflow.com/q/52094676
tags question: http://stackoverflow.com/q/52026933
tags question: http://stackoverflow.com/q/51961643
tags question: http://stackoverflow.com/q/52033852
tags question: http://stackoverflow.com/q/52010639
tags question: http://stackoverflow.com/q/51995696
tags question: http://stackoverflow.com/q/52109913
tags question: http://stackoverflow.com/q/52019676
tags question: http://stackoverflow.com/q/52077984
tags question: http://stackoverflow.com/q/52085511
tags question: http://stackoverflow.com/q/52085099
tags question: http://stackoverflow.com/q/51964602
tags question: http://stackoverflow.com/q/51982687
tags question: http://stackoverflow.com/q/52102872
tags question: http://stackoverflow.com/q/52074191
tags question: http://stackoverflow.com/q/51967289
tags question: http://stackoverflow.com/q/51961513
tags question: http://stackoverflow.com/q/52038317
tags question: http://stackoverflow.com/q/52049163
tags question: http://stackoverflow.com/q/52012261
tags question: http://stackoverflow.com/q/52024809
tags question: http://stackoverflow.com/q/52003887
tags question: http://stackoverflow.com/q/51995642
tags question: http://stackoverflow.com/q/51979692
tags question: http://stackoverflow.com/q/52103906
tags question: http://stackoverflow.com/q/52103304
tags question: http://stackoverflow.com/q/52098444
tags question: http://stackoverflow.com/q/52107234
tags question: http://stackoverflow.com/q/52069057
tags question: http://stackoverflow.com/q/52063964
tags question: http://stackoverflow.com/q/52052454
tags question: http://stackoverflow.com/q/52102642
tags question: http://stackoverflow.com/q/52056004
tags question: http://stackoverflow.com/q/52083260
tags question: http://stackoverflow.com/q/52039592
type: Tag
tags question: http://stackoverflow.com/q/52103283
tags question: http://stackoverflow.com/q/52075642
tags question: http://stackoverflow.com/q/52096150
tags question: http://stackoverflow.com/q/52037226
tags question: http://stackoverflow.com/q/52094797
tags question: http://stackoverflow.com/q/52100386
tags question: http://stackoverflow.com/q/52039991
tags question: http://stackoverflow.com/q/52045801
tags question: http://stackoverflow.com/q/52046077
tags question: http://stackoverflow.com/q/52055830
tags question: http://stackoverflow.com/q/52077959
tags question: http://stackoverflow.com/q/52057966
tags question: http://stackoverflow.com/q/52090187
tags question: http://stackoverflow.com/q/52014621
tags question: http://stackoverflow.com/q/52031620
tags question: http://stackoverflow.com/q/52108342
tags question: http://stackoverflow.com/q/52055984
tags question: http://stackoverflow.com/q/52015161
tags question: http://stackoverflow.com/q/51972438
tags question: http://stackoverflow.com/q/52069069
tags question: http://stackoverflow.com/q/51988001
tags question: http://stackoverflow.com/q/52090807
tags question: http://stackoverflow.com/q/52037060
tags question: http://stackoverflow.com/q/52008696
tags question: http://stackoverflow.com/q/52062719
tags question: http://stackoverflow.com/q/52077280
tags question: http://stackoverflow.com/q/52008774
tags question: http://stackoverflow.com/q/52015114
tags question: http://stackoverflow.com/q/52079160
tags question: http://stackoverflow.com/q/51989875
tags question: http://stackoverflow.com/q/51965039
tags question: http://stackoverflow.com/q/51964541
tags question: http://stackoverflow.com/q/52058876
tags question: http://stackoverflow.com/q/51979451
tags question: http://stackoverflow.com/q/52087743
tags question: http://stackoverflow.com/q/52072305
tags question: http://stackoverflow.com/q/51982564
tags question: http://stackoverflow.com/q/51995682

teradata
type: Tag
tag name: teradata
tags question: http://stackoverflow.com/q/52012587
tags question: http://stackoverflow.com/q/52098611

http://stackoverflow.com/q/52064324
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/91079357
tagged with: python
tagged with: lambda
score: 2
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52064386
upvote count: 2
has comment: http://stackoverflow.com/comment/91079264
has title: Add a different item from a list to each cell in a dataframe with Pandas
type: Question
tagged with: dataframe
tagged with: apply
accepted answer: http://stackoverflow.com/a/52064386
tagged with: pandas
answer count: 1
has body: Given a dataframe df = pd.DataFrame(np.random.randint(0,100,size=(15, 4)), columns=list('ABCD')) I want to make a list of sequential that has as many elements as there are rows in the dataframe l = [i for i in range(df['A'].count())] And then add each element of the list (as a string) onto the end of a single column in the dataframe. df['A'] = df['A'].apply(lambda x: str(x) + str(l[i])) Does not work, as it adds the whole list as a string to each value as opposed to one value of the list per value in the dataframe. Essentially, I want to transform A B C 23 16 85 9 74 12 99 24 83 to A B C 231 16 85 92 74 12 993 24 83 So anyway to do that would be fine. Thanks for the help!

http://stackoverflow.com/comment/91272155
comment on: http://stackoverflow.com/a/52137710
type: AnswerComment
has text: I don't understand why gcc is not able to match clang's performance - coding in pure C I cannot see much difference. But even when using C-code-vebatim in Cython there is huge difference between gcc and clang.
score: 0
type: Comment

http://stackoverflow.com/q/52056146
has answer: http://stackoverflow.com/a/52058739
score: 15
upvote count: 15
tagged with: iterator
answer count: 2
has answer: http://stackoverflow.com/a/52056290
accepted answer: http://stackoverflow.com/a/52056290
downvote count: 0
tagged with: iterable
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/91062580
has body: In Python 3, it is standard procedure to make a class an iterable and iterator at the same time by defining both the __iter__ and __next__ methods. But I have problems to wrap my head around this. Take this example which creates an iterator that produces only even numbers: class EvenNumbers: def __init__(self, max_): self.max_ = max_ def __iter__(self): self.n = 0 return self def __next__(self): if self.n &lt;= self.max_: # edit: self.max --&gt; self.max_ result = 2 * self.n self.n += 1 return result raise StopIteration instance = EvenNumbers(4) for entry in instance: print(entry) To my knowledge (correct me if I'm wrong), when I create the loop, an iterator is created by calling something like itr = iter(instance) which internally calls the __iter__ method. This is expected to return an iterator object (which the instance is due to defining __next__ and therefore I can just return self). To get an element from it, next(itr) is called until the exception is raised. My question here is now: if and how can __iter__ and __next__ be separated, so that the content of the latter function is defined somewhere else? And when could this be useful? I know that I have to change __iter__ so that it returns an iterator. Btw the idea to do this comes from this site (LINK), which does not state how to implement this.
tagged with: python
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/52058739
has title: Separating the __iter__ and __next__ methods
type: Question

http://stackoverflow.com/q/52048562
linked to: http://stackoverflow.com/q/53455909
tagged with: arrays
has title: Efficient way to compute cosine similarity between 1D array and all rows in a 2D array
answer count: 3
has comment: http://stackoverflow.com/comment/109038736
has comment: http://stackoverflow.com/comment/91047989
accepted answer: http://stackoverflow.com/a/52050974
has body: I have one 1D array of shape (300, ) and a 2D array of shape (400, 300). Now, I want to compute the cosine similarity between each of the rows in this 2D array to the 1D array. Thus, my result should be of shape (400, ) which represents how similar these vectors are. My initial idea is to iterate thru the rows in 2D array using a for loop and then compute cosine similarity between vectors. Is there a faster alternative using broadcasting method? Here is a contrived example: In [29]: vec = np.random.randn(300,) In [30]: arr = np.random.randn(400, 300) Below is the way I want to calculate the similarity between 1D arrays: inn = (vec * arr[0]).sum() vecnorm = numpy.sqrt((vec * vec).sum()) rownorm = numpy.sqrt((arr[0] * arr[0]).sum()) similarity_score = inn / vecnorm / rownorm How can I generalize this to arr[0] being replaced with a 2D array?
favorite count: 0
has comment: http://stackoverflow.com/comment/91048123
possible better answer: http://stackoverflow.com/a/52048673
has comment: http://stackoverflow.com/comment/91047951
score: 5
has answer: http://stackoverflow.com/a/52048673
tagged with: python
downvote count: 1
upvote count: 6
has comment: http://stackoverflow.com/comment/91048057
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/119734109
has answer: http://stackoverflow.com/a/52050974
type: Question
tagged with: cosine-similarity
tagged with: numpy
has answer: http://stackoverflow.com/a/52048671

http://stackoverflow.com/comment/91096383
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52071894
has text: @VineethSai No. I want to record the phone screen in a pc application after connecting my computer and smartphone with usb. I want to make that computer application using by python

http://stackoverflow.com/a/52085669
has comment: http://stackoverflow.com/comment/91122299
accepted answer of: http://stackoverflow.com/q/52085541
has body: filter makes it easy to select the columns you need, followed by one final division. df = df.set_index('Age') i = df.filter(regex=r'_y$') j = df[df.columns.difference(i.columns)] i.columns = j.columns.str.split('_y').str[0] df = j / i.reindex(j.columns, axis=1) The reindex is for added security to make sure both DataFrames are aligned.
type: Answer
upvote count: 1
answers question: http://stackoverflow.com/q/52085541
score: 1
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/91122448

http://stackoverflow.com/comment/91100790
has text: NO, no any other service running
type: Comment
score: 0
comment on: http://stackoverflow.com/q/52071153
type: QuestionComment

http://stackoverflow.com/q/52081588
favorite count: 0
has answer: http://stackoverflow.com/a/52081795
has answer: http://stackoverflow.com/a/52081754
answer count: 5
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/52081780
has answer: http://stackoverflow.com/a/52081682
has answer: http://stackoverflow.com/a/52081806
linked to: http://stackoverflow.com/q/13295735
has body: I have a data frame which has the structure as follows code value 1 red 2 blue 3 yellow 1 4 4 pink 2 blue so basically i want to update the value column so that the blank rows are filled with values from other rows. So I know the code 4 refers to value pink, I want it to be updated in all the rows where that value is not present.
has comment: http://stackoverflow.com/comment/91113613
type: Question
tagged with: dataframe
tagged with: python-2.7
score: 0
tagged with: pandas
upvote count: 1
has title: Updating existing dataframe columns
downvote count: 1

http://stackoverflow.com/q/52107584
tagged with: http://stackoverflow.com/tag/r
answer count: 3
downvote count: 0
favorite count: 0
accepted answer: http://stackoverflow.com/a/52113396
tagged with: python
tagged with: excel
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52112925
tagged with: strikethrough
has answer: http://stackoverflow.com/a/52141499
has title: How to detect "strikethrough" style from xlsx file in R
type: Question
possible better answer: http://stackoverflow.com/a/52141499
has comment: http://stackoverflow.com/comment/91169697
has body: I have to check the data which contain "strikethrough" format when importing excel file in R Do we have any method to detect them ? Welcome for both R and Python approach
has answer: http://stackoverflow.com/a/52113396
score: 4
has comment: http://stackoverflow.com/comment/91166494
upvote count: 4

http://stackoverflow.com/comment/91156321
type: QuestionComment
has text: Just do `finallst.sort()` without converting the lists to strings.
comment on: http://stackoverflow.com/q/52102724
score: 1
type: Comment

http://stackoverflow.com/comment/90963790
type: Comment
has text: I'm using python f-strings here, where you can execute statements inside curly braces, and the results appear in the string. However, since regex also use curly braces, I need to wrap them in an additional curly brace to make the regular expression work.
type: AnswerComment
comment on: http://stackoverflow.com/a/51993566
score: 0

python-3.x
tags question: http://stackoverflow.com/q/51988690
tags question: http://stackoverflow.com/q/51984408
tags question: http://stackoverflow.com/q/52063082
tags question: http://stackoverflow.com/q/52077329
tags question: http://stackoverflow.com/q/52010848
tags question: http://stackoverflow.com/q/52040142
tags question: http://stackoverflow.com/q/52025795
tags question: http://stackoverflow.com/q/52097034
tags question: http://stackoverflow.com/q/52007489
tags question: http://stackoverflow.com/q/51958350
tags question: http://stackoverflow.com/q/52012587
tags question: http://stackoverflow.com/q/51981630
tags question: http://stackoverflow.com/q/52030543
tags question: http://stackoverflow.com/q/52046446
tags question: http://stackoverflow.com/q/52084275
tags question: http://stackoverflow.com/q/52020964
tags question: http://stackoverflow.com/q/52071833
tags question: http://stackoverflow.com/q/52032785
tags question: http://stackoverflow.com/q/52022370
tags question: http://stackoverflow.com/q/52087567
tags question: http://stackoverflow.com/q/52059723
tags question: http://stackoverflow.com/q/51975256
tags question: http://stackoverflow.com/q/52015820
tags question: http://stackoverflow.com/q/52009985
tags question: http://stackoverflow.com/q/52035463
tags question: http://stackoverflow.com/q/52107551
tags question: http://stackoverflow.com/q/52001372
tags question: http://stackoverflow.com/q/52035872
tags question: http://stackoverflow.com/q/52055350
tags question: http://stackoverflow.com/q/52049131
tags question: http://stackoverflow.com/q/51978648
tags question: http://stackoverflow.com/q/51968526
tags question: http://stackoverflow.com/q/52109323
tags question: http://stackoverflow.com/q/51968274
tags question: http://stackoverflow.com/q/51989470
tags question: http://stackoverflow.com/q/52056943
tags question: http://stackoverflow.com/q/51970441
tags question: http://stackoverflow.com/q/52026406
tags question: http://stackoverflow.com/q/51996547
tags question: http://stackoverflow.com/q/52099625
tags question: http://stackoverflow.com/q/52041914
tags question: http://stackoverflow.com/q/51981627
tags question: http://stackoverflow.com/q/52062831
tags question: http://stackoverflow.com/q/52001964
tags question: http://stackoverflow.com/q/52024453
tags question: http://stackoverflow.com/q/51987490
tags question: http://stackoverflow.com/q/52053204
tags question: http://stackoverflow.com/q/52022499
tags question: http://stackoverflow.com/q/52094356
tags question: http://stackoverflow.com/q/52098260
tags question: http://stackoverflow.com/q/51992452
tags question: http://stackoverflow.com/q/52017724
tags question: http://stackoverflow.com/q/52079427
tags question: http://stackoverflow.com/q/52031770
tags question: http://stackoverflow.com/q/52105617
tags question: http://stackoverflow.com/q/52073747
tags question: http://stackoverflow.com/q/52110311
tags question: http://stackoverflow.com/q/52074771
tags question: http://stackoverflow.com/q/52023886
tags question: http://stackoverflow.com/q/52044489
tags question: http://stackoverflow.com/q/52025152
tags question: http://stackoverflow.com/q/52019883
tags question: http://stackoverflow.com/q/51981314
tags question: http://stackoverflow.com/q/52085276
tags question: http://stackoverflow.com/q/52059854
tags question: http://stackoverflow.com/q/51996000
tags question: http://stackoverflow.com/q/51975411
tags question: http://stackoverflow.com/q/52074332
tags question: http://stackoverflow.com/q/52083862
tags question: http://stackoverflow.com/q/51982456
tags question: http://stackoverflow.com/q/51976004
tags question: http://stackoverflow.com/q/52092566
tags question: http://stackoverflow.com/q/51981858
tags question: http://stackoverflow.com/q/52103063
tags question: http://stackoverflow.com/q/52034360
tags question: http://stackoverflow.com/q/51984318
tags question: http://stackoverflow.com/q/52084093
tags question: http://stackoverflow.com/q/51989564
tags question: http://stackoverflow.com/q/51997441
tags question: http://stackoverflow.com/q/52075570

http://stackoverflow.com/q/52081948
tagged with: python
tagged with: dictionary
has comment: http://stackoverflow.com/comment/91114191
score: 1
upvote count: 1
type: Question
has answer: http://stackoverflow.com/a/52082023
has comment: http://stackoverflow.com/comment/91114318
answer count: 3
downvote count: 0
has answer: http://stackoverflow.com/a/52082026
tagged with: key
favorite count: 0
has answer: http://stackoverflow.com/a/52082099
has title: Python - Looking for a more efficient way to renumber the keys in my dictionary
type: UnansweredQuestion
has body: Here is my current dictionary: {0: [(1,1.0)], 1: [(132,1.0)], 2: [(2000,1.0)], 3: [(234,1.0)]} Now, there are instances where I may have to drop on of these keys. Lets take 2 for example, the resulting dictionary would look like this: {0: [(1,1.0)], 1: [(132,1.0)], 3: [(234,1.0)]} Now, I want to renumber the keys so they are consistently increasing by 1: {0: [(1,1.0)], 1: [(132,1.0)], 2: [(234,1.0)]} My first thought was to loop through the dictionary and replace the keys but that doesn't seem like the most efficient path considering my actual dictionary has 2000 keys. Is there a more efficient way?

plot
tags question: http://stackoverflow.com/q/52088018
tags question: http://stackoverflow.com/q/52110463
tags question: http://stackoverflow.com/q/51996431
tags question: http://stackoverflow.com/q/52060625
tags question: http://stackoverflow.com/q/52048317
tags question: http://stackoverflow.com/q/52004433
tags question: http://stackoverflow.com/q/52083431
tags question: http://stackoverflow.com/q/52004075
tags question: http://stackoverflow.com/q/52026962
tags question: http://stackoverflow.com/q/52103408
tags question: http://stackoverflow.com/q/52102791
tags question: http://stackoverflow.com/q/52008009
tag name: plot
tags question: http://stackoverflow.com/q/52105356
tags question: http://stackoverflow.com/q/52096125
tags question: http://stackoverflow.com/q/51975728
tags question: http://stackoverflow.com/q/52051014
tags question: http://stackoverflow.com/q/52003609
tags question: http://stackoverflow.com/q/52029797
tags question: http://stackoverflow.com/q/52020347
type: Tag
tags question: http://stackoverflow.com/q/51999396
tags question: http://stackoverflow.com/q/52044434
tags question: http://stackoverflow.com/q/52087571
tags question: http://stackoverflow.com/q/52102805
tags question: http://stackoverflow.com/q/52092405
tags question: http://stackoverflow.com/q/51985853
tags question: http://stackoverflow.com/q/52067700
tags question: http://stackoverflow.com/q/52052755
tags question: http://stackoverflow.com/q/52014678
tags question: http://stackoverflow.com/q/52067792
tags question: http://stackoverflow.com/q/52058285

http://stackoverflow.com/a/52080982
has comment: http://stackoverflow.com/comment/91117567
accepted answer of: http://stackoverflow.com/q/52080024
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/52080024
type: Answer
has body: The main reason for this behavior is the asynchronous nature of Scrapy itself. The print(len(spider1.result)) line would be executed before the .parse() method is called. There are multiple ways to wait for the spider to be finished. I would do the spider_closed signal: from scrapy import signals def spider_closed(spider, reason): print(len(spider.result)) spider1 = mspider.MySpider() crawler_process = CrawlerProcess(settings) crawler = crawler_process.create_crawler() crawler.signals.connect(spider_closed, signals.spider_closed) crawler.crawl(spider1) crawler_process.start()
has comment: http://stackoverflow.com/comment/91114456
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/91116932
has comment: http://stackoverflow.com/comment/91114395

http://stackoverflow.com/q/52089036
downvote count: 1
tagged with: python
tagged with: regex
favorite count: 0
has title: re.findall() not returning all matches?
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/52089743
has comment: http://stackoverflow.com/comment/91128520
has body: I have the following string: This$#is% Matrix# %! I am trying to catch on substrings where special symbols/spaces occur between alphanumeric characters. For eg, my goal is to find these 2 set of substrings: This$#is (special symbols #, $ between 'This' and 'is') and is% Matrix (special symbol % and whitespace between 'is' and 'Matrix'). My regex findall is as follows: match = re.findall(r'([\w]{1,})([\s\W]{1,})([\w]{1,})', temp) It is returning me: [('This', '$#', 'is')] but not the second part ('is% Matrix'). Is there anything I am doing wrong? If I change my string to 'is% Matrix' and apply the same regex pattern, I get this: [('is', '% ', 'Matrix')].
type: Question
answer count: 1
score: 0
upvote count: 1

http://stackoverflow.com/comment/91151734
score: 0
has text: Possible duplicate of [InterfaceError (0, '')](https://stackoverflow.com/questions/6650940/interfaceerror-0)
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52100386

http://stackoverflow.com/comment/90968805
has text: Thanks again, duyue! This works great! Now is there an elegant way to do the reverse? Meaning I start with 0x1AF374A3 and I get [0x1A, 0xF3, 0x74, 0xA3]? I looked in functools for the opposite of "reduce" (e.g. "augment", "expand") but didn't find anything that jumped out at me.
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52003573

http://stackoverflow.com/a/69620010
upvote count: 1
answers question: http://stackoverflow.com/q/52085191
downvote count: 0
type: Answer
has body: A little late perhaps but I had the same issue (i'm using conda for python envs) and did the following to solve this: cd C:\Users\{user}\miniconda3\envs\{env_name} pip list Verify in the output if pyodbc is installed. If not run (from the environment folder) the following: pip install -r C:\dev\repos\{repo-name}\requirements.txt Check pip list again and now pyodbc should be there.
score: 1

http://stackoverflow.com/q/51973039
favorite count: 0
tagged with: python
upvote count: 4
has body: I've looked around on Stackoverflow, but could not find anything that would answer my question. Problem Setup: I am trying to solve a system of stiff ODEs using scipy.integrate.ode. I've reduced the code to the minimal working example: import scipy as sp from scipy import integrate import matplotlib.pylab as plt spiketrain =[0] syn_inst = 0 def synapse(t, t0): tau_1 = 5.3 tau_2 = 0.05 tau_rise = (tau_1 * tau_2) / (tau_1 - tau_2) B = ((tau_2 / tau_1) ** (tau_rise / tau_1) - (tau_2 / tau_1) ** (tau_rise / tau_2)) ** -1 return B*(sp.exp(-(t - t0) / tau_1) - sp.exp(-(t - t0) / tau_2)) #the culprit def alpha_m(v, vt): return -0.32*(v - vt -13)/(sp.exp(-1*(v-vt-13)/4)-1) def beta_m(v, vt): return 0.28 * (v - vt - 40) / (sp.exp((v- vt - 40) / 5) - 1) def alpha_h(v, vt): return 0.128 * sp.exp(-1 * (v - vt - 17) / 18) def beta_h(v, vt): return 4 / (sp.exp(-1 * (v - vt - 40) / 5) + 1) def alpha_n(v, vt): return -0.032*(v - vt - 15)/(sp.exp(-1*(v-vt-15)/5) - 1) def beta_n(v, vt): return 0.5* sp.exp(-1*(v-vt-10)/40) def inputspike(t): if int(t) in a : spiketrain.append(t) def f(t,X): V = X[0] m = X[1] h = X[2] n = X[3] inputspike(t) g_syn = synapse(t, spiketrain[-1]) syn = 0.5* g_syn * (V - 0) global syn_inst syn_inst = g_syn dydt = sp.zeros([1, len(X)])[0] dydt[0] = - 50*m**3*h*(V-60) - 10*n**4*(V+100) - syn - 0.1*(V + 70) dydt[1] = alpha_m(V, -45)*(1-m) - beta_m(V, -45)*m dydt[2] = alpha_h(V, -45)*(1-h) - beta_h(V, -45)*h dydt[3] = alpha_n(V, -45)*(1-n) - beta_n(V, -45)*n return dydt t_start = 0.0 t_end = 2000 dt = 0.1 num_steps = int(sp.floor((t_end - t_start) / dt) + 1) a = sp.zeros([1,int(t_end/100)])[0] a[0] = 500 #so the model settles sp.random.seed(0) for i in range(1, len(a)): a[i] = a[i-1] + int(round(sp.random.exponential(0.1)*1000, 0)) r = integrate.ode(f).set_integrator('vode', nsteps = num_steps, method='bdf') X_start = [-70, 0, 1,0] r.set_initial_value(X_start, t_start) t = sp.zeros(num_steps) syn = sp.zeros(num_steps) X = sp.zeros((len(X_start),num_steps)) X[:,0…
type: AnsweredQuestion
downvote count: 0
has title: Scipy ODE time steps going backward
tagged with: scipy
tagged with: ode
type: Question
has comment: http://stackoverflow.com/comment/90897021
score: 4
has answer: http://stackoverflow.com/a/52029544
accepted answer: http://stackoverflow.com/a/52029544
has comment: http://stackoverflow.com/comment/90937590
answer count: 1

http://stackoverflow.com/comment/91156542
has text: You can fork it and use it directly
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52099494

http://stackoverflow.com/a/54756334
answers question: http://stackoverflow.com/q/52084421
type: Answer
has body: Here's an alternative, using a stacked line chart: import pandas as pd import seaborn as sns from matplotlib import pyplot as plt # load csv df = pd.read_csv("test.csv") # generate graph plt.stackplot(df["Date"], df["Data"], alpha=0.5) plt.show()
downvote count: 1
score: 4
upvote count: 5

http://stackoverflow.com/q/51973653
has body: I did search for a lot of examples before posting but still can't properly use the tkinter grid. What I want: my code: import tkinter as tk from tkinter import ttk root = tk.Tk() b1 = ttk.Button(root, text='b1') b1.grid(row=0, column=0, sticky=tk.W) e1 = ttk.Entry(root) e1.grid(row=0, column=1, sticky=tk.EW) t = ttk.Treeview(root) t.grid(row=1, column=0, sticky=tk.NSEW) scroll = ttk.Scrollbar(root) scroll.grid(row=1, column=1, sticky=tk.E+tk.NS) scroll.configure(command=t.yview) t.configure(yscrollcommand=scroll.set) root.columnconfigure(0, weight=1) root.columnconfigure(1, weight=1) root.rowconfigure(1, weight=1) root.mainloop()
tagged with: grid-layout
type: AnsweredQuestion
has title: Tkinter grid fill empty space
accepted answer: http://stackoverflow.com/a/51973754
downvote count: 0
has comment: http://stackoverflow.com/comment/90898012
favorite count: 0
type: Question
tagged with: python
score: 15
tagged with: tkinter
has answer: http://stackoverflow.com/a/51973754
answer count: 1
has comment: http://stackoverflow.com/comment/90897978
has comment: http://stackoverflow.com/comment/90897869
has comment: http://stackoverflow.com/comment/90898026
upvote count: 15
has comment: http://stackoverflow.com/comment/90897953

http://stackoverflow.com/comment/90937749
score: 0
type: Comment
type: QuestionComment
has text: Not a dupe, but see: https://stackoverflow.com/q/30081275/4799172
comment on: http://stackoverflow.com/q/51993862

http://stackoverflow.com/q/52100386
has comment: http://stackoverflow.com/comment/91151971
answer count: 0
tagged with: mysql
has comment: http://stackoverflow.com/comment/91151491
has comment: http://stackoverflow.com/comment/91151734
has comment: http://stackoverflow.com/comment/91151764
type: Question
has comment: http://stackoverflow.com/comment/91184526
tagged with: flask
has comment: http://stackoverflow.com/comment/91151576
has title: Insert data into MySQL with python and curl
score: 0
has comment: http://stackoverflow.com/comment/91152102
has comment: http://stackoverflow.com/comment/91151923
linked to: http://stackoverflow.com/q/6650940
has body: I'm developing a small program which inserts a data obtained by curl to a MySQL database. Unfortunately, I haven't found any similar about my question, so if you have something on your mind - please point me out there. Here is what I tried so far import os import pymysql from flask import Flask, request app = Flask(__name__) db = pymysql.connect("127.0.0.1","meeting_admin","password","rooms") cur = db.cursor() @app.route('/book_room', methods = ['POST']) def book_room(): try: room = request.form['room'] book_date = request.form['book_date'] booked_by = request.form['booked_by'] cur.execute("INSERT INTO booked_rooms(room, book_date, booked_by) VALUES ('%c', '%d', '%s')",(room, book_date, booked_by)) db.commit() cur.close() return "OK\n", 200 except: db.rollback() return "Smth went wrong", 500 db.close() if __name__ == '__main__': app.run() And the curl command is: curl -H "Content-type: application/json" -X POST / http://127.0.0.1:5000/book_room -d / '{room=602,book_date:27-08-2019,booked_by="someone"}' And what I'm getting is: File "server_flask.py", line 23, in book_room room = request.form['room'] File "/usr/local/lib/python3.5/dist- packages/werkzeug/datastructures.py", line 431, in __getitem__ raise exceptions.BadRequestKeyError(key) werkzeug.exceptions.HTTPException.wrap.&lt;locals&gt;.newcls: 400 Bad Request: The browser (or proxy) sent a request that this server could not understand. Thanks in advance.
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/91152242
tagged with: curl

http://stackoverflow.com/q/51969739
score: 2
has comment: http://stackoverflow.com/comment/90903275
upvote count: 2
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/48427185
tagged with: python
has comment: http://stackoverflow.com/comment/90890684
has comment: http://stackoverflow.com/comment/90892046
has comment: http://stackoverflow.com/comment/90892300
has comment: http://stackoverflow.com/comment/90892441
tagged with: dataframe
linked to: http://stackoverflow.com/q/38296609
type: Question
has comment: http://stackoverflow.com/comment/90891700
has comment: http://stackoverflow.com/comment/90892495
tagged with: pyspark
answer count: 1
downvote count: 0
has title: Why does this code throw a wierd error in PySpark? Is this really the right way to do this?
has comment: http://stackoverflow.com/comment/90891737
tagged with: apache-spark
has answer: http://stackoverflow.com/a/51973462
has body: I have the following piece of small code. # do all the required imports import pyspark import pandas as pd from pyspark.sql.functions import udf from pyspark.sql import SparkSession #create a session spark = SparkSession \ .builder \ .appName("Python Spark SQL basic example") \ .config("spark.some.config.option", "some-value") \ .getOrCreate() #fashion_df is described below fashion_df = pd.read_csv('fashion_df.csv') #create a UDF def check_merchant_cat(text): if not isinstance(text, str): category = "N/A" return category category = fashion_df[fashion_df['merchant_category']==text]['merchant_category'] return category merchant_category_mapping_func = udf(check_merchant_cat) df = spark.read.csv('datafeed.csv', header=True, inferSchema=True) processed_df = df.withColumn("merchant_category_mapped", merchant_category_mapping_func(df['merchant_category'])) processed_df.select('merchant_category_mapped', 'merchant_category').show(10) Let me describe the problem I am trying to solve. I have a fashion_df which is basically multiple rows ( around 1000) with the header like this: merchant_category,category,sub_category Dresses &amp; Skirts,Dress,Skirts I have the datafeed.csv also referred in the code above which has around 1 Million rows. Each row has multiple columns, but few of the columns are of interest. Basically, I want to go over every row of the datafeed.csv. Then, I want to look at the merchant_category column of the row. Then, I want to search for this merchant_category value in the "merchant_category" column of the fashion_df pandas dataframe. Given that it has found the matching row, I take the value in the category column of the corresponding matching row in the fashion_df and return it. The returned category value is appended as a column in the original datafeed loaded in PySpark. Is this the right way to do this?
has comment: http://stackoverflow.com/comment/90891659
favorite count: 0

http://stackoverflow.com/comment/91018906
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/52033908
has text: @bigbounty The file does not exist because I erased it on purpose from disk. I thought the data are kept on memory. However, dataset actually tried to read the data from disk repeatedly, and I want to change the behavior a bit.

http://stackoverflow.com/comment/91121344
has text: Note that `|` is a regex meta character for alteration. Your example regex of `r'00 LOG | Cycles Run: (.*?)'` has the issue of looking for `00 LOG ` OR ` Cycles Run: (.*?)` which is why it is not matching anything.
comment on: http://stackoverflow.com/q/52084871
type: Comment
type: QuestionComment
score: 1

http://stackoverflow.com/comment/91007739
type: QuestionComment
score: 0
has text: Pls donot the comments space for this - **edit & update** your question instead
comment on: http://stackoverflow.com/q/52028474
type: Comment

http://stackoverflow.com/q/52041545
tagged with: python
has title: How do you transform the output of keras NN outside backpropagation?
has body: I have raw 1d data on one side of a NN, and 1d labels on the other. Input data is transformed by going through layers with trainable parameters and specific activation function. I want to add a final transformation using an external algorithm that I don't want to train (only the parameters in the previous layers are to be trained). How can I do that? UPDATE: Before implementing the external algorithm using subprocess, I give it a try with a simple test to output just a constant (1.0). This is the code: inputs=keras.Input(shape=(174,1)) labels=padded_label x = keras.layers.Conv1D(filters=4,kernel_size=8,strides=1,input_shape=(174,1),padding='same')(inputs) x = keras.layers.Dense(1, activation='sigmoid')(x) def grande(x): return np.ones((x.shape)) predictions=keras.layers.Lambda(grande,trainable=False)(x) model = keras.Model(inputs=inputs, outputs=predictions) model.compile(optimizer='rmsprop', loss='binary_crossentropy', metrics=['accuracy']) where the labels are vectors of shape (174,1) with values either 0 or 1. This doesn't work and throws error: TypeError Traceback (most recent call last) &lt;ipython-input-35-b23e29737fa2&gt; in &lt;module&gt;() 8 #return sp.check_output('echo 1.0',shell=True) 9 return np.ones((x.shape)) ---&gt; 10 predictions=keras.layers.Lambda(grande,trainable=False)(x) 11 model = keras.Model(inputs=inputs, outputs=predictions) 12 model.compile(optimizer='rmsprop', /usr/local/lib/python3.5/dist-packages/tensorflow/python/keras/engine /base_layer.py in __call__(self, inputs, *args, **kwargs) 701 702 if not in_deferred_mode: --&gt; 703 outputs = self.call(inputs, *args, **kwargs) 704 if outputs is None: 705 raise ValueError('A layer\'s `call` method should return a Tensor ' /usr/local/lib/python3.5/dist-packages/tensorflow/python/keras/layers/core.py in call(self, inputs, mask) 707 if generic_utils.has_arg(self.function, 'mask'): 708 arguments['mask'] = mask --&gt; 709 return self.function(inputs, **arguments) 710 711 def compute_mask(self, inpu…
has comment: http://stackoverflow.com/comment/91037650
score: -1
tagged with: tensorflow
type: Question
tagged with: customization
tagged with: neural-network
has answer: http://stackoverflow.com/a/52044861
tagged with: keras
favorite count: 0
downvote count: 2
upvote count: 1
answer count: 1
type: UnansweredQuestion

http://stackoverflow.com/q/52062156
type: Question
has comment: http://stackoverflow.com/comment/91082264
has comment: http://stackoverflow.com/comment/91074927
upvote count: 0
has answer: http://stackoverflow.com/a/52066285
has comment: http://stackoverflow.com/comment/91082967
has body: I am trying to read an input from excel in python which I convert into a dictionary , like: import xlrd, json d = {} wb = xlrd.open_workbook('input.xlsx') sh = wb.sheet_by_index(0) data=[] for i in range(1,sh.nrows): d={} for j in range(sh.ncols): d[sh.cell(0,j).value] = sh.cell(i,j).value data.append(d) data The resulting data is of the format [{'Age': 20.0, 'Brothers': 2.0, 'Name': 'Josh', 'Nationality': 'UK'}, {'Age': 22.0, 'Brothers': 1.0, 'Name': 'Kim', 'Nationality': 'France'}] My "json" file output should look exactly like this { 'Children':[ {'Age': 20.0, 'Brothers': 2.0, 'Name': 'Josh', 'Nationality': 'UK'}, {'Age': 22.0, 'Brothers': 1.0, 'Name': 'Kim', 'Nationality': 'France'} ] } However, When I call json.dumpts(data) I obtain something like this [ { "Name": "Josh", "Age": 20.0, "Nationality": "UK", "Brothers": 2.0 }, { "Name": "Kim", "Age": 22.0, "Nationality": "France", "Brothers": 1.0 } ] So two quesitons. How I can insert "Children" field at the begining and how can I get my exact desire output format? Thanks
has title: Dictionary to JSON in Python
downvote count: 4
has comment: http://stackoverflow.com/comment/91075491
answer count: 1
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion
score: -4
tagged with: python
tagged with: dictionary
has comment: http://stackoverflow.com/comment/91082907
tagged with: http://stackoverflow.com/tag/json

http://stackoverflow.com/comment/101773109
type: Comment
has text: @jayant it is present in the code. Look at the last few lines
comment on: http://stackoverflow.com/a/51998482
type: AnswerComment
score: 0

http://stackoverflow.com/q/52068083
type: UnansweredQuestion
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/91122772
has title: Anaconda Virtual Env Python script not executing
tagged with: anaconda
score: 1
type: Question
has body: I am trying to use a virtual environment in anaconda on Ubuntu. I start my environment using source activate testEnv just fine. However, if I run the command python, I get the following error: bash: /home/user/anaconda/envs/testEnv/bin/python: cannot execute binary file: Exec format error If I am not in the virtual environment, and I cd to /home/user/anaconda/envs/testEnv/bin/, I can run python perfectly fine. However, from any other location, say my home directory, I try to run /home/user/anaconda/envs/testEnv/bin/python, I get the same error as above.
downvote count: 0
has comment: http://stackoverflow.com/comment/91086317
tagged with: conda
has comment: http://stackoverflow.com/comment/91086261
favorite count: 0
answer count: 0

http://stackoverflow.com/comment/91058916
type: Comment
type: QuestionComment
has text: yes, and obviously I want the prediction to be updated as well.
comment on: http://stackoverflow.com/q/52053697
score: 1

http://stackoverflow.com/q/52022564
has answer: http://stackoverflow.com/a/52022585
accepted answer: http://stackoverflow.com/a/52022585
has title: Fastest way to generate dictionary from two lists
tagged with: python
tagged with: dictionary
possible better answer: http://stackoverflow.com/a/52022596
type: AnsweredQuestion
tagged with: list
has body: I have two lists. For example: keys = [1, 2, 3, 2, 4, 2, 1] and values = [1, 2, 3, 4, 5, 6, 7] I want to create a dictionary of lists out of them as shown below: dict = {1: [1, 7], 2: [2, 4, 6], 3: [3], 4: [5]} What is the fastest way to do it and what generates the efficiency gains, both by using any module and also by not importing any additional module?
has answer: http://stackoverflow.com/a/52022596
type: Question
has answer: http://stackoverflow.com/a/52022606
score: 0
answer count: 3

http://stackoverflow.com/q/52075916
accepted answer: http://stackoverflow.com/a/52076204
type: Question
answer count: 1
downvote count: 0
score: 1
has title: Python project structure
has answer: http://stackoverflow.com/a/52076204
tagged with: python
favorite count: 0
tagged with: python-3.x
upvote count: 1
has body: I've started a Python project. It's not a web app or GUI app, just a simple command line tool. I generally use the same kind of project structure, which is: tspviz │ .gitignore │ requirements.txt │ setup.py │ ├───data │ prices.txt │ shops.txt │ ├───tests └───tspviz │ tspviz.py │ __init__.py │ ├───algorithm │ │ genetic.py │ │ params.py │ │ __init__.py │ │ │ └───__pycache__ │ genetic.cpython-37.pyc │ params.cpython-37.pyc │ __init__.cpython-37.pyc So it is quite self-explanatory, the main file is the tspviz.py in tspviz directory. Now this is a program which will solve the Travelling Salesman Problem, so I would need to make some classes like City, Path etc. Then the problem is: where do I put them? I would make a separate directory in the tspviz dir (not the root one). Then, well, how do I name this folder without confusing my colleagues? I don't know, "classes", "types", "misc"? So my question would be: Should I place them all in a directory inside tspviz as they would probably be used only from there and secondly: is there a standardized way to name a folder like this? (with classes, that you use all over the place)
type: AnsweredQuestion

http://stackoverflow.com/q/51970096
tagged with: django-forms
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/90892131
tagged with: django-admin
upvote count: 2
has answer: http://stackoverflow.com/a/51970919
favorite count: 0
has title: How to add a custom field in django model form?
has answer: http://stackoverflow.com/a/51991424
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/4891506
tagged with: django
tagged with: python
has body: I'm trying to add a readonly field in a form. The model Folder is registered in admin site. The FolderAdminForm defines the custom field statistics. There isn't statistcs field in the Folder model, I just want to put some readonly data on the form. This data is defined in the template. But I get a error whenever the user doesn't have edit permission. If the user only have the view permission,this error is raised: AttributeError: Unable to lookup 'statistics' on Folder or FolderAdmin Here is my code: class CustomWidget(forms.Textarea): template_name = 'widget.html' class FolderAdminForm(forms.ModelForm): class Meta: model = Folder fields = ('field1', 'field2', 'field3',) statistics = forms.Field( widget=CustomWidget, label='Estatísticas', help_text='Estatísticas da pasta', )
score: 2
downvote count: 0

http://stackoverflow.com/comment/90985956
has text: It has only text ..
comment on: http://stackoverflow.com/q/52017742
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/q/52042695
upvote count: 26
has answer: http://stackoverflow.com/a/57053110
has title: Discord Bot Role Mentioning
has body: I am making simple Discord bot for my server, because part of one bot doesn't work. But, that bot needs to tag people from one role (let's say that role is "Moderator"). I wanted it to tag everyone from Moderator role, which will be like @Moderator. Here is my code (I am using Python 3.6): if message.content.startswith('!startbot'): msg = '@Moderator, (some message after this)'.format(message) But, that "@Moderator" doesn't actually tag anyone from Moderator role. It's just blank text like every other message. But, when I as someone real from Discord server type @Moderator, it brings red color (which I set) and it tags Moderator. Can someone help me please to solve this thing ?
downvote count: 0
accepted answer: http://stackoverflow.com/a/52042983
favorite count: 0
answer count: 5
possible better answer: http://stackoverflow.com/a/66365836
tagged with: python
tagged with: discord
has answer: http://stackoverflow.com/a/52042983
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52058395
has answer: http://stackoverflow.com/a/52043068
type: Question
tagged with: discord.py
score: 26
has answer: http://stackoverflow.com/a/66365836

http://stackoverflow.com/comment/90981205
has text: How are you using this? And what behaviour are you seeing, exactly? The base Manager class doesn't have a `set` method.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52012401

http://stackoverflow.com/comment/91049606
type: Comment
type: QuestionComment
has text: I have tried below code with PyVISA
comment on: http://stackoverflow.com/q/52040612
score: 0

http://stackoverflow.com/q/52007418
tagged with: upsert
score: 7
favorite count: 0
has answer: http://stackoverflow.com/a/69814053
type: Question
tagged with: python
has answer: http://stackoverflow.com/a/52007626
answer count: 3
tagged with: dataframe
upvote count: 7
has answer: http://stackoverflow.com/a/66636704
tagged with: apache-spark-sql
downvote count: 0
tagged with: pyspark
type: UnansweredQuestion
has title: PySpark: Insert or update dataframe with another dataframe
has body: I have two dataframes, DF1 and DF2. DF1 is the master and DF2 is the delta. The data from DF2 should be inserted into DF1 or used to update the DF1 data. Lets say the DF1 is of the following format: id_no start_date amount days 1 2016-01-01 4650 22 2 2016-01-02 3130 45 1 2016-01-03 4456 22 2 2016-01-15 1234 45 DF2 contains the following: id_no start_date amount days 1 2016-01-01 8650 52 2 2016-01-02 7130 65 1 2016-01-06 3456 20 2 2016-01-20 2345 19 3 2016-02-02 1345 19 I need to combine the two dataframes such that if the "id_no" and "start date" of DF2 matches DF1, it should be replaced in DF1 and if does not match, it should be inserted into DF1. The "id_no" is not unique. The expected result: id_no start_date amount days 1 2016-01-01 8650 52 2 2016-01-02 7130 65 1 2016-01-03 4456 22 2 2016-01-15 1234 45 1 2016-01-06 3456 20 2 2016-01-20 2345 19 3 2016-02-02 1345 19

http://stackoverflow.com/comment/91142181
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52093800
has text: Also, the second solution you propose is tried and works well. Will change it to your first tip tho.

http://stackoverflow.com/q/52044856
tagged with: http://stackoverflow.com/tag/c
has comment: http://stackoverflow.com/comment/91040668
type: Question
has title: Python3 and C different math division result
accepted answer: http://stackoverflow.com/a/52044887
answer count: 1
tagged with: python
favorite count: 0
has body: I have a simple number division. I have this two number: 39.654 8.381903173E-8 So, if I do the division on C: // ... float ii = 39.654; double bb = 8.381903173E-8; printf("\n%.20f\n", ii/bb); // ... The output is: 473090639.56200009584426879883 But, if I work on Python3: 39.654/8.381903173E-8 The output is: 473090647.5719557 If I use a calculator, indeed, the true value is that of Python3 What is wrong with my C code? Thanks! Regards!
upvote count: 2
downvote count: 1
has comment: http://stackoverflow.com/comment/91040937
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/13542944
score: 1
has answer: http://stackoverflow.com/a/52044887

http://stackoverflow.com/a/51974081
type: Answer
score: 1
answers question: http://stackoverflow.com/q/51973860
upvote count: 1
downvote count: 0
has body: You can access all of them using xpath: 1) [parents before this div]/div[2]/span/a/b 2) [parents before this div]/div[2]/span/font 3) [parents before this div]/div[1]/span/a/img [parents before this div] should be /html/body/...

http://stackoverflow.com/a/52044790
upvote count: 1
type: Answer
has body: Your decorator looks incorrect: app.route('/login') app.route('/') def login(): return render_template('login.html') try adding an @ character: @app.route('/login') @app.route('/') def login(): return render_template('login.html')
answers question: http://stackoverflow.com/q/52044738
downvote count: 0
score: 1

http://stackoverflow.com/comment/91071969
type: AnswerComment
comment on: http://stackoverflow.com/a/51971731
has text: I did the create_node but had to use False to get it to set to "Only build jobs with label expressions matching this node". So is that something setup on the Jenkins side or you just mixed up the True/False?
score: 0
type: Comment

http://stackoverflow.com/q/52082814
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91116947
accepted answer: http://stackoverflow.com/a/52083402
possible better answer: http://stackoverflow.com/a/73266689
has body: In Anaconda Navigator, I switched to running applications on tensorflow and installed jupyter 5.6.0. I then open up a Python3 notebook. I then import tensorflow, keras and numpy without issue. Then when I try to import matplotlib, the notebook says ImportError: No module named 'matplotlib'. I tried running the following command in my anaconda prompt in both base and after activating tensorflow: pip3 install matplotlib And it says: (tensorflow) C:\Users\danie>pip3 install matplotlib Requirement already satisfied for 7 different lines. What am I doing wrong?
has answer: http://stackoverflow.com/a/73266689
tagged with: tensorflow
type: Question
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/91116739
has comment: http://stackoverflow.com/comment/91116993
has comment: http://stackoverflow.com/comment/91116868
score: 0
answer count: 2
has comment: http://stackoverflow.com/comment/91116520
tagged with: python
has answer: http://stackoverflow.com/a/52083402
has title: Matplotlib in Tensorflow Jupyter Notebook
tagged with: jupyter-notebook

http://stackoverflow.com/comment/91090941
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52050476
score: 0
has text: i am a beginner in python, i don't have any special requirement. but if i have a case like that then how to access variable ph,

http://stackoverflow.com/comment/90949324
comment on: http://stackoverflow.com/q/52000052
type: QuestionComment
type: Comment
score: 0
has text: do you mean like this? test = testing.objects.get(id='name'), testing.objects.get(id='title')

http://stackoverflow.com/a/60696886
score: 2
upvote count: 3
downvote count: 1
answers question: http://stackoverflow.com/q/51992375
has body: I installed pyaudio on python 3.6.x without problem, but is not working on later versions. py -m pip install pyaudio works perfect on 3.6.x or earlier.
type: Answer

http://stackoverflow.com/q/52014217
has comment: http://stackoverflow.com/comment/90978953
has comment: http://stackoverflow.com/comment/90978893
score: 0
has title: Django back button issue after logout
answer count: 1
has comment: http://stackoverflow.com/comment/90978908
has comment: http://stackoverflow.com/comment/90978872
linked to: http://stackoverflow.com/q/28000981
has answer: http://stackoverflow.com/a/52014339
type: UnansweredQuestion
tagged with: django
tagged with: python
tagged with: django-views
has body: I am displaying same home page for both logged-in users and logged-out users. But the change is in navbar. Upon login there will be name of the user displayed. And upon logout nothing will be displayed. If I logout and click back button I see the back previous page getting displayed (i.e the one with the user name). I searched a bit about it and found even few questions about it. But there decorators are used to prevent logged out users to to come back. SO that that page will get prevented from loading again. But here as I am displaying the same page for both the users, how to accomplish it ?? How to prevent navbar from showing user name of users upon logout and clicking back button. My navbar code:: {% if request.user.is_authenticated %} {{ request.user.username }} Profile Logout {% else %} {% ifequal request.path '/accounts/login/' %} Sign Up {% else %} Login {% endifequal %} {% endif %} UPDATE: My home page view is class HomeView(TemplateView): template_name = "home/home.html" # same template for login and logout urls.py is urlpatterns = [ url(r'^$', HomeView.as_view(), name="home"), ] I am using django.contrib.auth.urls for both login and logout operations Thanks in advance!
type: Question

http://stackoverflow.com/comment/90967004
has text: I don't see the expected output
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52008241
score: 0

http://stackoverflow.com/a/52026936
type: AcceptedAnswer
has body: This can be done in exactly the way your describe: import tensorflow as tf import numpy as np RS = np.random.RandomState(42) # Defining model parameters as TF variables W1 = tf.Variable(RS.randn(2, 1)) b1 = tf.Variable(RS.randn(1,)) W2 = tf.Variable(RS.randn(2, 1)) b2 = tf.Variable(RS.randn(1,)) def odeModel(state, t): x, y, z = tf.unstack(state) dx = y # Model definition dy = tf.nn.relu(tf.matmul(tf.expand_dims([y, z], -1), W1, transpose_a=True) + b1) dz = tf.nn.relu(tf.matmul(tf.expand_dims([y, z], -1), W2, transpose_a=True) + b2) return tf.stack([dx, tf.squeeze(dy), tf.squeeze(dz)]) t = np.linspace(0, 5, 100) state0 = tf.constant([0, 1, 3], dtype=tf.float64) states, info = tf.contrib.integrate.odeint(odeModel, state0, t, full_output=True) loss = tf.reduce_mean(tf.pow(states[:, 2], 2)) optimizer = tf.train.AdagradOptimizer(0.05).minimize(loss) # ---- sess = tf.Session() sess.run(tf.global_variables_initializer()) # Value before optimizing sess.run(W1) # array [[ 0.49671415], # [-0.1382643 ]] # Optimize for 10 steps. for i in range(10): sess.run(optimizer) # Value after optimization sess.run(W1) # array([[ 0.38043613], # [-0.26166077]])
type: Answer
has comment: http://stackoverflow.com/comment/91007702
accepted answer of: http://stackoverflow.com/q/52023464
answers question: http://stackoverflow.com/q/52023464
score: 0

http://stackoverflow.com/q/52069057
linked to: http://stackoverflow.com/q/42681231
has answer: http://stackoverflow.com/a/52276457
accepted answer: http://stackoverflow.com/a/52276457
score: 1
upvote count: 1
answer count: 1
tagged with: flask
tagged with: flask-sqlalchemy
favorite count: 0
has title: flask SQLAlchemy hybrid_property Boolean value of this clause is not defined
tagged with: python
type: AnsweredQuestion
tagged with: python-3.x
downvote count: 0
has body: I'm using Python 3.6.5, Flask 1.0.2, SQLAlchemy 1.0.5 and I want to define an attribute as a maximum between other two, based on flask-admin hybrid property example: from flask import Flask from flask_sqlalchemy import SQLAlchemy from sqlalchemy.ext.hybrid import hybrid_property import flask_admin as admin from flask_admin.contrib import sqla from sqlalchemy.sql.expression import func # Create application app = Flask(__name__) # Create dummy secrey key so we can use sessions app.config['SECRET_KEY'] = '123456790' # Create in-memory database app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///sample_db_2.sqlite' app.config['SQLALCHEMY_ECHO'] = True db = SQLAlchemy(app) # Flask views @app.route('/') def index(): return 'Click me to get to Admin!' class Screen(db.Model): __tablename__ = 'screen' id = db.Column(db.Integer, primary_key=True) width = db.Column(db.Integer, nullable=False) height = db.Column(db.Integer, nullable=False) @hybrid_property def max(self): return max(self.height, self.width) class ScreenAdmin(sqla.ModelView): """ Flask-admin can not automatically find a hybrid_property yet. You will need to manually define the column in list_view/filters/sorting/etc.""" column_list = ['id', 'width', 'height', 'max'] column_sortable_list = ['id', 'width', 'height', 'max'] # Flask-admin can automatically detect the relevant filters for hybrid properties. column_filters = ('max', ) # Create admin admin = admin.Admin(app, name='Example: SQLAlchemy2', template_mode='bootstrap3') admin.add_view(ScreenAdmin(Screen, db.session)) if __name__ == '__main__': # Create DB db.create_all() # Start app app.run(debug=True) But it fails, raising this error: raise TypeError("Boolean value of this clause is not defined") Traceback: /home/bibo/usr/miniconda/envs/otroflask/lib/python3.6/site-packages/flask_sqlalchemy/__init__.py:794: FSADeprecationWarning: SQLALCHEMY_TRACK_MODIFICATIONS adds significant overhead and will be disabled by default in the future. Set it to True or False to …
type: Question

http://stackoverflow.com/q/51985916
tagged with: raspberry-pi3
has body: i m using industrial PIR sensor (ekmc1603111) [link-https://www.amazon.in/Panasonic-EKMC1603111-Pir-Sensor/dp/B016KL1EQG/ref=sr_1_1?s=industrial&amp;ie=UTF8&amp;qid=1535017218&amp;sr=8-1&amp;keywords=pir+sensor+ekmc1603111]. which is digital sensor, with relay on raspberry pi for lab automation, when motion is detected lab values goes to high n relays goes to high. &amp; when it goes to low relay also goes to low, my problem as follows, when motion is detected or human is present in lab sensor gives 4-5V value on multi meter its correct n relay goes high, but when there is no motion n no human presence sensor still gives me 2-3V rather than Zero, n here relays always set to high.(here relays have to set as LOW so please help me out from this, VCC-5V, GND-GND, SINGAL-GPIO 18, Relay - GPIO 5,6. Thanks in advance. below is my code. from threading import Thread, Event import time import RPi.GPIO as GPIO GPIO.setmode(GPIO.BCM) GPIO.setup(18,GPIO.IN) GPIO.setup(5,GPIO.OUT) GPIO.setup(6,GPIO.OUT) class MyThread(Thread): def __init__(self, timeout=20): super(MyThread, self).__init__() self.intruder_spotted = Event() self.timeout = timeout self.daemon = True def run(self): while True: if self.intruder_spotted.wait(self.timeout): self.intruder_spotted.clear() print("Intruder") GPIO.output(5,GPIO.HIGH) GPIO.output(6,GPIO.HIGH) else: print("No intruder") GPIO.output(5,GPIO.LOW) GPIO.output(6,GPIO.LOW) t = MyThread(20) try: t.start() while True: i=GPIO.input(18) if i==1: t.intruder_spotted.set() time.sleep(1) except KeyboardInterrupt: GPIO.cleanup() exit(0)
type: UnansweredQuestion
tagged with: python
tagged with: arduino
type: Question
tagged with: automation
has answer: http://stackoverflow.com/a/52022318
score: 0
has title: Industrial PIR sensor always High
tagged with: sensors
answer count: 1

http://stackoverflow.com/comment/107181774
score: 0
has text: Thank you! This is the only response that worked in 2020. Everything out was outdated.
type: AnswerComment
comment on: http://stackoverflow.com/a/59554616
type: Comment

http://stackoverflow.com/q/52108417
type: AnsweredQuestion
tagged with: arrays
downvote count: 0
linked to: http://stackoverflow.com/q/13643363
has answer: http://stackoverflow.com/a/52110266
has title: How to apply linear regression to every pixel in a large multi-dimensional array containing NaNs?
favorite count: 0
tagged with: python-xarray
score: 19
type: Question
has comment: http://stackoverflow.com/comment/91197089
accepted answer: http://stackoverflow.com/a/52711081
tagged with: python
has comment: http://stackoverflow.com/comment/91235292
upvote count: 19
has answer: http://stackoverflow.com/a/52135253
has body: I have a 1D array of independent variable values (x_array) that match the timesteps in a 3D numpy array of spatial data with multiple time-steps (y_array). My actual data is much larger: 300+ timesteps and up to 3000 * 3000 pixels: import numpy as np from scipy.stats import linregress # Independent variable: four time-steps of 1-dimensional data x_array = np.array([0.5, 0.2, 0.4, 0.4]) # Dependent variable: four time-steps of 3x3 spatial data y_array = np.array([[[-0.2, -0.2, -0.3], [-0.3, -0.2, -0.3], [-0.3, -0.4, -0.4]], [[-0.2, -0.2, -0.4], [-0.3, np.nan, -0.3], [-0.3, -0.3, -0.4]], [[np.nan, np.nan, -0.3], [-0.2, -0.3, -0.7], [-0.3, -0.3, -0.3]], [[-0.1, -0.3, np.nan], [-0.2, -0.3, np.nan], [-0.1, np.nan, np.nan]]]) I want to compute a per-pixel linear regression and obtain R-squared, P-values, intercepts and slopes for each xy pixel in y_array, with values for each timestep in x_array as my independent variable. I can reshape to get the data in a form to input it into np.polyfit which is vectorised and fast: # Reshape so rows = number of time-steps and columns = pixels: y_array_reshaped = y_array.reshape(len(y_array), -1) # Do a first-degree polyfit np.polyfit(x_array, y_array_reshaped, 1) However, this ignores pixels that contain any NaN values (np.polyfit does not support NaN values), and does not calculate the statistics I require (R-squared, P-values, intercepts and slopes). The answer here uses scipy.stats import linregress which does calculate the statistics I need, and suggests avoiding NaN issues by masking out these NaN values. However, this example is for two 1D arrays, and I can't work out how to apply a similar masking approach to my case where each column in y_array_reshaped will have a different set of NaN values. My question: How can I calculate regression statistics for each pixel in a large multidimensional array (300 x 3000 x 3000) containing many NaN values in a reasonably fast, vectorised way? Desired result: A 3 x 3 array of regression stat…
has answer: http://stackoverflow.com/a/78300407
answer count: 5
possible better answer: http://stackoverflow.com/a/56633279
tagged with: scipy
has answer: http://stackoverflow.com/a/52711081
tagged with: numpy
has answer: http://stackoverflow.com/a/56633279

http://stackoverflow.com/comment/91168140
has text: @jezrael I removed it,but same error happens.
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/52108703

http://stackoverflow.com/comment/91047029
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52047814
has text: You may always edit your own question. I suggest you add a section at its bottom and place anything else you want there.
type: AnswerComment

http://stackoverflow.com/q/51983216
tagged with: python
favorite count: 0
upvote count: 2
has answer: http://stackoverflow.com/a/51983263
type: AnsweredQuestion
score: 2
accepted answer: http://stackoverflow.com/a/51983263
has body: The problem I'm trying to order a dataframe by two different variables at the same time, I'll post a small subsample of my dataframe as an example: +---------------------------+-------------------+-----------------------+-------------------------+---------------------------+-----------------------+---------------------+------------------+ | | Caldisericumexile | Haloplasmacontractile | Chthonomonascalidirosea | Desulfurispirillumindicum | Chrysiogenesarsenatis | Gracilimonastropica | Balneolavulgaris | +---------------------------+-------------------+-----------------------+-------------------------+---------------------------+-----------------------+---------------------+------------------+ | Caldisericumexile | 0 | 11.313708499 | 11.313708499 | 271.970586645 | 271.970586645 | 271.970586645 | 271.970586645 | +---------------------------+-------------------+-----------------------+-------------------------+---------------------------+-----------------------+---------------------+------------------+ | Haloplasmacontractile | 11.313708499 | 0 | 11.313708499 | 271.970586645 | 271.970586645 | 271.970586645 | 271.970586645 | +---------------------------+-------------------+-----------------------+-------------------------+---------------------------+-----------------------+---------------------+------------------+ | Chthonomonascalidirosea | 11.313708499 | 11.313708499 | 0 | 271.970586645 | 271.970586645 | 271.970586645 | 271.970586645 | +---------------------------+-------------------+-----------------------+-------------------------+---------------------------+-----------------------+---------------------+------------------+ | Desulfurispirillumindicum | 271.970586645 | 271.970586645 | 271.970586645 | 0 | 11.313708499 | 25.2982212813 | 25.2982212813 | +---------------------------+-------------------+-----------------------+-------------------------+---------------------------+-----------------------+---------------------+------------------+ | Chrysiogenesarsenatis | 27…
type: Question
has answer: http://stackoverflow.com/a/51983482
answer count: 2
downvote count: 0
possible better answer: http://stackoverflow.com/a/51983482
has title: Using pandas to order a dataframe alphabetically by values in one column and one row
tagged with: pandas

http://stackoverflow.com/comment/91097204
comment on: http://stackoverflow.com/q/52073722
has text: Don't post images of the sample dataframe or code
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/a/51970718
type: Answer
accepted answer of: http://stackoverflow.com/q/51970497
score: 4
has body: You need to remove fig.autofmt_xdate(rotation=90) as you aren't using dates and set the tick labels yourself with a rotation using ax.set_xticklabels(labels_go_here, rotation=90) fig, axs = plt.subplots(3,3, figsize=(10,10), sharey=True, sharex=False) for ax, df in zip(axs.ravel(), dfs): ax.bar(df['Passing-Player'], df['Passing-Yds']) ax.set_xticklabels(df['Passing-Player'], rotation=90) fig.tight_layout(pad=2.0, w_pad=2.0, h_pad=10.0) plt.show()
answers question: http://stackoverflow.com/q/51970497
upvote count: 4
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/90978982
score: 0
comment on: http://stackoverflow.com/a/52014282
has text: Thanks for the detailed response! Will make changes and report back!
type: AnswerComment
type: Comment

http://stackoverflow.com/a/52065587
has comment: http://stackoverflow.com/comment/91083157
has comment: http://stackoverflow.com/comment/91084986
has comment: http://stackoverflow.com/comment/91081779
has body: sounds like you might want something more like this? For each sentence, you get the mean of the word-sentiments, and then put that value in the DF. from textblob import TextBlob import pandas as pd import statistics as s df = pd.DataFrame({'text':['this is great!','how dare you?!']}) df['score'] = 0 for j in range(len(text.text)): lst=[] i = text.text[j] d = TextBlob(i) words_list=d.words for i in words_list: f = TextBlob(i) print(f.sentiment) lst.append(f.sentiment.polarity) z = s.mean(lst) df['score'][j] = z
score: 0
has comment: http://stackoverflow.com/comment/91082185
answers question: http://stackoverflow.com/q/52063689
has comment: http://stackoverflow.com/comment/91081924
type: Answer
has comment: http://stackoverflow.com/comment/91083493
has comment: http://stackoverflow.com/comment/91083950
has comment: http://stackoverflow.com/comment/91083214
has comment: http://stackoverflow.com/comment/91083093
has comment: http://stackoverflow.com/comment/91081962

http://stackoverflow.com/q/52006634
tagged with: django
type: Question
score: 2
linked to: http://stackoverflow.com/q/27634694
has body: I've opened my Django project in PyCharm, as I want to use a proper IDE instead of a text editor to better manage the project. When I run Find Usages on a function in /projectroot/app/views.py it says "No usages found in Project Files," but when I run CMD + SHIFT + F it finds 34 matches in 13 files. As suggested in this answer, I marked /projectroot/ directory as Sources Root did File > Invalidate Caches / Restart... in Find Options... I also tried to searching in All Places If I run Find Usages on some other functions in /projectroot/app/helpers.py it seems to work. Any ideas what else I could try?
tagged with: intellij-idea
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/90963236
tagged with: python
has comment: http://stackoverflow.com/comment/90963534
answer count: 0
tagged with: pycharm
upvote count: 2
has title: PyCharm No usages found in Project Files
type: UnansweredQuestion

http://stackoverflow.com/comment/91088400
type: QuestionComment
has text: @YuanChu please be sure about your data before you go for flattening. It may solve the problem of not getting error but it may not get you good model. Please understand the data and why data is representing that way. Dig up a little. It won't hurt!
type: Comment
comment on: http://stackoverflow.com/q/52055072
score: 0

http://stackoverflow.com/q/51974510
tagged with: printing
tagged with: dashboard
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/57376599
has body: Is there a way to create a section of a bokeh dashboard that shows the console output from the python session? I am creating a front-end dashboard with bokeh that runs a process that can take a while and does a lot of stuff. I wanted a section that would show some of the print statements that are executed along the way. Ideally I was hoping for a little widget type object that could display the output directly within the dashboard.
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/90930526
has title: How can I show and update a list of print statements in a Bokeh dashboard?
tagged with: python
has comment: http://stackoverflow.com/comment/101219743
has comment: http://stackoverflow.com/comment/90920009
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/57376599
tagged with: bokeh
has comment: http://stackoverflow.com/comment/90911486
type: Question
has comment: http://stackoverflow.com/comment/101236781
score: 4
upvote count: 4

http://stackoverflow.com/a/51996223
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/90941943
has comment: http://stackoverflow.com/comment/90941893
has body: async is a reserved keyword in Python 3 (here's the full list). Look like you aren't the only one running into this problem, there's an active thread on the tensorflow github issue tracker addressing it that dates back to July: https://github.com/tensorflow/tensorflow/issues/20517
has comment: http://stackoverflow.com/comment/90942257
upvote count: 1
type: AcceptedAnswer
type: Answer
accepted answer of: http://stackoverflow.com/q/51996163
answers question: http://stackoverflow.com/q/51996163

http://stackoverflow.com/a/52000674
downvote count: 0
has body: You are almost close, all you need is appropriate regex and use casting (that you have already done) after the regexp_replace and split inbuilt functions. so the correct and working solution would be as df = spark.read.csv('Kindle.csv', sep='|', header=None) oldColumns = df.schema.names newColumns = ["asin", "helpful", "overall", "Reviewtext", "reviewTime", "reviewerID", "reviewerName", "summary", "unixReviewTime"] df = reduce(lambda df, idx: df.withColumnRenamed(oldColumns[idx], newColumns[idx]), range(len(oldColumns)), df) from pyspark.sql import functions as F df = df.withColumn("helpful", F.split(F.regexp_replace(F.col("helpful"), "[\[\] ]", ""), ",").cast('array&lt;int&gt;'))\ .withColumn('useful_review', F.col('helpful')[0])\ .withColumn('voted_review', F.col('helpful')[1])\ .drop('helpful') so df would be +----------+-------+--------------------+-----------+--------------+--------------------+--------------------+--------------------+-------------+------------+ | asin|overall| Reviewtext| reviewTime| reviewerID| reviewerName| summary| unixReviewTime|useful_review|voted_review| +----------+-------+--------------------+-----------+--------------+--------------------+--------------------+--------------------+-------------+------------+ |B000F83SZQ| 5.0|I enjoy vintage b...| 05 5, 2014|A1F6404F1VG29J| Avidreader| Nice vintage story|1399248000 ...| 0| 0| |B000F83SZQ| 4.0|This book is a re...| 01 6, 2014| AN0N05A9LIJEQ| critters| Different...|1388966400 ...| 2| 2| |B000F83SZQ| 4.0|This was a fairly...| 04 4, 2014| A795DMNCJILA6| dot| Oldie|1396569600 ...| 2| 2| |B000F83SZQ| 5.0|I'd never read an...|02 19, 2014|A1FV0SX13TWVXQ|Elaine H. Turley ...| I really liked it.|1392768000 ...| 1| 1| |B000F83SZQ| 4.0|If you like perio...|03 19, 2014|A3SPTOKDG7WBLN| Father Dowling Fan| Period Mystery|1395187200 ...| 0| 1| |B000F83SZQ| 4.0|A beautiful in-de...|05 26, 2014|A1RK2OCZDSGC6R| ubavka seirovska| Review|1401062400 ...| 0| 0| |B000F83SZQ| 4.0|I enjoyed this on...|06 10, 20…
type: Answer
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/51990946
has comment: http://stackoverflow.com/comment/91001491

http://stackoverflow.com/q/51986259
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51995190
accepted answer: http://stackoverflow.com/a/51986476
score: 3
tagged with: python
favorite count: 0
possible better answer: http://stackoverflow.com/a/51995190
type: Question
upvote count: 3
answer count: 2
has body: With the unittest module, how can I test FileNotFoundError is raised when opening a file as follows: func(filename): try: file = open(filename) except FileNotFoundError: exit() Unittest module class TestFunc(unittest.TestCase): def test_func(self): self.assertRaises(FileNotFoundError, func, "no_exist.txt") Resulting error AssertionError: FileNotFoundError not raised by func
tagged with: unit-testing
has answer: http://stackoverflow.com/a/51986476
has title: How to properly unit test FileNotFoundError
downvote count: 0

http://stackoverflow.com/a/52661292
score: 2
upvote count: 2
downvote count: 0
has body: You may need to pass the session_token information too as a parameter. Like this.. auth = AWS4Auth(credentials.access_key, credentials.secret_key, region, service, session_token=credentials.token) as shown here
type: Answer
answers question: http://stackoverflow.com/q/52084215

http://stackoverflow.com/q/52084122
tagged with: python
accepted answer: http://stackoverflow.com/a/52084605
tagged with: networkx
type: AnsweredQuestion
downvote count: 0
has title: Python NetworkX - get DiGraph from nested dictionaries
score: 1
has answer: http://stackoverflow.com/a/52084605
type: Question
tagged with: graph
tagged with: digraphs
upvote count: 1
has body: I am trying to create a simple DiGraph in python's NetworkX from nested dictionary but it looks like built in initialization doesn't built final leaf nodes. Toy example: class_hierarchy= {-1: ["A", "B"], "A":{"A1":[1], "A2":[3,4]}, "B": {"B1":[5,6], "B2": [7,8]}} Building graph: G = DiGraph(class_hierarchy) Now let's see what we have in it: G.nodes Out[86]: NodeView((-1, 'A', 'B', 'A1', 'A2', 'B1', 'B2')) Looks like final nodes are not added Checking it: list(G.successors('A')) Out[88]: ['A1', 'A2'] Looks reasonable But: list(G.successors('A1')) Out[89]: [] I am not sure why this is the case? Documentation for NetworkX specifies that: incoming_graph_data (input graph (optional, default: None)) – Data to initialize graph. If None (default) an empty graph is created. The data can be any format that is supported by the to_networkx_graph() function, currently including edge list, dict of dicts, dict of lists, etc... Any idea what I am doing wrong?
answer count: 1
favorite count: 0

http://stackoverflow.com/a/51987149
has body: Because a set is an un-ordered collection of items, by definition. There it no "first" or "last" element. So, it removes a random one. If you want order, use a list instead.
type: AcceptedAnswer
downvote count: 0
type: Answer
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/51987093
accepted answer of: http://stackoverflow.com/q/51987093

http://stackoverflow.com/a/52062986
type: Answer
has body: If your intention is to apply the dictionary keys sorted by their values, then you can do this: df.columns = [df.columns[0]] \ + [k for k,_ in sorted(data_dict.items(), key=lambda x:x[1])]
answers question: http://stackoverflow.com/q/52062893
has comment: http://stackoverflow.com/comment/91077161
has comment: http://stackoverflow.com/comment/91076627
score: 0

http://stackoverflow.com/comment/91135871
comment on: http://stackoverflow.com/q/52092887
score: 0
has text: You can merge two or more data frames using [pandas.DataFrame.merge](https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.merge.html)
type: Comment
type: QuestionComment

http://stackoverflow.com/a/51987760
has comment: http://stackoverflow.com/comment/90927599
has comment: http://stackoverflow.com/comment/90926213
has comment: http://stackoverflow.com/comment/90925904
upvote count: 1
has body: As per your question to click() on a random link from google search results, as per your code trial if you invoke window.scrollTo(0, 873) and then invoke click() as in: find_element(By.XPATH, '(//h3)[3]/a').click()` Selenium will still try to attempt click() on the first match, which may not be your desired usecase. Solution Inorder to click() on a random link from google search results, you can create a List out of the search results and then generate a Random Number and invoke click() through an index as follows: Code Block: from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.keys import Keys from random import randint options = webdriver.ChromeOptions() options.add_argument("start-maximized") options.add_argument('disable-infobars') browser=webdriver.Chrome(chrome_options=options, executable_path=r'C:\Utility\BrowserDrivers\chromedriver.exe') browser.get('http://www.google.com') search = browser.find_element_by_name('q') search.send_keys("selenium") search.send_keys(Keys.RETURN) my_search_list = WebDriverWait(browser, 10).until(EC.visibility_of_all_elements_located((By.XPATH, "//h3[@class='r']/a[not(ancestor::div[@class='xIleA'])]"))) myRandomNumber = randint(0, len(my_search_list)) print(myRandomNumber) my_search_list[myRandomNumber].click() Console Output: 4
score: 1
has comment: http://stackoverflow.com/comment/90927255
has comment: http://stackoverflow.com/comment/90928151
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/90927469
has comment: http://stackoverflow.com/comment/90926165
has comment: http://stackoverflow.com/comment/90927139
accepted answer of: http://stackoverflow.com/q/51976238
has comment: http://stackoverflow.com/comment/90927685
has comment: http://stackoverflow.com/comment/90926683
answers question: http://stackoverflow.com/q/51976238
type: Answer
has comment: http://stackoverflow.com/comment/90928201
has comment: http://stackoverflow.com/comment/90927093
has comment: http://stackoverflow.com/comment/90926263

http://stackoverflow.com/a/52110566
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/52084840
type: AcceptedAnswer
has body: That happens because you're calling button.handle_event(event) for each button in the self.all_sprites group in a for loop, so you're printing print( Button.whichButton(event)+' mouse pressed at ' + str(event.pos)) for each button. def handle_events(self): for event in pg.event.get(): if event.type == pg.QUIT: self.done = True # Iterates over all buttons in the group and calls their `handle_event` method. for button in self.all_sprites: button.handle_event(event)
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52084840
type: Answer
has comment: http://stackoverflow.com/comment/91176786
has comment: http://stackoverflow.com/comment/91175579

http://stackoverflow.com/a/74666973
score: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/52096704
answers question: http://stackoverflow.com/q/52096704
has body: Be aware of using of spawning multiple processes for NGINX. Every process handles its own cache. Without an additional layer, it is not possible to access to a cache from different nginx process. This answer was posted as an edit to the question Flask-Caching use UWSGI cache with NGINX by the OP ewro under CC BY-SA 4.0.
type: AcceptedAnswer

http://stackoverflow.com/q/52061357
downvote count: 2
tagged with: import-csv
tagged with: python
has body: I'm trying to convert all string values to floating values to make an addition but, there are strings present in my csv, and it returns this error: L.append([i, j, sum(i for i in map(float, filter(None, k)) if i in {0.5, 1, 2})]) ValueError: could not convert string to float: 'l0g0dim' How can i ignore strings with letters, comma, and other non-convertible characters and sum them with out problem ? Sample file3.csv 1754|2014-06-13 07:00:00|0|0.5|0 1754|2014-06-13 08:00:00|0|2|0.5 1754|2014-06-13 09:00:00|0|a0|b0|2 1278|2014-01-26 18:00:00|light subcoatal draft ...|0|0|2|0.5 1754|2014-06-04 19:00:00|0|leg dim|0|0 1754|2014-06-13 10:00:00|0|(C) fins|0|0 Code import csv import re import time from io import StringIO replacements = ( ("(B)", "0"), ("(D)", "1"), ("Entrée air absente", "2"), ("+", "0.5"), ("++", "1"), ("+++", "2"), ("(S) +", "0.5"), ("(S) expi. ++", "1"), ("(S) +++", "2"), ("100", "0"), ("99", "0"), ("98", "0"), ("97", "0"), ("96", "0"), ("95", "0"), ("94", "1"), ("93", "1"), ("92", "1"), ("91", "1"), ("90", "1"), ("89", "1"), ("Bruits de transmission", "0"), ("Fatigué/épuisé", "0"), (" *", "0"), ("tirage sous costal", "0"), ("léger BAN", "0"), ) replvalues = dict(replacements) regex = "|".join(map(re.escape, replvalues.keys())) repl = lambda x: replvalues.get(x.string[x.start():x.end()]) with open("file3.csv", "r", encoding='utf-8') as f_in, \ open("file4.csv", "w", encoding='utf-8') as f_out: for i in f_in: line = re.sub(regex, repl, i) f_out.write(line) with open("file4.csv", "r", encoding='utf-8') as f_in, \ open("file5.csv", "w", encoding='utf-8') as f_out: L = [] with f_in as fin: reader = csv.reader(fin, delimiter='|') for i, j, *k in reader: L.append([i, j, sum(i for i in map(float, filter(None, k)) if i in {0.5, 1, 2})]) f_out.write(L) print(L)
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/52061443
upvote count: 3
score: 1
has comment: http://stackoverflow.com/comment/91072966
has answer: http://stackoverflow.com/a/52061495
has comment: http://stackoverflow.com/comment/91072901
has answer: http://stackoverflow.com/a/52061443
has comment: http://stackoverflow.com/comment/91073050
type: Question
accepted answer: http://stackoverflow.com/a/52061495
answer count: 2
has title: Ignoring all the non float value when convert string to float to sum them
tagged with: http://stackoverflow.com/tag/csv
favorite count: 0
tagged with: python-3.x

http://stackoverflow.com/q/52072640
tagged with: tensorflow
type: Question
downvote count: 0
favorite count: 0
has title: What are the operations allowed in tensorflow loss function definition?
linked to: http://stackoverflow.com/q/37900780
answer count: 0
type: UnansweredQuestion
upvote count: 1
tagged with: python
score: 1
has body: I learned that we need to use tf.OPERATIONS to define the computation graph, but I found sometimes, using + or = are just fine, without using tf.add or tf.assign see here. My question is that what are the operations allowed in tensorflow loss function definition without using "tf.OPERATIONS". In other words, other than + and = what else? can we use for example *, or ^2 on variables? PS: I just do not understand why x*x is ok but x^2 is not ...

http://stackoverflow.com/q/52053103
type: UnansweredQuestion
tagged with: python
has body: I run following code : import easygui easygui.ynbox('Shall I continue?', 'Title', ('Yes', 'No')) easygui.msgbox('This is a basic message box.', 'Title Goes Here'); but i get different window for ynbox and msgbox ,i want bot both of them to be included in same window
score: 0
type: Question
has answer: http://stackoverflow.com/a/57044251
answer count: 1
has title: How to add ynbox and messagebox in same window using easygui
tagged with: python-3.x
tagged with: easygui

http://stackoverflow.com/a/51966101
has comment: http://stackoverflow.com/comment/90916090
accepted answer of: http://stackoverflow.com/q/51963938
has body: To calculate the index, you can use next with a generator expression and str.isalpha / enumerate. Then use string slicing as normal. Here's a demo: a = '% 0.9 Saline solution' b = '2% Taurolidine Lock' c = '2 DAA' def get_string(x): idx = next(i for i, j in enumerate(x) if j.isalpha()) return x[idx:] for val in [a, b, c]: print(val, ':', get_string(val)) % 0.9 Saline solution : Saline solution 2% Taurolidine Lock : Taurolidine Lock 2 DAA : DAA
score: 0
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/51963938
type: Answer

http://stackoverflow.com/q/52026360
has answer: http://stackoverflow.com/a/66061326
has body: I am using multiple conda environments, and use Spyder as my IDE. These environments often have the same python version, and differ based on installed packages (packages not used by spyder). I looked how to run spyder in a certain environment, and the answers i found all state that i first have to install spyder in that environment and then run it. However, this of course requires extra space used on my computer. Is there a way to use spyder in different conda environments, without installing spyder multiple times (or maybe just once per python version)? Thanks in advance!
tagged with: spyder
tagged with: python
type: AnsweredQuestion
upvote count: 10
accepted answer: http://stackoverflow.com/a/66061326
type: Question
score: 10
possible better answer: http://stackoverflow.com/a/52043159
has title: Switch Spyder Environment without installing spyder at each environment
tagged with: conda
has answer: http://stackoverflow.com/a/52043159
answer count: 2
downvote count: 0
favorite count: 0

http://stackoverflow.com/a/55399961
type: Answer
has comment: http://stackoverflow.com/comment/98139090
score: 2
upvote count: 3
downvote count: 1
has body: Both solutions - dt.components or np.timedelta64 - are useful. But the np.timedelta64 is (1) much faster than dt.components (good to know especially for large dataframes) (2, as @Sam Chats noted) also takes into account the difference in days. For time comparison: import pandas as pd import numpy as np dct = { 'date1': ['08:05:23', '18:07:20', '08:05:23'], 'date2': ['09:15:24', '22:07:20', '08:54:01'] } df = pd.DataFrame(dct) df['date1'] = pd.to_datetime(df['date1'], format='%H:%M:%S') df['date2'] = pd.to_datetime(df['date2'], format='%H:%M:%S') df['delta'] = df['date2']-df['date1'] %timeit df['np_h'] = (df['delta'] / np.timedelta64(1,'h')).astype(int) %timeit df['td_h'] = df['delta'].dt.components['hours'] Output: 1000 loops, best of 3: 484 µs per loop 1000 loops, best of 3: 1.43 ms per loop
answers question: http://stackoverflow.com/q/52093199

http://stackoverflow.com/comment/97257757
type: QuestionComment
comment on: http://stackoverflow.com/q/51989279
has text: I didn't find a solution. I didn't use odo because of this.
score: 0
type: Comment

http://stackoverflow.com/comment/90938802
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51994134
has text: @BlackFenix06 As I said you cannot add a number to a string.
score: 0

http://stackoverflow.com/comment/91079950
type: Comment
has text: Have you try a breakpoint? I think it does, but I think `return self.datetime_field.to_internal_value(value)` returns *None* if `value` is 'null'
type: AnswerComment
comment on: http://stackoverflow.com/a/52064687
score: 0

http://stackoverflow.com/comment/91121279
type: Comment
has text: @ajwood No, just being thorough and explicit about the indexing. They're both the same.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52085417

http://stackoverflow.com/q/51986724
score: 2
downvote count: 0
favorite count: 0
has title: Control order of plotting on Seaborn plot in Python
answer count: 1
has answer: http://stackoverflow.com/a/51986865
upvote count: 2
tagged with: seaborn
tagged with: python
type: AnsweredQuestion
tagged with: matplotlib
accepted answer: http://stackoverflow.com/a/51986865
type: Question
has body: I am trying to plot residuals on a linear regression plot. It works, with only one caveat. There is an unpleasant looking overlap between residuals and data points. Is there a way to tell matplotlib to plot the residuals first followed by Seaborn plot. I tried changing the order of code, but it didn't help. import numpy as np import pandas as pd import seaborn as sns from pylab import * from sklearn.linear_model import LinearRegression x = np.array([1, 2, 3, 4, 5, 7, 8, 9, 10]) y = np.array([-3, 0, 4, 5, 9, 5, 7, 7, 12]) dat = pd.DataFrame({'x': x, 'y': y}) x = x.reshape(-1,1) y = y.reshape(-1,1) linear_model = LinearRegression() linear_model.fit(X=x, y=y) pred = linear_model.predict(x) for ix in range(len(x)): plot([x[ix], x[ix]], [pred[ix], y[ix]], '#C9B97D') g = sns.regplot(x='x', y='y', data=dat, ci=None, fit_reg=True) sns.set(font_scale=1.1) g.figure.set_size_inches(6, 6) sns.set_style('ticks') sns.despine()

http://stackoverflow.com/comment/91017473
comment on: http://stackoverflow.com/q/52033607
type: Comment
type: QuestionComment
score: 2
has text: There is an entire SE called https://codereview.stackexchange.com/ for these situations I think (Not sure if yours will fit better there).

http://stackoverflow.com/comment/90953008
type: QuestionComment
has text: If you intend to find "said", then find it. Why are you looking for double quotes `"`?
score: 0
comment on: http://stackoverflow.com/q/52001828
type: Comment

http://stackoverflow.com/q/52064868
has comment: http://stackoverflow.com/comment/91119518
accepted answer: http://stackoverflow.com/a/52094332
type: Question
type: AnsweredQuestion
has body: The Firebase API provides a convenience function Storage::refFromUrl (source) that converts a URL into a storage reference. From the source (location.ts) It looks like it's a straightforward Regular expression. Is there an equivalent Python method that works with the google-cloud-storage API to get the bucket and path?
tagged with: google-cloud-storage
score: 0
answer count: 1
has answer: http://stackoverflow.com/a/52094332
tagged with: python
has title: Is there an equivalent to `refFromUrl` in google-cloud-storage for Python?

http://stackoverflow.com/comment/91142750
type: Comment
has text: beautifulsoup4==4.6.3 numpy==1.15.0 pandas==0.20.3 requests==2.19.1 Updated all modules but I still get this error "Object 'None' has no member 'content'"
comment on: http://stackoverflow.com/q/52049257
score: 0
type: QuestionComment

http://stackoverflow.com/comment/91193254
type: AnswerComment
type: Comment
has text: When I try it I get this error: ValueError: Unknown interpolation method array([1.32802 , 1.38199939, 1.43597878, 1.48995816, 1.54393755, (...) 1.86781388, 1.92179327, 1.97577265, 2.02975204, 2.08373143, 3.91903061, 3.97301 ]) for 1 dimensional data
comment on: http://stackoverflow.com/a/52106864
score: 0

http://stackoverflow.com/comment/91129201
type: QuestionComment
type: Comment
score: 0
has text: get_route(segments,segments ) does not seem to work ? is that how you are calling ?
comment on: http://stackoverflow.com/q/52089186

http://stackoverflow.com/comment/90895820
score: 0
type: Comment
has text: At what stage can I call to_json()? I.e. do I have to call .compile() first? Can it be before fit() ?
comment on: http://stackoverflow.com/a/51972601
type: AnswerComment

http://stackoverflow.com/comment/91148594
comment on: http://stackoverflow.com/a/52098394
has text: @Nick Yes, you are correct. Just like linux commands, `from . import` refers to files in same folder, and `from .. import` goes to root level.
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/90979054
comment on: http://stackoverflow.com/a/52014282
type: AnswerComment
has text: No worries, it's 6am here so will get some sleep but will check in first thing. I have another potential solution that you might be able to user as well - but it may bloat your DB over time.
type: Comment
score: 1

http://stackoverflow.com/a/52072552
has body: If I have got your question correctly then you are trying to keep count of each character in a string and store the result in a list. The brute force way of doing is using a dictionary to keep track of character and number of times it has appeared. Here is the code: st= "kkikkd" l=[] temp=1 for i in range(1,len(st)): if st[i-1] == st[i]: temp += 1 else: l.append([st[i-1],temp]) temp= 1 if st[i] == st[i-1]: temp += 1 l.append([st[i],temp]) output: [['k', 2], ['i', 1], ['k', 2], ['d', 1]]
upvote count: 1
accepted answer of: http://stackoverflow.com/q/52072181
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/91097712
answers question: http://stackoverflow.com/q/52072181
has comment: http://stackoverflow.com/comment/91095983
type: Answer
downvote count: 0
has comment: http://stackoverflow.com/comment/91096927
has comment: http://stackoverflow.com/comment/91098135
score: 1
has comment: http://stackoverflow.com/comment/91096673

http://stackoverflow.com/comment/91168969
type: Comment
type: QuestionComment
has text: in get() use self.saved_objectID = editObjectId but not sure if class instance will be available for different calls
score: 0
comment on: http://stackoverflow.com/q/52108846

http://stackoverflow.com/comment/90953779
comment on: http://stackoverflow.com/a/52002192
type: AnswerComment
has text: Likely not. I simply wasn't aware of underlying attribute being public and documented.
type: Comment
score: 1

http://stackoverflow.com/q/52112336
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91175706
has comment: http://stackoverflow.com/comment/91175403
type: Question
has comment: http://stackoverflow.com/comment/91175473
answer count: 1
tagged with: python-2.7
score: 0
has body: I have a JSON with non ascii value: my_json = { 'mykey': 'bbür'} I am trying to print or display this JSON and what I see is: print my_json {'mykey': 'bb\xc3\xbcr'} I want to print or display like: { 'mykey': 'bbür'} I googled and tried the following but it seems not to be working: print unicode(my_json).encode('utf-8') print unicode(my_json).decode('utf-8') print unicode(my_json).encode('ascii') print unicode(my_json).encode('ascii') print ord(j['mykey'])
has answer: http://stackoverflow.com/a/52112663
tagged with: python
has title: Printing non ascii characters

http://stackoverflow.com/a/51961584
downvote count: 0
score: 28
has comment: http://stackoverflow.com/comment/136888382
upvote count: 28
has body: &gt;&gt;&gt;a = [1,2,3,4,5,6] &gt;&gt;&gt;print (len(a)) 6 For one dimensional lists, the above method can be used. len(list_name) returns number of elements in the list. &gt;&gt;&gt;a = [[1,2,3],[4,5,6]] &gt;&gt;&gt;nrow = len(a) &gt;&gt;&gt;ncol = len(a[0]) &gt;&gt;&gt;nrow 2 &gt;&gt;&gt;ncol 3 The above gives the dimension of the list. len(a) returns number of rows. len(a[0]) returns number of rows in a[0] which is the number of columns. Here's a link to original answer.
type: Answer
answers question: http://stackoverflow.com/q/51960857
has comment: http://stackoverflow.com/comment/138288987
has comment: http://stackoverflow.com/comment/138288923

http://stackoverflow.com/a/52117803
score: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/51988363
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/51988363
has body: The following is what worked for me: Get rid of the try/except blocks. Find elements via ID's (not xpath). That allowed me to extract text from elements I couldn't extract from before.

http://stackoverflow.com/q/51998131
answer count: 2
score: 5
upvote count: 5
possible better answer: http://stackoverflow.com/a/51998197
has answer: http://stackoverflow.com/a/51998200
has answer: http://stackoverflow.com/a/51998197
tagged with: pandas-groupby
tagged with: pandas
downvote count: 0
accepted answer: http://stackoverflow.com/a/51998200
favorite count: 0
tagged with: python
type: AnsweredQuestion
has title: Filter a GroupBy object where at least 1 row fulfills the condition
has body: Let's say there's this test_df: test_df = pd.DataFrame({'Category': ['P', 'P', 'P', 'Q', 'Q', "Q"], 'Subcategory' : ['A', 'B', 'C', 'C', 'A', 'B'], 'Value' : [2.0, 5., 8., 1., 2., 1.]}) Doing this gives: test_df.groupby(['Category', 'Subcategory'])['Value'].sum() # Output is this Category Subcategory P A 2.0 B 5.0 C 8.0 Q A 2.0 B 1.0 C 1.0 I want to filter for Categories where at least one value in the Subcategory is more than or equal to 3. Meaning in the current test_df, Q will be excluded from the filter as none of its rows are greater than or equal to 3. If one of its rows is 5, however, then Q will remain in the filter. I have tried using the following, but it filters out the 'A' Subcategory in Category 'P'. test_df_grouped = test_df.groupby(['Category', 'Subcategory']) test_df_grouped.filter(lambda x: (x['Value'] &gt; 2).any()).groupby(['Category', 'Subcategory'])['Value'].sum() Thank you in advance!
type: Question

http://stackoverflow.com/q/52012636
type: Question
has title: Logistic Regression different results with R and Python?
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/52012700
has comment: http://stackoverflow.com/comment/90976289
score: -2
tagged with: statistics
tagged with: http://stackoverflow.com/tag/r
linked to: http://stackoverflow.com/q/27558067
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/52012700
tagged with: python
has comment: http://stackoverflow.com/comment/90976216
tagged with: regression
downvote count: 3
upvote count: 1
has body: I used a logistic regression approach in both programs, and was wondering why I am getting different results, especially with the coefficients. The outcome, Infection, is (1, 0) and Flushed is a continuous variable. Python: import statsmodels.api as sm logit_model=sm.Logit(data['INFECTION'], data['Flushed']) result=logit_model.fit() print(result.summary()) Results: Logit Regression Results ============================================================================== Dep. Variable: INFECTION No. Observations: 414 Model: Logit Df Residuals: 413 Method: MLE Df Model: 0 Date: Fri, 24 Aug 2018 Pseudo R-squ.: -1.388 Time: 15:47:42 Log-Likelihood: -184.09 converged: True LL-Null: -77.104 LLR p-value: nan ============================================================================== coef std err z P&gt;|z| [0.025 0.975] ------------------------------------------------------------------------------ Flushed -0.6467 0.070 -9.271 0.000 -0.783 -0.510 ============================================================================== R: mylogit &lt;- glm(INFECTION ~ Flushed, data = cvc, family = "binomial") summary(mylogit) Results: Call: glm(formula = INFECTION ~ Flushed, family = "binomial", data = cvc) Deviance Residuals: Min 1Q Median 3Q Max -1.0598 -0.3107 -0.2487 -0.2224 2.8051 Coefficients: Estimate Std. Error z value Pr(&gt;|z|) (Intercept) -3.91441 0.38639 -10.131 &lt; 2e-16 *** Flushed 0.22696 0.06049 3.752 0.000175 *** --- Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1

http://stackoverflow.com/a/51992385
accepted answer of: http://stackoverflow.com/q/51992344
type: Answer
has comment: http://stackoverflow.com/comment/90934970
answers question: http://stackoverflow.com/q/51992344
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/90934927
has body: Use broadcasted XOR. (shortened.values ^ shortened.values[:, None]).sum(2) array([[0, 1, 2], [1, 0, 3], [2, 3, 0]]) XOR is the easiest (and fastest) way of checking whether two bits are the same. This should work as long as your input is binary. Note that this is memory intensive, especially for very large frames, with a chance of OOM at ~1M rows.
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/52065521
linked to: http://stackoverflow.com/q/11367140
has title: python-gnupg sign / verify a tar archive
tagged with: gpg-signature
upvote count: 1
tagged with: gnupg
type: Question
score: 1
has comment: http://stackoverflow.com/comment/91083027
has comment: http://stackoverflow.com/comment/91117630
has answer: http://stackoverflow.com/a/52083721
has body: I am using python-gpg to sign / encrypt / verify / decrypt a tar archive. code snippet - # import private key into gnupghome _pvtKey = urllib2.urlopen(_certurl) _pv_data = _pvtKey.read() gpg.import_keys(_pv_data) ..... stream = open("/tar/at/some/path/arh.tar", "rb") status = gpg.sign_file(stream, passphrase=_salt, detach=True, output="/output/sig/here.sig") The code generated sig file just fine. However, if I try to verify the sig / tar using public keys, i receive following message - gpg: armor header: Version: GnuPG v1 gpg: Signature made Tue 28 Aug 2018 07:48:28 PM UTC using RSA key ID 6B93AF63 gpg: using PGP trust model gpg: BAD signature from "abc@def.com" gpg: binary signature, digest algorithm SHA1 On contrary, if i try to generate sig file directly on linux and verify, it works fine. I am loosing my mind on this, any pointers pls?
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/91084866
favorite count: 0
type: UnansweredQuestion
tagged with: python

pipeline
type: Tag
tags question: http://stackoverflow.com/q/52055658
tags question: http://stackoverflow.com/q/52106725
tag name: pipeline
tags question: http://stackoverflow.com/q/52073866

http://stackoverflow.com/q/51972597
score: 3
has answer: http://stackoverflow.com/a/60053650
linked to: http://stackoverflow.com/q/42807676
type: Question
has body: I have a question that was somehow discussed here ([python][selenium] on-screen position of element) but that doesn't currently do what I'm trying to achieve. My goal is the following: element.location gives the position of the top left corner of element in the browswer. I have a website in which, even if it's probably not a good selenium practice, I want to be able to click on such element purely based on its position because it has never changed and likely never will. Assuming element.location gives {'x': 253, 'y': 584}, this is the code I tried so far with no luck from selenium import webdriver from selenium.webdriver.common.action_chains import ActionChains driver.maximize_window() url = "https://learn.letskodeit.com/p/practice" driver.get(url) open_window_elem = driver.find_element_by_id("openwindow") # from wherever the mouse is, I move to the top left corner of the broswer action = ActionChains(driver) action.move_by_offset(-1000, -1000) action.click() action.perform() y_coordinate = open_window_elem.location["y"] x_coordinate = open_window_elem.location["x"] action = ActionChains(driver) action.move_by_offset(x_coordinate, y_coordinate) action.click() action.perform() Nothing happens when I run this code. I would except to open a new window. Can somebody help?
has comment: http://stackoverflow.com/comment/90920063
tagged with: position
has answer: http://stackoverflow.com/a/51982982
upvote count: 3
has answer: http://stackoverflow.com/a/51987080
answer count: 3
tagged with: python
has comment: http://stackoverflow.com/comment/90922479
has comment: http://stackoverflow.com/comment/90916104
favorite count: 0
tagged with: selenium-webdriver
has comment: http://stackoverflow.com/comment/90922334
tagged with: selenium-chromedriver
downvote count: 0
linked to: http://stackoverflow.com/q/6775351
type: UnansweredQuestion
has title: Python Selenium - click on element purely based on its location based on body element offset
has comment: http://stackoverflow.com/comment/90922461
has comment: http://stackoverflow.com/comment/90923362

http://stackoverflow.com/comment/91055584
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/52049514
has text: You have no `replace()` calls in your code related to image path. Obviously you have an error in another part of your `test.py`
type: Comment

http://stackoverflow.com/comment/91017123
has text: I tried by keeping it in killa.js . ( app.directive("killa", function ($compiler, $httpProvider) { $httpProvider.defaults.xsrfCookieName = 'csrftoken'; $httpProvider.defaults.xsrfHeaderName = 'X-CSRFToken'; ) But the form disappear. There is also separate killa.html file which has form as register.html.
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/52031838
score: 0

http://stackoverflow.com/q/52071239
has answer: http://stackoverflow.com/a/75119027
has answer: http://stackoverflow.com/a/52102100
type: Question
tagged with: google-sheets-api
has title: Adding a new spreadsheet in an existing workbook raises HttpError "Unknown name requests"
downvote count: 0
accepted answer: http://stackoverflow.com/a/52072077
has comment: http://stackoverflow.com/comment/91093134
has comment: http://stackoverflow.com/comment/91093393
favorite count: 0
answer count: 3
tagged with: google-api-python-client
has comment: http://stackoverflow.com/comment/91092611
has comment: http://stackoverflow.com/comment/91093291
has comment: http://stackoverflow.com/comment/91092811
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/91093701
has body: I'm done building the Google Sheets service with the code snippet shown below and I would like to know how to create a new spreadsheet (aka tab) inside an already existing Google Sheet (workbook) with Python. credentials = get_credentials(client_secret_file_path) service = build('sheets', 'v4', credentials=credentials) add_tab_request = {"requests": {"addSheet": {"properties": {"title": "New Tab"}}}} request = service.spreadsheets().values().batchUpdate(spreadsheetId=&lt;google_sheet_id&gt;, body=add_tab_request) Executing this code gives an HttpError: Invalid JSON payload received. Unknown name "requests": Cannot find field. The full error: googleapiclient.errors.HttpError: https://sheets.googleapis.com/v4/spreadsheets//values:batchUpdate?alt=json returned "Invalid JSON payload received. Unknown name "requests": Cannot find field.">` I did a lot of Google searching, but could not find a solution to this problem. I did not find this in the Google Sheets API v4 official documentation either. Why does not my request work?
has answer: http://stackoverflow.com/a/52072077
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/52102100
score: 1
has comment: http://stackoverflow.com/comment/91093582

http://stackoverflow.com/comment/91044704
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51997994
type: AnswerComment
has text: I was able to adapt your code from the other question, and it runs but does not learn.

http://stackoverflow.com/comment/90871659
type: AnswerComment
type: Comment
has text: @sysuser. Glad that you found what you were looking for. Please verify the answer. :)
score: 0
comment on: http://stackoverflow.com/a/51960666

http://stackoverflow.com/q/52076415
tagged with: machine-learning
tagged with: python
has comment: http://stackoverflow.com/comment/91138744
has body: I have a dataset that has one categorical and multiple continuous variables as follows: A B C 2.0 1.0 foo 2.2 1.2 bar 1.0 1.5 foo I wish to compute: Pr(C='foo'| A=2.0) # column A Pr(C='foo'| A=1.0) # column A Pr(C='bar'| A=2.2) # column A Pr(C='foo'| B=1.0) # column B Pr(C='bar'| B=1.2) # column B What will be an correct approach to solving this? Will it be valid to group the values in A and B into brackets or to compute for every random variable in A and B? Thanks!
has comment: http://stackoverflow.com/comment/91114232
score: 1
has comment: http://stackoverflow.com/comment/91102619
type: Question
upvote count: 2
has answer: http://stackoverflow.com/a/52082803
answer count: 2
has title: Calculating Conditional Probabilities for Categorical and Continuous variables in python? P(categorical|continuous)
favorite count: 0
tagged with: statistics
downvote count: 1
has answer: http://stackoverflow.com/a/52082395
has comment: http://stackoverflow.com/comment/91154249
has comment: http://stackoverflow.com/comment/91120057
has comment: http://stackoverflow.com/comment/91160419
tagged with: classification
type: UnansweredQuestion
tagged with: probability

http://stackoverflow.com/comment/132717278
has text: For a user token, try following [these instructions](https://discordjs.guide/oauth2/#getting-an-oauth2-url)
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/61442389

http://stackoverflow.com/comment/91179376
has text: @ElBrutale, the `mockb_update.return_value` does make any difference here, the default value is a `Mock()` object. if the nodes are different types of class, you could try multiple patches, or to patch `A.update()` to get minimum coverage such as method exists, call_args, called_with etc.
comment on: http://stackoverflow.com/a/52106362
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/102599327
type: AnswerComment
comment on: http://stackoverflow.com/a/52015620
type: Comment
has text: life saver! I had the same issue when I entered in a default value incorrectly. I had forgotten to make the value (`>>> "all" `) a string, and instead typed (`>>> all`)
score: 0

differential-equations
tags question: http://stackoverflow.com/q/52014550
tags question: http://stackoverflow.com/q/52088980
type: Tag
tag name: differential-equations

http://stackoverflow.com/q/52029136
upvote count: 2
accepted answer: http://stackoverflow.com/a/52029168
tagged with: django
tagged with: python
type: AnsweredQuestion
score: 2
type: Question
downvote count: 0
has answer: http://stackoverflow.com/a/52029168
has body: In the following code, for some reason, after using the foreign key for the project name, at the def __str__(self): part, on the 2nd like where it says return self.Project + ' (' + self.Situation_Type + ') ' + ' [' + self.Status + '] ' at the self.Project part, it shows me an error saying, class 'Project' does not define '_add_', so the '+' operator cannot be used on its instances This inspection detects names that should resolve but dont. Due to dynamic dispatch and ducttyping, this is possible in a limited but useful number of cases. Top-level and class level items are supported better than instance items. Ever since this error started coming up, My Projects page has been displaying nothing in the list, but it says that there is 1 item. What could be the issue? from django.db import models # Create your models here. from django.contrib.auth.models import User from django.db import models from django.core.mail import EmailMessage # Create your models here. class Project(models.Model): STATUS_CHOICE = ( ('Project Manager', 'Project Manager'), ('Technician', 'Technician'), ('Tester', 'Tester') ) STATUS_CHOICE_1 = ( ('Work Assigned', 'Work Assigned'), ('Work in Progress', 'Work in Progress'), ('Testing', 'Testing'), ('Completed', 'Completed') ) Project_Name = models.CharField(max_length=100) Project_Description = models.CharField(max_length=100) Admin_Name = models.ForeignKey(User, on_delete=models.CASCADE, related_name='User.Admin_Name_users+') Admin_Mail_ID = models.EmailField(max_length=50) Project_Manager_1 = models.ForeignKey(User, on_delete=models.CASCADE, related_name='User.Project_Manager_1_users+') Project_Manager_1_Mail_ID = models.EmailField(max_length=50) Project_Manager_2 = models.ForeignKey(User, on_delete=models.CASCADE, related_name='User.Project_Manager_2_users+', blank=True, null=True) Project_Manager_2_Mail_ID = models.EmailField(max_length=50, blank=True, null=True) Technician_1 = models.ForeignKey(User, on_delete=models.CASCADE, related_name='User…
answer count: 1
linked to: http://stackoverflow.com/q/52029805
favorite count: 0
has title: Django: class 'Project' does not define '_add_', so the '+' operator cannot be used on its instances

http://stackoverflow.com/comment/91173816
comment on: http://stackoverflow.com/a/52101898
type: AnswerComment
score: 0
type: Comment
has text: Thanks @IljaEverilä, I will try that out and update my answer

http://stackoverflow.com/comment/90867295
type: QuestionComment
comment on: http://stackoverflow.com/q/51958326
has text: Next thing: What platform are you on? Any firewall settings that could be relevant?
score: 0
type: Comment

http://stackoverflow.com/a/51978594
answers question: http://stackoverflow.com/q/51978243
has comment: http://stackoverflow.com/comment/90907774
has body: You probably want to do something like: output.writerow(row.split(',')) I've never used the csv module, but it looks like it also provides a reader which you could use to do the parsing. Updated with more context: with open("Winning No - Sheet1.csv", "r") as input: with open("output_file.csv", "w") as f: output = writer(f, delimiter=";") output.writerow(["Col {}".format(i+1) for i in xrange(COLUMNS)]) for row in input: output.writerow(row.split(','))
has comment: http://stackoverflow.com/comment/90906932
type: Answer
has comment: http://stackoverflow.com/comment/90907334
has comment: http://stackoverflow.com/comment/90906853
has comment: http://stackoverflow.com/comment/90907036
has comment: http://stackoverflow.com/comment/90907211
has comment: http://stackoverflow.com/comment/90908216
score: 0
has comment: http://stackoverflow.com/comment/90907597
has comment: http://stackoverflow.com/comment/90907266
has comment: http://stackoverflow.com/comment/90907229

http://stackoverflow.com/q/51976149
type: Question
upvote count: 4
has answer: http://stackoverflow.com/a/51976475
downvote count: 0
answer count: 1
score: 4
has body: I'm trying to change a value nested deeply in a YAML file using Python and pyyaml. I need to preserve the formatting, which is a combination of block and flow. I want to change a single value nested in a dictionary several layers deep in the structure. For example, I might change the x value to 2: a: b: c: {x:1, y:1} d: {r1: 2, r2: 4} e: f: 1 g: 1 I've been able to import the data, change the value, and dump the file with block formatting or with default formatting, but neither exactly matches the format that I need. Is there a way to either mix the formatting or to only change the target value without re-writing the entire file?
has comment: http://stackoverflow.com/comment/90902898
tagged with: yaml
accepted answer: http://stackoverflow.com/a/51976475
favorite count: 0
tagged with: python
type: AnsweredQuestion
has title: Mixing block and flow formatting in YAML with Python
tagged with: pyyaml

http://stackoverflow.com/q/51962092
tagged with: boto3
answer count: 2
has answer: http://stackoverflow.com/a/51962824
has answer: http://stackoverflow.com/a/52016115
tagged with: amazon-ec2
downvote count: 0
tagged with: amazon-web-services
favorite count: 0
tagged with: python-3.x
tagged with: python
has title: Error in retrieving public dns name of ec2 instance
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/52016115
score: 1
upvote count: 1
type: Question
accepted answer: http://stackoverflow.com/a/51962824
has body: I am trying to retrieve public dns name of an ec2 instance. Here is my python3 script. import sys import boto3 from botocore.exceptions import ClientError instance_id = "i-03e7f6391a0f523ee" action = 'ON' ec2 = boto3.client('ec2') if action == 'ON': # Do a dryrun first to verify permissions try: ec2.start_instances(InstanceIds=[instance_id], DryRun=True) except ClientError as e: if 'DryRunOperation' not in str(e): raise # Dry run succeeded, run start_instances without dryrun try: response = ec2.start_instances(InstanceIds=[instance_id], DryRun=False) print(response) except ClientError as e: print(e) else: # Do a dryrun first to verify permissions try: ec2.stop_instances(InstanceIds=[instance_id], DryRun=True) except ClientError as e: if 'DryRunOperation' not in str(e): raise # Dry run succeeded, call stop_instances without dryrun try: response = ec2.stop_instances(InstanceIds=[instance_id], DryRun=False) print(response) except ClientError as e: print(e) instance = ec2.Instance('i-1234567890123456') while instance.state['Name'] not in ('running', 'stopped'): sleep(5) print("the instance is initializing") #pubdns=instance.PublicDnsName #print ("public dns name"+pubdns) def get_name(inst): client = boto3.client('ec2') response = client.describe_instances(InstanceIds = [inst[0].instance_id]) foo = response['Reservations'][0]['Instances'][0]['NetworkInterfaces'][0]['Association']['PublicDnsName'] return foo foo = get_name(instance_id) print (foo) If I use ec2 = boto3.client('ec2') in the above code, I get the following error: AttributeError: 'EC2' object has no attribute 'Instance' and if I use ec2 = boto3.resource('ec2') then I get this error instead: AttributeError: 'ec2.ServiceResource' object has no attribute 'start_instances' what I want to do is to be able to connect to an ec2 instance and retrieve its publicdns name. I have changed the code now based on below suggestions import sys import boto3 instance_id = "i-03e7f6391a0f523ee" action = 'ON' ec2 = boto3.client('…

http://stackoverflow.com/a/52068579
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/91089444
downvote count: 0
has body: Your explanation of the problem is a little sloppy, but I have a feeling that you need this: interactions.set_index(['ItemID','UserID'])\ .unstack().fillna(0).astype(int).stack()\ .reset_index() This code creates a rectangular table of users and items, fills the voids with zeros, and converts the table back into a "tall" vector. Output: ItemID UserID Ratings 0 136771 176 0 1 136771 383 0 2 136771 67E 3 3 136771 70C 0 4 136771 A74 0 5 341785 176 0 6 341785 383 0 7 341785 67E 0 8 341785 70C 4 9 341785 A74 0 10 1172952 176 0 .... I assume that each item and each user (but not their combinations!) are referenced in the interaction table at least once. If not, some merge'ing with the other two tables is needed.
upvote count: 2
accepted answer of: http://stackoverflow.com/q/52068525
type: Answer
answers question: http://stackoverflow.com/q/52068525
score: 2
has comment: http://stackoverflow.com/comment/91089448

http://stackoverflow.com/q/52041893
type: Question
tagged with: python
has answer: http://stackoverflow.com/a/52042269
answer count: 1
has title: boto3 get_metric_statistics returning empty datapoints
tagged with: amazon-dynamodb
upvote count: 1
has body: I'm trying to make a simple python plugin that returns metrics on dynamodb but I can only get it to return an empty datapoint. #!/usr/bin/env python import sys import boto3 import time import optparse from pprint import pprint from datetime import datetime from datetime import timedelta def initialize_client(): client = boto3.client( 'cloudwatch', aws_access_key_id = 'xxxxx', aws_secret_access_key = 'xxxxx', region_name = 'us-east-2' ) return client def request_metric(client): response = client.get_metric_statistics( Namespace = 'AWS/DynamoDB', Period = 120, StartTime = datetime.utcnow() - timedelta(days=2), EndTime = datetime.utcnow(), MetricName = 'ConsumedWriteCapacityUnits', Statistics=['Average'], Dimensions = [ { 'Name': 'TableName', 'Value': 'test' } ], ) return response def main(): client = initialize_client() response = request_metric(client) pprint(response) return 0 main() Here is the output I get: {u'Datapoints': [], u'Label': 'ConsumedWriteCapacityUnits', 'ResponseMetadata': {'HTTPHeaders': {'content-length': '349', 'content-type': 'text/xml', 'date': 'Wed, 22 Aug 2018 20:57:44 GMT', 'x-amzn-requestid': 'xxxxx'}, 'HTTPStatusCode': 200, 'RequestId': 'xxxxx', 'RetryAttempts': 0}} I was able to get it working with RDS but I can't seem to get DynamoDB to return datapoints. What am I missing here?
accepted answer: http://stackoverflow.com/a/52042269
downvote count: 0
tagged with: boto3
tagged with: amazon-web-services
type: AnsweredQuestion
score: 1
favorite count: 0

http://stackoverflow.com/q/51998202
type: UnansweredQuestion
tagged with: python
tagged with: excel
has body: Im trying to view basic info in an excel file ,like sheet names,etc from xlrd import open_workbook book = open_workbook('SampleData.xlsx') book.sheet_names However it dosent seem to recognize sheetname, sheet_by_index etc .Below is the error AttributeError: module 'xlrd.book' has no attribute 'sheet_names'
linked to: http://stackoverflow.com/q/43070508
score: 0
type: Question
tagged with: xlrd
answer count: 1
has answer: http://stackoverflow.com/a/51998327
has title: python xlrd attribute error
has comment: http://stackoverflow.com/comment/90945635
has comment: http://stackoverflow.com/comment/90945586

http://stackoverflow.com/comment/91027309
has text: I have modified my question, please check again.
score: 0
comment on: http://stackoverflow.com/q/52038461
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51996545
favorite count: 0
tagged with: python
tagged with: dictionary
downvote count: 0
tagged with: csvtoarray
type: UnansweredQuestion
has title: Using a Python script to create an list of dictionaries by running through csv file data
score: 1
has body: I have data in the format from to Location1 Location2 Location1 Location3 Location1 Location4 Location1 Location5 Location2 Location1 Location2 Location3 Location3 Location1 Location3 Location2 Location3 Location4 In a csv file. The data maps bike trips from one station to another and is taken from the website of a bike rental company in Chicago. Right now I have basic code that takes each row and adds it to a list, but it does not create a dictionary in the second index as I am wishing for. My script looks like: import csv li = [] with open('Desktop/test_Q4_trips.csv', newline='') as csvfile: reader = csv.reader(csvfile, delimiter=',') for name, imports in reader: li.append({ "name": name, "imports": imports, }) del li[0] Here is the output, [{"from": "Location1", "to": "Location2"}, {"from": "Location1", "to": "Location3"}, {"from": "Location1", "to": "Location4"}, {"from": "Location1", "to": "Location5"}, ...] I want to convert this data into a this format, [{"from": "Location1", "to": ["Location2", "Location3", "Location4", "Location5"]}, {"from": "Location2", "to": ["Location1", "Location3"]}, {"from": "Location3", "to": ["Location1", "Location2", "Location4"]}, ... ]. In words, I would like to create a list of dictionaries where each dictionary has a single value in the first index and a list of (variably many) values in the second index. In particular, the output should list all of the stations that are on the receiving end of a bike rental trip in a list in the second index. To do this, I imagine I will have to create a script with a for loop that loops through the "from" values on the left and appends every "to" location that corresponds to each "from" one to a list. I would like my data to be in the particular form I am mentioning in order to work with data visualization code that I have. I am sure that creating the format that I would like needs a leap in thought, but I am not sure exactly what to do to satisfy this. I am also not sure if the output type …
tagged with: http://stackoverflow.com/tag/json
has answer: http://stackoverflow.com/a/51996618
type: Question
has answer: http://stackoverflow.com/a/51996631
answer count: 2
upvote count: 1
has comment: http://stackoverflow.com/comment/90942509

http://stackoverflow.com/q/52081773
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/52211579
tagged with: django
tagged with: python
has title: django inspectdb utf8mb4 error
accepted answer: http://stackoverflow.com/a/52211579
tagged with: mysql
upvote count: 1
answer count: 1
tagged with: utf8mb4
has body: Python manage.py inspectdb is giving following error even after all tables are having CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci from django.db import models Unable to inspect table 'execution' The error was: (3719, "3719: 'utf8' is currently an alias for the character set UTF8MB3, but will be an alias for UTF8MB4 in a future release. Please consider using UTF8MB4 in order to be unambiguous.", None)
type: AnsweredQuestion
downvote count: 0
score: 1

http://stackoverflow.com/comment/90946187
comment on: http://stackoverflow.com/q/51997053
score: 0
type: Comment
has text: This is the desired output [[2,-2,7], [-1,1,4], [10,7,1]]
type: QuestionComment

http://stackoverflow.com/a/51983166
has comment: http://stackoverflow.com/comment/90916059
has comment: http://stackoverflow.com/comment/90918605
upvote count: 4
answers question: http://stackoverflow.com/q/51982930
has comment: http://stackoverflow.com/comment/90916145
type: AcceptedAnswer
downvote count: 0
has body: Try this: from bs4 import BeautifulSoup as bs html=''' Pageviews Pageviews: 101,172 Daily average: 4,818 ''' soup = bs(html, 'html.parser') div = soup.find("div", {"class": "linear-legend--counts"}) span = div.find('span') text = span.get_text() print(text) output: 101,172 simply in one line: soup = bs(html, 'html.parser') result = soup.find("div", {"class": "linear-legend--counts"}).find('span').get_text() EDIT: As OP has posted another question which can be a possible duplicate for this one, He had found an answer. For someone who is looking for an answer for a similar kind of a question I will post the accepted answer for this question. It can be found here. The javascript code won't get executed if you retrieve page with the requests.get. So the selenium shall be used instead. It will mimic user like behaviour with the opening of the page in browser, so the js code will be executed. To start with selenium, you need to install with pip install selenium. Then to retrieve your item use code below: from selenium import webdriver browser = webdriver.Firefox() # List of the page url and selector of element to retrieve. wiki_pages = [("https://tools.wmflabs.org/pageviews/?project=en.wikipedia.org&platform=all-access&agent=user&range=latest-20&pages=Star_Wars:_The_Last_Jedi", ".summary-column--container .legend-block--pageviews .linear-legend--counts:first-child span.pull-right"),] for wiki_page in wiki_pages: url = wiki_page[0] selector = wiki_page[1] browser.get(wiki_page) page_views_count = browser.find_element_by_css_selector(selector) print page_views_count.text browser.quit() NOTE: If you need to run headless browser, consider using PyVirtualDisplay (a wrapper for Xvfb) to run headless WebDriver tests, see 'How do I run Selenium in Xvfb?' for more information.
accepted answer of: http://stackoverflow.com/q/51982930
type: Answer
score: 4

http://stackoverflow.com/q/52063008
answer count: 2
tagged with: for-loop
has answer: http://stackoverflow.com/a/52063065
tagged with: arrays
downvote count: 0
possible better answer: http://stackoverflow.com/a/52063077
has body: I have two numpy arrays data_0.shape = (500, 52) and data_3.shape = (480, 52) I am trying to create a new array by concatenating the above two arrays in a special way. So far I have been doing this manually like this. data_train = np.concatenate((data_0[:50],data_3[:50],data_0[50:100],data_3[50:100],data_0[100:150],data_3[100:150], data_0[150:200],data_3[150:200],data_0[200:250],data_3[200:250],data_0[250:300],data_3[250:300], data_0[300:350],data_3[300:350],data_0[350:400],data_3[350:400],data_0[400:450],data_3[400:450], data_0[450:],data_3[450:])) As you can see, I am basically grabbing 50 values each from data_0 and data_3 repeatedly and concatenating them together to get the new array data_train, the shape of which is as follows. data_train.shape = (980, 52) This process is extremely time consuming and I am trying to automate this task. This is how my code looks like but I am confused as to how to loop through these 2 arrays simultaneously and also how to concatenate them by grabbing 50 values each from both arrays in an alternating way? j = 0 k = 10 data_train = [] data_train.append(np.concatenate((data_0[j:k],data_3[j:k]))) j = j+10 k = k+10 data_train = np.array(data_train) How should I initiate the for loop here?
has answer: http://stackoverflow.com/a/52063077
tagged with: python
favorite count: 0
accepted answer: http://stackoverflow.com/a/52063065
upvote count: 1
type: Question
type: AnsweredQuestion
score: 1
has title: Looping through 2 numpy arrays and concatenating them
tagged with: numpy

http://stackoverflow.com/q/51987744
has comment: http://stackoverflow.com/comment/90925545
downvote count: 0
tagged with: optional-arguments
favorite count: 0
has title: Passing constants and variables into Scipy.minimize.optimize constraints and boundaries
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/90925882
linked to: http://stackoverflow.com/q/25206482
answer count: 0
score: 1
upvote count: 1
tagged with: scipy
type: Question
tagged with: minimize
has body: I found how one can pass *args into the main function of scipy.minimize.optimize, see this question. But how do I pass constants and variables into constraints and boundaries? P is a variable vector, P0 is the initial solution vector, f(P) is the function to minimize, the rest are constant data. Will it work like this? def constraint_1(P, args): M_goal, other_args = args M = calc_M_from_P(P, args) # calculate M from P return M-M_goal # boundary is simply (P0[i]-500, P0[i]+500) def get_boundaries(P0): list_bnds = [] for i in range(len(P0)): list_bnds.append((P0[i]-500.0, P0[i]+500.0)) return tuple(list_bnds) func = objective(P0, args) bnds = get_boundaries(P0) con1 = {'type': 'ineq', 'fun': constraint_1} sol = minimize(func, P0, args = args, method='SLSQP', bound=bnds, constraints = con1)

http://stackoverflow.com/comment/90895535
score: 0
type: Comment
type: QuestionComment
has text: Your code has a `print(args)` line. It should run before hitting this key error. Pay attention to what it shows. You might even want to test a stripped down version of this code, one that stops after this print.
comment on: http://stackoverflow.com/q/51971647

http://stackoverflow.com/q/52001578
answer count: 0
downvote count: 0
tagged with: webrtc
has title: How to use stun library python to get TURN relay allocation from remote server
type: UnansweredQuestion
score: 1
favorite count: 0
type: Question
has body: I'm building an application on Python to test WebRTC connection to a server. What I've managed to do it get to the point where I get the TURN server information from the WebRTC server, see below: {'turnPort': 3478, 'turnTcpPort': 443, 'turnAddress': '10.13.xx.xx', 'turnUsername': 'expturncreds', 'turnPassword': 'abcd123'} {'turnPort': 3478, 'turnTcpPort': 443, 'turnAddress': '10.12.xx.xy', 'turnUsername': 'expturncreds', 'turnPassword': 'abcd123'} Now i want to tell the program to send Allocate requests to the server using the information above and the stun library. Will this be possible? If so any pointers?
tagged with: python
upvote count: 1
tagged with: stun
has comment: http://stackoverflow.com/comment/90966040
tagged with: ice
has comment: http://stackoverflow.com/comment/91062398
has comment: http://stackoverflow.com/comment/91062365

http://stackoverflow.com/q/51959635
has comment: http://stackoverflow.com/comment/90869684
has comment: http://stackoverflow.com/comment/90869538
has title: Designing code to handle specific error messages processed by a generic function
type: Question
tagged with: python
tagged with: design-patterns
tagged with: oop
score: 0
tagged with: error-handling
answer count: 0
type: UnansweredQuestion
has body: I am a beginner in Python, but I have referred several questions related to individually handling error messages in Python and I've also read best practices of raising exceptions. However, this is more of a design question to handle error messages when a single function is used to process/validate errors. There are individual functions that make different API calls. To handle the response, all these functions use the following generic function: def print_if_error_and_exit(response, debug, message_override_map=None, exit_on_failure=True): if hasattr(response, 'status') and (response.status &lt; 200 or response.status &gt;= 300): overriden_message = message_override_map.get(response.status) if message_override_map else None if overriden_message: error_message = overriden_message elif hasattr(response, 'message'): error_message = response.message else: error_message = 'No error message found' if exit_on_failure: print_error_message('Error (HTTP {0}): {1}'.format(response.status, error_message)) if debug: print_error_message(repr(response)) sys.exit(1) else: raise ResponseException(error_message) Now, we want to retain this function but also have a capability to provide custom, API-specific human-friendly error messages. One way of doing that would be to call this function with a dict that can take HTTP status codes along with corresponding customized messages. However, this might not be the best approach, and I was wondering if there was a better way of achieving this objective.

http://stackoverflow.com/comment/90912126
type: Comment
comment on: http://stackoverflow.com/a/51980971
has text: Thanks for reply. Actually, I am reading csv file and trying to update the last column value for all the rows.
score: 0
type: AnswerComment

http://stackoverflow.com/comment/91242080
comment on: http://stackoverflow.com/q/52102240
score: 0
type: Comment
type: QuestionComment
has text: interesting link, I'll take a look. thanks a lot!

http://stackoverflow.com/a/61514769
has body: Type conda list to verify that the package you want to run is installed in the current environment. If you are not in the correct environment, type conda activate env_name (where env_name is the name of the environment you want to activate). If the package you want to run is listed when you type conda list, then you can run it directly. Try by just typing the package name. If not, try python -m package_name.
type: Answer
answers question: http://stackoverflow.com/q/51991004
score: 0

http://stackoverflow.com/q/52078594
has title: pandas apply changing dtype
possible better answer: http://stackoverflow.com/a/52080487
answer count: 2
tagged with: pandas
has answer: http://stackoverflow.com/a/52080487
has body: I'm trying to convert a pandas dataframe into a Series of tuples: Example input: df = pd.DataFrame([[1,2,3.0],[3,4,5.0]]) Desired Output: 0 (1, 2, 3.0) 1 (3, 4, 5.0) dtype: object However pandas seems to coerce my integer columns to floats. I tried import pandas as pd df = pd.DataFrame([[1,2,3.0],[3,4,5]]) print(df) print(df.dtypes) print(df.apply(tuple,axis=1,reduce=False).apply(str)) Actual output: 0 1 2 0 1 2 3.0 1 3 4 5.0 0 int64 1 int64 2 float64 dtype: object 0 (1.0, 2.0, 3.0) 1 (3.0, 4.0, 5.0) dtype: object This question suggests using reduce=False but this doesn't change anything for me. Could someone explain why pandas is coercing the datatype somewhere along the way?
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/52078751
tagged with: python-3.x
linked to: http://stackoverflow.com/q/34917404
score: 6
tagged with: python
upvote count: 6
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91107855
accepted answer: http://stackoverflow.com/a/52078751
type: Question

http://stackoverflow.com/a/52050587
type: Answer
has body: Why don't you try using a loop to go through all the links for i in parsedjson['data']['children']: finalUrl =i['data']['url'] print(finalUrl) Output https://i.sstatic.net/LHAf3.jpg https://i.redd.it/szj6wnw2foi11.jpg https://i.redd.it/5k8vgy173mi11.jpg https://i.sstatic.net/UaMch.jpg https://i.redd.it/9nab5nvi4mi11.jpg https://i.redd.it/9zgnp3z1gmi11.jpg https://i.redd.it/ulhtdcomsoi11.jpg https://i.redd.it/yjthueewmmi11.jpg https://i.redd.it/gtdm76o3yni11.jpg https://i.redd.it/1j7ez5alloi11.jpg https://i.imgur.com/8xNGW6T.jpg https://i.redd.it/13fk1b3rhki11.jpg https://i.sstatic.net/jCRXi.jpg https://i.redd.it/qqfb57u53ni11.jpg https://i.redd.it/17fs1whd3pi11.jpg https://i.redd.it/kjwv5p15qni11.png https://i.redd.it/oayns08fjqi11.jpg https://i.sstatic.net/10mMp.jpg https://i.redd.it/px53p4e2ski11.jpg https://i.redd.it/ncjytopnami11.jpg https://i.sstatic.net/K6njE.jpg https://i.redd.it/ecbs9yao5ni11.jpg https://i.redd.it/10210k2rpli11.jpg https://i.redd.it/xxs7h8ng1qi11.jpg https://i.redd.it/5toz9ercjni11.jpg Hope this is what you are looking for
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/52050375
upvote count: 1

http://stackoverflow.com/q/52059974
favorite count: 0
tagged with: python-3.x
tagged with: tkinter
tagged with: python
accepted answer: http://stackoverflow.com/a/52064361
type: AnsweredQuestion
score: 3
has comment: http://stackoverflow.com/comment/91078833
possible better answer: http://stackoverflow.com/a/60941312
downvote count: 1
has body: This Tkinter code doesn't have a widget, just a label so it displays just a text on the screen so I want to destroy or delete the label after a certain time !. How can I do this when method label.after(1000 , label.destroy) doesn't work? import tkinter, win32api, win32con, pywintypes label = tkinter.Label(text='Text on the screen', font=('Times New Roman','80'), fg='black', bg='white') label.master.overrideredirect(True) label.master.geometry("+250+250") label.master.lift() label.master.wm_attributes("-topmost", True) label.master.wm_attributes("-disabled", True) label.master.wm_attributes("-transparentcolor", "white") hWindow = pywintypes.HANDLE(int(label.master.frame(), 16)) exStyle = win32con.WS_EX_COMPOSITED | win32con.WS_EX_LAYERED | win32con.WS_EX_NOACTIVATE | win32con.WS_EX_TOPMOST | win32con.WS_EX_TRANSPARENT win32api.SetWindowLong(hWindow, win32con.GWL_EXSTYLE, exStyle) label.pack() label.after(1000 , lambda: label.destroy()) #doesn't work anyway.. label.mainloop()
type: Question
upvote count: 4
has answer: http://stackoverflow.com/a/60941312
has title: How to delete or destroy Label in tkinter?
has comment: http://stackoverflow.com/comment/91070310
has comment: http://stackoverflow.com/comment/91070383
answer count: 2
has answer: http://stackoverflow.com/a/52064361
has comment: http://stackoverflow.com/comment/91070325

http://stackoverflow.com/tag/csv
tags question: http://stackoverflow.com/q/51994368
tags question: http://stackoverflow.com/q/52014473
tags question: http://stackoverflow.com/q/52111009
tags question: http://stackoverflow.com/q/52063200
type: Tag
tags question: http://stackoverflow.com/q/52051521
tags question: http://stackoverflow.com/q/52021100
tags question: http://stackoverflow.com/q/51973570
tags question: http://stackoverflow.com/q/52012899
tags question: http://stackoverflow.com/q/52064062
tags question: http://stackoverflow.com/q/52043742
tags question: http://stackoverflow.com/q/52083431
tags question: http://stackoverflow.com/q/52104025
tags question: http://stackoverflow.com/q/52086665
tags question: http://stackoverflow.com/q/52103428
tag name: csv
tags question: http://stackoverflow.com/q/52040800
tags question: http://stackoverflow.com/q/52074325
tags question: http://stackoverflow.com/q/52102402
tags question: http://stackoverflow.com/q/52029148
tags question: http://stackoverflow.com/q/52109412
tags question: http://stackoverflow.com/q/52085033
tags question: http://stackoverflow.com/q/52090690
tags question: http://stackoverflow.com/q/52059217
tags question: http://stackoverflow.com/q/52087219
tags question: http://stackoverflow.com/q/52056393
tags question: http://stackoverflow.com/q/51999427
tags question: http://stackoverflow.com/q/52027382
tags question: http://stackoverflow.com/q/51988354
tags question: http://stackoverflow.com/q/51986297
tags question: http://stackoverflow.com/q/52061708
tags question: http://stackoverflow.com/q/52005830
tags question: http://stackoverflow.com/q/52079180
tags question: http://stackoverflow.com/q/52018940
tags question: http://stackoverflow.com/q/52077487
tags question: http://stackoverflow.com/q/51959989
tags question: http://stackoverflow.com/q/52060461
tags question: http://stackoverflow.com/q/51976847
tags question: http://stackoverflow.com/q/52092332
tags question: http://stackoverflow.com/q/52041891
tags question: http://stackoverflow.com/q/51958993
tags question: http://stackoverflow.com/q/52018333
tags question: http://stackoverflow.com/q/51959862
tags question: http://stackoverflow.com/q/52000223
tags question: http://stackoverflow.com/q/52103724
tags question: http://stackoverflow.com/q/52010069
tags question: http://stackoverflow.com/q/51986666
tags question: http://stackoverflow.com/q/51968465
tags question: http://stackoverflow.com/q/51972676
tags question: http://stackoverflow.com/q/52079999
tags question: http://stackoverflow.com/q/51995179
tags question: http://stackoverflow.com/q/52087613
tags question: http://stackoverflow.com/q/52081155
tags question: http://stackoverflow.com/q/51981323
tags question: http://stackoverflow.com/q/52070106
tags question: http://stackoverflow.com/q/52084976
tags question: http://stackoverflow.com/q/52061357
tags question: http://stackoverflow.com/q/52054973
tags question: http://stackoverflow.com/q/52009301
tags question: http://stackoverflow.com/q/52035560
tags question: http://stackoverflow.com/q/51967102
tags question: http://stackoverflow.com/q/52019176
tags question: http://stackoverflow.com/q/52002271
tags question: http://stackoverflow.com/q/52083185
tags question: http://stackoverflow.com/q/52035739
tags question: http://stackoverflow.com/q/51980730
tags question: http://stackoverflow.com/q/51959431
tags question: http://stackoverflow.com/q/52002236
tags question: http://stackoverflow.com/q/52087426
tags question: http://stackoverflow.com/q/51978243
tags question: http://stackoverflow.com/q/51994654
tags question: http://stackoverflow.com/q/52108369
tags question: http://stackoverflow.com/q/52027851
tags question: http://stackoverflow.com/q/52047967
tags question: http://stackoverflow.com/q/52098763
tags question: http://stackoverflow.com/q/51991474
tags question: http://stackoverflow.com/q/52027711
tags question: http://stackoverflow.com/q/52017438
tags question: http://stackoverflow.com/q/52012897
tags question: http://stackoverflow.com/q/52047920

http://stackoverflow.com/a/52044768
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52043231
type: Answer
answers question: http://stackoverflow.com/q/52043231
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/91042988
has comment: http://stackoverflow.com/comment/91042173
has body: refresh_from_db is just a method inside models.Model class so you can override it inside the Booking model. See here for the source: https://docs.djangoproject.com/en/2.1/_modules/django/db/models/base/#Model.refresh_from_db You just need to change db_instance_qs to use BookingDeletedManager()

http://stackoverflow.com/q/52070949
tagged with: pandas
downvote count: 0
possible better answer: http://stackoverflow.com/a/52071058
favorite count: 0
tagged with: python
tagged with: merge
type: AnsweredQuestion
score: 3
has body: I got two dataframes that I need to merge as per follows: Df1 Name Type Speed a x 1 a y 0 a z 1 Df2 Type Fast Slow x 2 3 y 3 5 z 4 6 Df3 - DESIRED OUTCOME Name Type Speed Time a x 1 2 a y 0 5 a z 1 4 So basically I need to create a new 'Time' column that displays times from either 'Fast' or 'Slow' column based on 'Speed' column and the object 'Type'. I have literally no idea how to do this so any help would be much appreciated! Thanks in advance. Apologies for the confusing explanation..
upvote count: 3
has answer: http://stackoverflow.com/a/52071058
type: Question
answer count: 2
has title: Merging two dataframes with an added condition
tagged with: dataframe
has answer: http://stackoverflow.com/a/52071111
accepted answer: http://stackoverflow.com/a/52071111

http://stackoverflow.com/q/51995350
type: Question
score: 3
tagged with: anaconda
has comment: http://stackoverflow.com/comment/90940279
tagged with: conda
answer count: 1
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/51995836
tagged with: python
has title: Windows Sublime Text, how to use Anaconda Python instead of default
upvote count: 3
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90940245
has body: How do I go about setting sublime text to build with my anaconda python and not the default one? I have pyaudio installed in anaconda but when I build my page in sublime it says no module of pyaudio found. I assume it is because it is building with the default python. I have installed conda in the sublime package manager too and it says I am pointed to my anaconda python, still not working though.

http://stackoverflow.com/comment/90992217
type: QuestionComment
has text: Very difficult to tell what your issue is, are you able to strip your project back to the point and which it was working...?
comment on: http://stackoverflow.com/q/52020581
score: 0
type: Comment

http://stackoverflow.com/comment/91785073
comment on: http://stackoverflow.com/q/52026823
has text: I found the solution....I am using sigmoid and keras is using hard_sigmoid...
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91086551
comment on: http://stackoverflow.com/a/52068056
score: 0
type: Comment
has text: Thank you Wen. This approach looks very promising. I have updated my original question slightly to request a resolution for my actual formula. How would a multi term complex formula be applied to this solution?
type: AnswerComment

http://stackoverflow.com/q/51976787
tagged with: google-cloud-storage
has comment: http://stackoverflow.com/comment/113131835
type: Question
answer count: 1
has comment: http://stackoverflow.com/comment/91039487
has comment: http://stackoverflow.com/comment/91039651
has comment: http://stackoverflow.com/comment/113317109
has body: I have a Django project built on Google Cloud Platform. We are using Django's auth system, and most (nearly all) users do not have credentials set up in the GCP project, so all file auth needs to be based on Django and not GCP. Our backend configuration for file storage is very basic, and files are successfully uploaded to GCS as expected: DEFAULT_FILE_STORAGE = 'storages.backends.gcloud.GoogleCloudStorage' GS_BUCKET_NAME = 'my-bucket' The generated URLs for files are of the form (again, as expected): https://storage.googleapis.com/my-bucket/my-document.txt The problem is this bucket cannot be made publicly readable as files have access controls based on rules set up in Django's permission system that are different per user. How can I have Django serve the file instead of the file being served by GCS? One thought that comes to mind is to have views that load files from GCS and pass them through to the requesting client, but I suspect this will not handle large files well as I need to either load the entire file into local memory (bad) or load the file in chunks and write them out to the response stream in those chunks, but don't know if this can be done in Django.
tagged with: google-cloud-platform
upvote count: 7
accepted answer: http://stackoverflow.com/a/52047636
favorite count: 0
linked to: http://stackoverflow.com/q/63969069
downvote count: 0
has answer: http://stackoverflow.com/a/52047636
tagged with: django
tagged with: python
has title: Django Serve Files From External Storage Directly
type: AnsweredQuestion
score: 7

http://stackoverflow.com/q/52091783
type: Question
has title: How to use pandas datafames in weka wrapper instead of arff files?
tagged with: weka
has body: I am new to this weka wrapper and trying to apply the attribute selection algorithm on my panda's data frame bowDataFrame. Please help. ` jvm.start(packages=True) search = ASSearch(classname="weka.attributeSelection.BestFirst", options=["-D", "1", "-N", "5"]) evaluator = ASEvaluation(classname="weka.attributeSelection.CfsSubsetEval", options=["-P", "1", "-E", "1"]) print("We are here") attsel = AttributeSelection() attsel.search(search) attsel.evaluator(evaluator) attsel.select_attributes(bowDataFrame)`
downvote count: 0
score: 6
favorite count: 0
tagged with: python
upvote count: 6
answer count: 0
type: UnansweredQuestion

http://stackoverflow.com/comment/90959414
has text: If there is something Just like a `throttle` module which cause API limit call per second, you call use Ipproxy module to send your request by using a proxy to skip this problem.From my understanding, you want to implement a crawler.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52004801
score: 0

http://stackoverflow.com/a/52044193
has comment: http://stackoverflow.com/comment/91041956
has comment: http://stackoverflow.com/comment/91048412
has comment: http://stackoverflow.com/comment/91050172
has comment: http://stackoverflow.com/comment/91048493
has comment: http://stackoverflow.com/comment/91049608
has comment: http://stackoverflow.com/comment/91048650
has comment: http://stackoverflow.com/comment/91048643
type: AcceptedAnswer
has body: You’re starting from a set of faulty premises: It is a well-known problem in python that recursion involves a lot of overhead. No it isn’t. The overhead for recursive function calls is essentially the same as for any other function calls. There’s probably a small difference in that you keep allocating new stack frames and loading them into the cache, whereas the same thing implemented with a loop with a non-recursive call inside would be able to reuse the same stack frame. But it’s going to be pretty minor. So much so, that even relatively shallow recursive calls cause programs to crash. No they don’t. Recursion beyond a depth of 1000 cleanly fails with an exception. This is in part to prevent such crashes, but also to make it easier to detect accidental infinite recursion. One possible workaround would be to implement fancy recursive algorithms in C That’s not going to help anything. Most C implementations handle recursion essentially the same way most Python implementations do (in fact. In CPython, recursion can just be a matter of C-recursing the main eval loop). There’s still no tail call elimination, no special handling for keeping only live variables from a frame alive, etc. While C stack frames are a little smaller than Python ones, this is just a small multiplicative factor. And, meanwhile, unlike Python programs,, C programs actually will crash if you recurse too deeply. Of course C code does tend to be an order of magnitude or two faster than Python code when what you’re doing is low-level computation, and that will help you here the same way it well anywhere else (although maybe not as much as usual, because function calls in C are, while not as slow as Python, still far from free). Plus, C does force you to be more explicit about some things—e.g., there are no closures, so if you want the effect of nonlocal you’ll need to pass down pointers to locals—which could lead to you optimizing things you wouldn’t think to in Python. But in general, there is if an…
answers question: http://stackoverflow.com/q/52043718
has comment: http://stackoverflow.com/comment/91049004
type: Answer
accepted answer of: http://stackoverflow.com/q/52043718
score: 2
has comment: http://stackoverflow.com/comment/91051779
upvote count: 3
downvote count: 1
has comment: http://stackoverflow.com/comment/91048584
has comment: http://stackoverflow.com/comment/91040714

http://stackoverflow.com/comment/90959054
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52004279
has text: 1. The `\0` is still there but it's not printed (check `NULL` terminated strings). 2. They were probably developed in parallel (I remember that at 1st, *ctypes* was not in *Python* standard library). The functionality does partially overlap. Removing one such module would break backwards compatibility as there is probably lots of code out there that depends on each of the 3 modules. Note: ***ctypes* uses *struct***.

http://stackoverflow.com/q/52045839
has title: Django, CreateView: pass form argument to reverse_lazy
type: Question
upvote count: 2
answer count: 3
accepted answer: http://stackoverflow.com/a/52046041
possible better answer: http://stackoverflow.com/a/52046254
has answer: http://stackoverflow.com/a/52046254
has answer: http://stackoverflow.com/a/66099463
favorite count: 0
has answer: http://stackoverflow.com/a/52046041
tagged with: django
tagged with: python
has body: To redirect the user after filling out the CreateView form I would like to access an argument from the form and pass it to the reverse_lazy function. How can I access the parameters of the form within CreateView? I actually use the argument I'm looking for to pass it to the form itself (self.request.META.get('HTTP_REFERER').split('/')[-1]), but seem not to be able to use this logic in reverse_lazy. get_form_kwargs also seems not to achieve the result: views.py class PieceInstanceCreate(LoginRequiredMixin, CreateView): model = PieceInstance fields = ['version', 'piece_image', 'status'] def form_valid(self, form): obj = form.save(commit=False) obj.piece = Piece.objects.get(id=self.request.META.get('HTTP_REFERER').split('/')[-1]) return super(PieceInstanceCreate, self).form_valid(form) def get_form_kwargs(self): kwargs = super(PieceInstanceCreate, self).get_form_kwargs() return kwargs['piece'] success_url = reverse_lazy('piece-detail', kwargs={'pk': get_form_kwargs(self)}) urls.py path('piece/&lt;int:pk&gt;', views.PieceDetailView.as_view(), name='piece-detail')
score: 2
type: AnsweredQuestion
downvote count: 0

http://stackoverflow.com/a/52123745
answers question: http://stackoverflow.com/q/52084911
score: 1
upvote count: 1
downvote count: 0
type: Answer
has body: tf.custom_gradient is the best tool to use here. It lets you define the gradient function at the call site, has a nicer interface than the override map, and works well with eager execution.

http://stackoverflow.com/a/51994118
answers question: http://stackoverflow.com/q/51993862
score: 1
has body: Maybe simple math? Just calculate difference between start and stop and devoid it on step size. And, finely subtract one from the result ((p[1]-p[0])/p[2]) - 1
upvote count: 1
type: Answer
downvote count: 0

http://stackoverflow.com/comment/129483098
type: AnswerComment
type: Comment
score: 2
has text: Incorrect, experiment for yourself with below code (by adding/removing the inf part): ``` x = np.arange(10.); y = (-1) ** x; y[5] = np.nan; y[5] = np.inf; df = pd.DataFrame({'x': x, 'y': y}); sns.lineplot(data=df, x='x', y='y'); ```
comment on: http://stackoverflow.com/a/64172693

http://stackoverflow.com/a/51991193
answers question: http://stackoverflow.com/q/51991034
score: 2
upvote count: 2
has body: Assuming you have the default template CONTEXT_PROCESSORS in your settings module, one of which includes django.contrib.auth.context_processors.auth which sets the user variable in all of your templates. Also, you can look at the source code.
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51991034
type: Answer

http://stackoverflow.com/q/52035453
has answer: http://stackoverflow.com/a/52035677
has comment: http://stackoverflow.com/comment/91021079
has comment: http://stackoverflow.com/comment/91021472
type: Question
has title: Write and Read List, Python Pickle
downvote count: 0
has comment: http://stackoverflow.com/comment/91021178
accepted answer: http://stackoverflow.com/a/52035677
answer count: 1
tagged with: python
favorite count: 0
tagged with: tkinter
tagged with: pickle
upvote count: 1
type: AnsweredQuestion
has body: I made a program with a List and this List is included in the Combobox. I want to write the List into a file in order to read the List again later, even after a restart of the program. I tried this: import tkinter as tk from tkinter import ttk import pickle # window win = tk.Tk() win.title("menu") List = [] newList = [] with open('data.txt', 'wb') as f: pickle.dump(List, f) with open('data.txt', 'rb') as f: newList = pickle.load(f) # button click event def clickMe(): List.append(name.get()) numberChosen.configure(values=List) # text box entry ttk.Label(win, text="Eingabe:").grid(column=0, row=0) name = tk.StringVar() nameEntered = ttk.Entry(win, width=12, textvariable=name) nameEntered.grid(column=0, row=1) # button action = ttk.Button(win, text="Enter", command=clickMe) action.grid(column=2, row=1) # drop down menu ttk.Label(win, text="Auswahl:").grid(column=1, row=0) number = tk.StringVar() numberChosen = ttk.Combobox(win, width=12) numberChosen['values'] = [List] numberChosen.grid(column=1, row=1) win.mainloop()
tagged with: list
score: 1

http://stackoverflow.com/a/51996257
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/131060352
type: Answer
upvote count: 15
has comment: http://stackoverflow.com/comment/90941945
downvote count: 0
has comment: http://stackoverflow.com/comment/90941982
accepted answer of: http://stackoverflow.com/q/51996139
score: 15
has body: Assuming you were able read the HTML contents into a variable and named the variable html, you have to parse the HTML using beautifulsoup: from bs4 import BeautifulSoup soup = BeautifulSoup(html, 'html.parser') Then, to search for &lt;meta content="text I want to grab" name="description"/&gt;, you have to find a tag with name 'meta' and attribute name='description': def is_meta_description(tag): return tag.name == 'meta' and tag['name'] == 'description' meta_tag = soup.find(is_meta_description) You are trying to fetch the content attribute of the tag, so: content = meta_tag['content'] Since it is a simple search, there is also a simpler way to find the tag: meta_tag = soup.find('meta', attrs={'name': 'description'})
answers question: http://stackoverflow.com/q/51996139
has comment: http://stackoverflow.com/comment/90941969

http://stackoverflow.com/comment/91149158
has text: Is performance different if using `.iloc` to do the slicing? (I assume not)
comment on: http://stackoverflow.com/a/52099224
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/52103145
has body: I am confused by what airflow does if a dagrun fails. The behaviour I want to achieve is: Regular triggers of the DAG (hourly) Retries for the task If a task fails n retries, send an email about the failure When the next hourly trigger comes round, trigger a new dagrun as if nothing had failed. These are my dag arguments and task arguments: task defaults: 'depends_on_past': True, 'start_date': airflow.utils.dates.days_ago(2), 'email': ['email@address.co.uk'], 'email_on_failure': True, 'email_on_retry': False, 'retries': 1, 'retry_delay': timedelta(minutes=5), 'wait_for_downstream': False, dag arguments: schedule_interval=timedelta(minutes=60), catchup=False, max_active_runs=1 I think I am misunderstanding some of these arguments because it appears to me that if a task fails n times (i.e. the dagrun fails), then the next dagrun gets scheduled but just sits in the running state forever and no further dagruns ever succeed (or even get scheduled). for example, here are the dagruns (I didn't know where to find the text based scheduler logs like in this question) where the dags are scheduled to run every 5 minutes instead of every hour: The execution runs every 5 minutes until the failure, after that the last execution is just in the running state and has been so for the past 30 minutes. What have I done wrong? I should add that restarting the scheduler doesn't help and neither does manually setting that running task to failed...
downvote count: 0
has title: airflow stops scheduling dagruns after task failure
type: Question
answer count: 2
possible better answer: http://stackoverflow.com/a/57393328
tagged with: airflow
has answer: http://stackoverflow.com/a/57393328
tagged with: scheduler
upvote count: 2
tagged with: scheduled-tasks
linked to: http://stackoverflow.com/q/48110703
favorite count: 0
tagged with: python
has answer: http://stackoverflow.com/a/52103931
accepted answer: http://stackoverflow.com/a/52103931
type: AnsweredQuestion
score: 2

http://stackoverflow.com/comment/91025433
comment on: http://stackoverflow.com/a/52037583
has text: I don't understand what you mean by 'fuse'. Could you specify what the arrays look like before using `np.unique` on them? Otherwise it is unclear what operation will give the desired result.
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/90953676
has text: Sorry guys. I was so frustated. My apologies. I just want to get the word before the quote, but my word is terrible. @SmashGuy
comment on: http://stackoverflow.com/a/52002011
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/90869870
type: Comment
score: 2
has text: `df=df.iloc[:,:4]`, will keep colummns, 0,1,2,3
comment on: http://stackoverflow.com/q/51959658
type: QuestionComment

list
tags question: http://stackoverflow.com/q/52096432
tags question: http://stackoverflow.com/q/51974880
tags question: http://stackoverflow.com/q/51995808
type: Tag
tags question: http://stackoverflow.com/q/52029708
tags question: http://stackoverflow.com/q/52020413
tags question: http://stackoverflow.com/q/52094719
tags question: http://stackoverflow.com/q/52048454
tags question: http://stackoverflow.com/q/51972213
tags question: http://stackoverflow.com/q/52023685
tags question: http://stackoverflow.com/q/51974207
tags question: http://stackoverflow.com/q/51974341
tags question: http://stackoverflow.com/q/52012126
tags question: http://stackoverflow.com/q/51973414
tags question: http://stackoverflow.com/q/51958145
tags question: http://stackoverflow.com/q/51988800
tags question: http://stackoverflow.com/q/51959329
tags question: http://stackoverflow.com/q/52083886
tags question: http://stackoverflow.com/q/52067524
tags question: http://stackoverflow.com/q/52033242
tags question: http://stackoverflow.com/q/52020608
tags question: http://stackoverflow.com/q/51969998
tags question: http://stackoverflow.com/q/52005295
tags question: http://stackoverflow.com/q/51984344
tags question: http://stackoverflow.com/q/51969283
tags question: http://stackoverflow.com/q/51986666
tags question: http://stackoverflow.com/q/52094832
tags question: http://stackoverflow.com/q/52032525
tags question: http://stackoverflow.com/q/52082762
tags question: http://stackoverflow.com/q/52093838
tags question: http://stackoverflow.com/q/52096848
tags question: http://stackoverflow.com/q/51988166
tags question: http://stackoverflow.com/q/52019478
tags question: http://stackoverflow.com/q/52104327
tags question: http://stackoverflow.com/q/52038311
tags question: http://stackoverflow.com/q/52035934
tags question: http://stackoverflow.com/q/52052561
tags question: http://stackoverflow.com/q/51996621
tags question: http://stackoverflow.com/q/52034106
tags question: http://stackoverflow.com/q/51989660
tags question: http://stackoverflow.com/q/52058140
tags question: http://stackoverflow.com/q/52072445
tags question: http://stackoverflow.com/q/52083823
tags question: http://stackoverflow.com/q/52044392
tag name: list
tags question: http://stackoverflow.com/q/51989161
tags question: http://stackoverflow.com/q/52097767
tags question: http://stackoverflow.com/q/52034340
tags question: http://stackoverflow.com/q/51988142
tags question: http://stackoverflow.com/q/52022564
tags question: http://stackoverflow.com/q/52090212
tags question: http://stackoverflow.com/q/51958696
tags question: http://stackoverflow.com/q/52035453
tags question: http://stackoverflow.com/q/52002645
tags question: http://stackoverflow.com/q/52053579
tags question: http://stackoverflow.com/q/52015342
tags question: http://stackoverflow.com/q/52013760
tags question: http://stackoverflow.com/q/52041914
tags question: http://stackoverflow.com/q/52074332
tags question: http://stackoverflow.com/q/52103100
tags question: http://stackoverflow.com/q/52009986
tags question: http://stackoverflow.com/q/52090122
tags question: http://stackoverflow.com/q/52072935
tags question: http://stackoverflow.com/q/52022590
tags question: http://stackoverflow.com/q/52076956
tags question: http://stackoverflow.com/q/51983141
tags question: http://stackoverflow.com/q/52111627
tags question: http://stackoverflow.com/q/52059116
tags question: http://stackoverflow.com/q/52024486
tags question: http://stackoverflow.com/q/52064649
tags question: http://stackoverflow.com/q/52041035
tags question: http://stackoverflow.com/q/52111532
tags question: http://stackoverflow.com/q/52049352
tags question: http://stackoverflow.com/q/52083510
tags question: http://stackoverflow.com/q/51997373
tags question: http://stackoverflow.com/q/51989352
tags question: http://stackoverflow.com/q/52067004
tags question: http://stackoverflow.com/q/52035779
tags question: http://stackoverflow.com/q/51984323
tags question: http://stackoverflow.com/q/52041448

http://stackoverflow.com/q/52073396
has answer: http://stackoverflow.com/a/52082201
downvote count: 0
type: Question
tagged with: windows
tagged with: path
tagged with: python
has title: Converting a path to a file on a network drive from macos to windows
tagged with: macos
has body: I want to select a file on my Mac, and want the file to be opened on a Windows machine with the path I input on the mac. I have a server the files are located on, maped as follows: Mac: /Volumes/myraid/projects/file.txt Windows X:\projects\file.txt Is there any way I can convert the path from the mac to any file on the server, to be opened on any windows machine, that is able to access the server? The code to manipulate the path should be executed on the windows machine. Edit: My main problem is the front part of the path, because windows assigns a different letter for each individual drive (e.g. X:\). Especially when I have multiple network drives and I want to be able to select files from all of them.
favorite count: 0
upvote count: 2
answer count: 2
tagged with: network-drive
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/52073726
score: 2

http://stackoverflow.com/q/52017758
has title: Django: Using ".first()" on a related queryset triggers queries despite "prefetch_related". Is there a workaround?
answer count: 0
downvote count: 0
favorite count: 0
has body: I'm trying to optimize some querysets in my Django code by using prefetch_related. However, I've realized that if elsewhere in the code, a queryset function such as first, last, latest etc.. is called on a related queryset, a query is triggered regardless, effectively nullifying the optimization. e.g. class Client(models.Model): # [...] @property def latest_order(self): self.orders.latest('ordered_at') # Order is a Many-to-one related obj Using Client.objects.prefetch_related('orders') is not gonna be useful and latest_order will still trigger a query for each Client. Is there a way around this without altering the Client model's property? Otherwise if that's the best solution, what's the best way to retain the functionality latest_order? The only way I can think of is to just to replicate latest functionality but in memory (via the sorted function), however this means that I lose out on being able to do this operation database-side if it's advantageous (e.g. I'm just looking at 1 client with A LOT of orders).
tagged with: query-optimization
type: Question
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/90985797
has comment: http://stackoverflow.com/comment/90985783
upvote count: 2
has comment: http://stackoverflow.com/comment/90986103
tagged with: django-models
type: UnansweredQuestion
score: 2

http://stackoverflow.com/comment/91013694
score: 0
comment on: http://stackoverflow.com/q/52031397
type: Comment
type: QuestionComment
has text: I feel like you are missing Customer_review in zip().

http://stackoverflow.com/comment/90891416
comment on: http://stackoverflow.com/q/51970343
has text: I'm pretty sure you don't need an explicit `tf.constant`, even if the conversion will happen under the hood anyway.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91147221
type: AnswerComment
has text: @AlhpaDelta I changed the code to only parse strings through isFloat and isInt - should work now
type: Comment
comment on: http://stackoverflow.com/a/52097927
score: 1

http://stackoverflow.com/q/52081316
type: AnsweredQuestion
has body: When I try to view the built-in function all() in PyCharm, I could just see "pass" in the function body. How to view the actual implementation so that I could know what exactly the built-in function is doing? def all(*args, **kwargs): # real signature unknown """ Return True if bool(x) is True for all values x in the iterable. If the iterable is empty, return True. """ pass
has comment: http://stackoverflow.com/comment/91113002
upvote count: 8
type: Question
tagged with: built-in
has title: How to view the implementation of python's built-in functions in pycharm?
tagged with: function
answer count: 1
accepted answer: http://stackoverflow.com/a/52082427
downvote count: 0
linked to: http://stackoverflow.com/q/8608587
has answer: http://stackoverflow.com/a/52082427
tagged with: python
favorite count: 0
score: 8
tagged with: pycharm
has comment: http://stackoverflow.com/comment/91120422
duplicate of: http://stackoverflow.com/q/8608587

http://stackoverflow.com/comment/91029827
score: 0
has text: post the full logs
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52039592

http://stackoverflow.com/comment/90996503
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52022551
has text: I added the case when md 5 _ password was added to the question.

http://stackoverflow.com/comment/90953053
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52001964
score: 4
has text: something like: `entity_mapped = [mapping[i] for i in entities_list if i in mapping]` ? Does that produce the expected output?

http://stackoverflow.com/q/52013220
downvote count: 0
has body: A beginner python programming learner here. I'm making a very simple two number calculator in python. Although it runs perfectly, I can't fix the issue with floating numbers ending with ".0". I want to remove this ending. I tried a few things but they didn't work. What condition do I need to add inside the code? Could you please take a look at it below: def calculator(): num1 = float(input('First number: ')) operator = input('+, -, / or * ? ') num2 = float(input('Second Number: ')) if operator == '+': return print(num1, '+', num2, '=', num1 + num2) elif operator == '-': return print(num1, '-', num2, '=', num1 - num2) elif operator == '/': return print(num1, '/', num2, '=', num1 / num2) elif operator == '*': return print(num1, '*', num2, '=', num1 * num2) calculator() Thank you in advance! I exactly did what @water-winter suggested but whenever I execute the program and enter numbers and operator I get this error: if result.is_integer(): AttributeError: 'int' object has no attribute 'is_integer' Update: Looks like that only "/" operator works perfectly. The other 3 operators give the same error above. :/ New Update: Finally I managed to make the calculator programming flawlessly! def calculator(): num1 = float(input("First number: ")) operator = input("Choose: +, -, /, or *") num2 = float(input("Second number: ")) num1 = int(num1) if num1.is_integer() else num1 num2 = int(num2) if num2.is_integer() else num2 add = (num1 + num2) subtract = (num1 - num2) divide = (num1 / num2) multiply = (num1 * num2) if operator == "+" and add % 1 == 0: print(num1, "+", num2, "is equal to:", int(add)) elif operator == "+" and not add % 1 == 0: print(num1, "+", num2, "is equal to:", add) elif operator == "-" and subtract % 1 == 0: print(num1, "-", num2, "is equal to:", int(subtract)) elif operator == "-" and not subtract % 1 == 0: print(num1, "-", num2, "is equal to:", subtract) elif operator == "/" and divide % 1 == 0: print(num1, "/", num2, "is equal to:", int(divide)) elif operator …
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90977246
has comment: http://stackoverflow.com/comment/90977255
score: 1
duplicate of: http://stackoverflow.com/q/2440692
type: Question
upvote count: 1
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/52013419
has title: How to remove the floating number ending in python?
linked to: http://stackoverflow.com/q/2440692
tagged with: python
tagged with: python-3.x
tagged with: pycharm

powerbi
tags question: http://stackoverflow.com/q/52079733
type: Tag
tag name: powerbi

http://stackoverflow.com/comment/91041122
has text: It is strange, when I tried to use it on my macbook with a small sample, it uses all the cores on the mac, but on the windows nothing happens ...
score: 1
comment on: http://stackoverflow.com/q/52045028
type: Comment
type: QuestionComment

msys2
tags question: http://stackoverflow.com/q/52077195
tags question: http://stackoverflow.com/q/52078733
tag name: msys2
type: Tag
tags question: http://stackoverflow.com/q/51981570

http://stackoverflow.com/a/52108792
has body: I think, you need: idx = pd.date_range('2011-01-01','2011-12-31') mux = pd.MultiIndex.from_product([idx, df['ID'].unique()], names=['Date','ID']) df = df.set_index(['Date','ID']).reindex(mux, fill_value=0) print (df.head()) Name Score Rank Date ID 2011-01-01 100 0 0 0 101 0 0 0 2011-01-02 100 0 0 0 101 0 0 0 2011-01-03 100 0 0 0
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52108703
answers question: http://stackoverflow.com/q/52108703
type: Answer
has comment: http://stackoverflow.com/comment/91168335
upvote count: 2
score: 2

http://stackoverflow.com/a/52025914
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/52025769
has comment: http://stackoverflow.com/comment/91004002
upvote count: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/91002978
has body: Use: #list of DataFrames dfs = [dfdate, dfqty, dfprices] #list comprehension with reshape comb = [x.unstack() for x in dfs] #join together df = pd.concat(comb, axis=1, keys=['date', 'qty', 'price']) #remove second level of MultiIndex and index to column df = df.reset_index(level=1, drop=True).reset_index().rename(columns={'index':'col'}) #extract all values without first by indexing [1:] and first letter by [0] df['Number'] = df['col'].str[1:] df['Letter'] = df['col'].str[0] cols = ['Letter', 'Number', 'date', 'qty', 'price'] #change order of columns df = df.reindex(columns=cols) print (df) Letter Number date qty price 0 x 1 2 1 0 1 x 1 4 2 2 2 x 1 7 6 2 3 x 1 5 6 4 4 x 1 6 8 4 5 x 2 2 3 2 6 x 2 2 1 0 7 x 2 2 1 0 8 x 2 6 7 3 9 x 2 7 5 4 10 y 1 3 2 1 11 y 1 1 4 3 12 y 1 4 3 2 13 y 1 5 2 1 14 y 1 9 8 3
type: Answer
accepted answer of: http://stackoverflow.com/q/52025769

http://stackoverflow.com/a/51999818
answers question: http://stackoverflow.com/q/51999680
has body: Try this one to get desired output: from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.support.ui import WebDriverWait as wait print(wait(driver, 10).until(EC.presence_of_element_located((By.XPATH, '//table[@id="example"]//td'))).text)
has comment: http://stackoverflow.com/comment/90948996
type: Answer
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/90949150
accepted answer of: http://stackoverflow.com/q/51999680
has comment: http://stackoverflow.com/comment/90948741
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/90948816
downvote count: 0

http://stackoverflow.com/a/52069717
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52065970
type: Answer
score: 1
upvote count: 1
has body: Generally, when you need linear complexity, but can think of a quadratic solution, then think about precomputing things. Code with improved complexity: from itertools import accumulate # use itertools accumulate to compute prefix sums, it not allowed, can simply write your own function def solution(N, M, X, Y): # precompute the mines along rows and cols [O(k)] rows = [0 for i in range(N)] cols = [0 for j in range(M)] for k in range(len(X)): rows[X[k]]+=1 cols[Y[k]]+=1 # precompute the prefix sum and suffix sum( i.e the total mine grids from left/right upto, including this index ) [O(M+N)] r_left = list(accumulate(rows)) r_right = list(reversed(list(accumulate(reversed(rows))))) c_left = list(accumulate(cols)) c_right = list(reversed(list(accumulate(reversed(cols))))) # now horizontal splits possible at indices where the left and right accumulations are same [O(M+N)] pos_horizontal_spilts = sum([1 if r_left[i]==r_right[i]-rows[i] else 0 for i in range(N)]) pos_vertical_spilts = sum([1 if c_left[j]==c_right[j]-cols[j] else 0 for j in range(M)]) return pos_horizontal_spilts + pos_vertical_spilts Example run: solution(N = 5, M = 5, X = [0, 4, 2, 0], Y = [0, 0, 1, 4]) rows = [2, 0, 1, 0, 1] cols = [2, 1, 0, 0, 1] r_left, r_right = [2, 2, 3, 3, 4], [4, 2, 2, 1, 1] c_left, c_right = [2, 3, 3, 3, 4], [4, 2, 1, 1, 1] pos_horizontal_spilts = 2 pos_vertical_spilts = 1 P.S : I have not submitted it on codility, so some corner cases might be unhandled.
has comment: http://stackoverflow.com/comment/91089668
has comment: http://stackoverflow.com/comment/91089538
answers question: http://stackoverflow.com/q/52065970
type: AcceptedAnswer

http://stackoverflow.com/comment/91126764
type: Comment
has text: Indexing in Python (and in all other good languages) starts from 0, not from 1. So, `x=0`. But even after this change, your code is still wrong: the number of iterations must be `len(vowels)`, not `len(new_message)`.
comment on: http://stackoverflow.com/q/52088236
score: 1
type: QuestionComment

http://stackoverflow.com/comment/91162403
type: AnswerComment
score: 0
type: Comment
has text: @SpiderRico True, and that makes the time complexity O(len(l1) + len(l2)) + O(min(len(l1), len(l2)), which is still O(len(l1) + len(l2)). However, the set comprehensions are pretty fast, and more importantly, the intersection operation is done at C speed, which is significantly faster than your Python loop with an `if` test.
comment on: http://stackoverflow.com/a/52104784

http://stackoverflow.com/comment/90998171
comment on: http://stackoverflow.com/a/51987348
has text: When passing `specific_fixture` to `specific_test` it says that the variable shadows function name - what's the point of passing `specific_fixture` to the `specific_test` function ? `specific_fixture` is only a local variable when inside the function, it won't be recognized as the setup function anyway
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/q/52032966
tagged with: dataframe
linked to: http://stackoverflow.com/q/45395093
has comment: http://stackoverflow.com/comment/109014102
has title: Pyspark dataframe filter using occurrence based on column
tagged with: apache-spark
answer count: 1
favorite count: 0
has body: I have pyspark dataframe and I want to filter dataframe with columns A and B. Now I want to get only values of B where occurrence of A is greater than some number N. Column A is like and id which can have repeated values. Right now I am doing group by and the filtering and using list of values which is not efficient so I am looking for efficient solution. Example N = 5 Input Image Expected Output Image You can see there that only ID1 and ID3 of column A is selected because of threshold of 5 rest all are excluded.
upvote count: 2
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91016477
tagged with: python
has answer: http://stackoverflow.com/a/52033025
score: 1
downvote count: 1
type: Question
tagged with: pyspark

http://stackoverflow.com/comment/90936558
type: QuestionComment
has text: I don't know why but matplotlib reduces image resolution from 704x490 to 562x394. I can `plt.savefig('file.png', bbox_inches='tight', dpi =125 )` which yields an image of 703x493 resolution. That being good enough, is there a way to just keep my image resolution during conversion?
score: 0
comment on: http://stackoverflow.com/q/51991592
type: Comment

http://stackoverflow.com/q/52073181
has body: I have been trying to run the following code in three different weblinks. Code works fine on one weblink. However, it throws an error message about "Message: stale element reference: element is not attached to the page document". I looked into forum's two previous threads (Python Selenium stale element fix and How to Navigate to a New Webpage In Selenium?) about the same error message but didn't get sort it out the issue. Here is my code: driver.get('https://github.com/avassalotti') contributions = driver.find_elements_by_xpath(".//ul[@class='filter-list small']//li") print(contributions) for item in contributions: print (item) print(item.text) item.click() time.sleep(3) contribution = driver.find_element_by_xpath(".//*[@class='f4 text-normal mb-2']").text print(contribution) Program works for this link (https://github.com/alex) and does not work for (https://github.com/agronholm, https://github.com/avassalotti). Any advice to fix the issue.
has title: Message: stale element reference: element is not attached to the page document in Python
has comment: http://stackoverflow.com/comment/91096943
has answer: http://stackoverflow.com/a/52075477
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/44838538
has comment: http://stackoverflow.com/comment/91096560
linked to: http://stackoverflow.com/q/27003423
tagged with: python
favorite count: 0
tagged with: webdriverwait
type: Question
has comment: http://stackoverflow.com/comment/91097395
score: 0
tagged with: selenium
upvote count: 1
linked to: http://stackoverflow.com/q/24775988
answer count: 1
downvote count: 1
tagged with: selenium-webdriver
has comment: http://stackoverflow.com/comment/91096760
tagged with: staleelementreferenceexception

http://stackoverflow.com/comment/91096600
comment on: http://stackoverflow.com/q/52073400
type: QuestionComment
has text: @Moberg this does not only apply to lists, it works the same for all types.
score: 2
type: Comment

http://stackoverflow.com/a/52082568
accepted answer of: http://stackoverflow.com/q/52082414
has comment: http://stackoverflow.com/comment/91115634
type: AcceptedAnswer
downvote count: 0
upvote count: 2
answers question: http://stackoverflow.com/q/52082414
type: Answer
score: 2
has comment: http://stackoverflow.com/comment/91115874
has body: Note that you are not using the argument you have added in the function body. Judging from the docstring, I assume you want to make the upper boundary of the range flexible. Try sth along the following lines: def fname(arg1): # actually use the argument to build the range result = list(range(0, arg1, 5)) return result def main(): arg1 = 101 from_fname_function = fname(arg1) print(from_fname_function)

javascript
tags question: http://stackoverflow.com/q/52084162
tags question: http://stackoverflow.com/q/52098156
tags question: http://stackoverflow.com/q/51984646
tags question: http://stackoverflow.com/q/51976453
tags question: http://stackoverflow.com/q/52080459
tags question: http://stackoverflow.com/q/52107234
tags question: http://stackoverflow.com/q/52111376
tag name: javascript
tags question: http://stackoverflow.com/q/51961513
tags question: http://stackoverflow.com/q/52020484
tags question: http://stackoverflow.com/q/52026423
tags question: http://stackoverflow.com/q/51958739
tags question: http://stackoverflow.com/q/51987936
tags question: http://stackoverflow.com/q/52098444
type: Tag
tags question: http://stackoverflow.com/q/52061898
tags question: http://stackoverflow.com/q/52101331
tags question: http://stackoverflow.com/q/51997403
tags question: http://stackoverflow.com/q/52007266
tags question: http://stackoverflow.com/q/51978995
tags question: http://stackoverflow.com/q/52011622
tags question: http://stackoverflow.com/q/51985389
tags question: http://stackoverflow.com/q/51957005
tags question: http://stackoverflow.com/q/52014159
tags question: http://stackoverflow.com/q/51982047
tags question: http://stackoverflow.com/q/52063944
tags question: http://stackoverflow.com/q/52003414
tags question: http://stackoverflow.com/q/52069069
tags question: http://stackoverflow.com/q/52049876
tags question: http://stackoverflow.com/q/52086726
tags question: http://stackoverflow.com/q/52046078
tags question: http://stackoverflow.com/q/52044184
tags question: http://stackoverflow.com/q/52058788
tags question: http://stackoverflow.com/q/52059893
tags question: http://stackoverflow.com/q/52010016
tags question: http://stackoverflow.com/q/52029343
tags question: http://stackoverflow.com/q/51957928

http://stackoverflow.com/q/52104337
type: Question
has comment: http://stackoverflow.com/comment/91159852
has answer: http://stackoverflow.com/a/52104526
has answer: http://stackoverflow.com/a/52104490
has comment: http://stackoverflow.com/comment/91159833
answer count: 3
has comment: http://stackoverflow.com/comment/91160039
type: UnansweredQuestion
tagged with: python
has body: I don't know how compare 2 different lists of list and write what I need: I have a list of list. I need to check 3 things. First if the item[1], item[2] of este_mes item are in the list resto and add the complete item to changes. Second if the item[1], item[2] of este_mes item are not in the resto, add to news and for the item[1], item[2] of resto item are not este_mes, add to lost este_mes = [ ['1', 'A', 'a', '300'], ['1', 'B', 'b', '30'], ['1', 'C', 'c', '100'], ['1', 'D', 'd', '4500']] resto = [ ['2', 'A', 'a', '3'], ['2', 'B', 'b', '302'], ['2', 'X', 'x', '98'], ['2', 'Z', 'z', '276'], ['3', 'A', 'a', '54'], ['3', 'B', 'b', '65'], ['3', 'F', 'f', '76'], ['3', 'Y', 'y', '99']] # I need something like this but I don't know how can I do it! changes = [] news = [] lost = [] for item in este_mes: if item[1] and item[2] are in some item of resto: changes.append(item_resto) if item[1] and item[2] are not in some item of resto: news.append(item) for item in resto: if item[1] and item[2] are not in item of este_mes: lost.append(item_resto) the answers should be: news = [['1', 'C', 'c', '100'], ['1', 'D', 'd', '4500']] lost = [['2', 'X', 'x', '98'], ['2', 'Z', 'z', '276'], ['3', 'F', 'f', '76'], ['3', 'Y', 'y', '99']] changes = [['2', 'A', 'a', '3'], ['2', 'B', 'b', '302'], ['3', 'A', 'a', '54'], ['3', 'B', 'b', '65']] This is the answer: este_mes = [] resto = [] changes = [] for item in este_mes: for rest in resto: if (item[1] == rest[1] and item[2] == rest[2]): rest = [rest[0]] + [item[1]] + [item[2]] + ([float(item[3]) - float(rest[3])]) changes.append(rest) resto.remove(rest)
has title: Work with a list of list and make some comparisons Python
has answer: http://stackoverflow.com/a/52104778
score: 0
has comment: http://stackoverflow.com/comment/91160725

text
tags question: http://stackoverflow.com/q/52037404
type: Tag
tags question: http://stackoverflow.com/q/51999656
tags question: http://stackoverflow.com/q/52046149
tags question: http://stackoverflow.com/q/52048391
tags question: http://stackoverflow.com/q/52061299
tags question: http://stackoverflow.com/q/52083185
tags question: http://stackoverflow.com/q/52061933
tags question: http://stackoverflow.com/q/51996822
tags question: http://stackoverflow.com/q/52002973
tags question: http://stackoverflow.com/q/52016751
tags question: http://stackoverflow.com/q/52048694
tags question: http://stackoverflow.com/q/52070222
tag name: text
tags question: http://stackoverflow.com/q/52101321
tags question: http://stackoverflow.com/q/52081913

http://stackoverflow.com/a/52054602
has body: The convention is to define the weights as attributes of the network and not inside the predict function, same remark for the optimizer and train_step. Maybe it could help because train_step = optimizer.minimize(loss) look at the whole graph.
upvote count: 2
accepted answer of: http://stackoverflow.com/q/52045375
answers question: http://stackoverflow.com/q/52045375
score: 2
type: AcceptedAnswer
downvote count: 0
type: Answer

http://stackoverflow.com/q/51997310
upvote count: 0
answer count: 1
favorite count: 0
has body: I have two spiders class called 'categories' and 'articles', where the categories class contain all the url what i need pass to the articles class. But i don't know how do it. Can somebody helpme ? thanks
tagged with: python
score: -1
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90943887
tagged with: scrapy
downvote count: 1
type: Question
has answer: http://stackoverflow.com/a/51998611
has title: Issue with scrapy python from two class spiders

http://stackoverflow.com/comment/90900639
comment on: http://stackoverflow.com/q/51974905
type: Comment
type: QuestionComment
score: 1
has text: Yep, more or less. See if you can do it, and I'll check tomorrow and help out if you get stuck - it's getting late here now.

http://stackoverflow.com/q/52022935
upvote count: 1
tagged with: python
tagged with: recursion
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/65196070
has answer: http://stackoverflow.com/a/65196070
has answer: http://stackoverflow.com/a/52031948
type: Question
has comment: http://stackoverflow.com/comment/90997024
has comment: http://stackoverflow.com/comment/91014252
has comment: http://stackoverflow.com/comment/90996186
has comment: http://stackoverflow.com/comment/90996166
has comment: http://stackoverflow.com/comment/90996185
score: -1
has comment: http://stackoverflow.com/comment/90996148
has body: class Solution: def climbStairs(self, n): """ :type n: int :rtype: int """ if n == 1: return 1 if n == 2: return 2 else: return self.climbStairs(n - 1) + self.climbStairs(n - 2) My solution however is not working on Leetcode. Do you know why this is? Thank you so much! I am trying to solve fibonacci sequence
answer count: 2
has title: Why is my solution on LeetCode not working (recursion, python)?
has comment: http://stackoverflow.com/comment/90996234
accepted answer: http://stackoverflow.com/a/52031948
favorite count: 0
downvote count: 2

http://stackoverflow.com/comment/91082608
score: 0
has text: Done! Thank you. Could you also help me in upvoting my answer? I am new here and had 2 bad questions asking by the community. It will help me. Thank you.
type: AnswerComment
comment on: http://stackoverflow.com/a/52065786
type: Comment

http://stackoverflow.com/q/52069778
accepted answer: http://stackoverflow.com/a/52072955
score: 2
type: AnsweredQuestion
favorite count: 0
tagged with: python-3.x
type: Question
has answer: http://stackoverflow.com/a/52069830
tagged with: python
tagged with: selenium-webdriver
tagged with: xpath
possible better answer: http://stackoverflow.com/a/52069830
has title: SyntaxError: Failed to execute 'evaluate' on 'Document': The string '//img[contains('1236548597')]' is not a valid XPath expression
upvote count: 3
has body: I am getting syntax error: SyntaxError: Failed to execute 'evaluate' on 'Document': The string '//img[contains('1236548597')]' is not a valid XPath expression. My code: enter_chat = driver.find_element_by_xpath("//img[contains('1236548597')]") enter_chat.click()
answer count: 2
tagged with: selenium
downvote count: 1
has answer: http://stackoverflow.com/a/52072955

http://stackoverflow.com/a/52103520
has body: First of all, lowercase file names in order to minimize the number of possible options regex = re.compile('feedback.{0,3}report.*\.xlsx?', flags=re.IGNORECASE) looks for 'feedback', next up to 3 whatever characters, next 'report', and whatever again, ending with a dot and xls or xlsx extension or just filename = 'ZL-SA_feedback report_012844.xlsx' matched = re.search('feedback.{0,3}report.*\.xlsx?', filename.lower()) Also you can use python glob module to search files in linux fashion: import glob glob.glob('*[fF][eE][dD][bB][aA][cC][kK]*[rR][eE][pP][oO][rR][tT]*.xlsx')
type: Answer
upvote count: 1
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/52103370

http://stackoverflow.com/a/52006416
has comment: http://stackoverflow.com/comment/90963542
has body: If you're not interested in the fact that a key is pressed, but rather that a key is held down, use pygame.key.get_pressed to get the keyboard state. One way to solve your issue is to create a dict that maps each arrow key to a vector, and then simply iterate that dict and check if the specific key is pressed, something like this: keymap = { pygame.K_LEFT: Vector2(-speed, 0), pygame.K_RIGHT: Vector2(speed, 0), pygame.K_UP: Vector2(0, -speed), pygame.K_DOWN: Vector2(0, speed) } while not done: for event in pygame.event.get(): if event.type == pygame.QUIT: done = True current_time = pygame.time.get_ticks() pressed = pygame.key.get_pressed() for key in keymap: if pressed[key]: if current_time - previous_time &gt; 500: previous_time = current_time projectiles.add(Projectile(player.rect.x, player.rect.y, keymap[key])) Some further notes: You can add sprites to multiple groups, and it usually makes sense to add all sprites to a groups that holds all sprites to keep the main loop simple. You already have a group called all_sprites_list, so use it like this. Just add all new projectiles to that groups, also, and call update/draw only on that very group: ... if current_time - previous_time &gt; 500: previous_time = current_time Projectile(player.rect.x, player.rect.y, keymap[key], all_sprites_list, projectiles) # ----- Game Logic all_sprites_list.update() screen.fill(GREEN) all_sprites_list.draw(screen) pygame.display.flip() ... and in Projectile.py: ... class Projectile(pygame.sprite.Sprite): def __init__(self, x, y, vel, *groups): super().__init__(groups) ...
answers question: http://stackoverflow.com/q/52006196
type: Answer
accepted answer of: http://stackoverflow.com/q/52006196
has comment: http://stackoverflow.com/comment/90963473
has comment: http://stackoverflow.com/comment/90963354
score: 4
upvote count: 4
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/91081532
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52065375
has text: Wow. Where is that `.put` method documented?
type: AnswerComment

http://stackoverflow.com/comment/91162437
type: Comment
type: QuestionComment
has text: Got it, I've updated my answer accordingly.
comment on: http://stackoverflow.com/q/52103193
score: 0

http://stackoverflow.com/q/52071862
tagged with: recommendation-engine
favorite count: 0
has body: I'm trying to build a recommender system through a SkipGram Model, i built a variant of Word2vec adapted to my data (anime) where i use the anime watched list of a users like data =[] for key, chunk in ratings.groupby('user_id'): data.append(chunk.sort_values('user_rating').anime_id.values) my ratings dataframe has 30k unique users 12k unique anime , user rating and some metadata likes (anime_tags, year, numbers of episodes, synopsis ...etc.) I'm trying to find a way to add that metadata in my "Anime2Vec" model. May I need to build different model then (concat/blend/sum ???) the embeddings about my baseline model it's construct like that i said previously watched session of users then i use this functions : def get_batch(seq, rel_window_size=.2): """get a batch of data for a single user sequence. data will be chosen randomly from within a anime window relative to the size of the entire sequence. with the initial point chosen at random. """ window = math.floor(len(seq) * rel_window_size) +1 x = [] y = [] i = random.randint(0, len(seq)-1) for _ in range(batch_size): x.append(seq[i]) moves = list(range(max(i-window, 0), i)) + list(range(i+1, min((i+window + 1, len(seq))))) j = random.choice(moves) y.append(seq[j]) i = j return x, y def gen_batch(data, batch_size, rel_window_size=.2, shuffle=True): """make a generator for data using each 'user' as a document.""" while True: for doc_index, doc in enumerate(data): x, y = get_batch(doc, rel_window_size) yield np.array(x, 'int32'), np.expand_dims(np.array(y,'int32'), 1) if shuffle: random.shuffle(data) Then i took few sample for try if my model works fine val_anime = ['Naruto', 'Bleach', "Clannad", "Air", "Code Geass Hangyaku no Lelouch", "Overlord", "Mononoke Hime", "Hajime no Ippo", "Fullmetal Alchemist"] val_ids = [reverse_dictionary[s] for s in val_anime] val_set = np.array(val_ids, 'int32') Then i define model and data # valid_examples = np.array(random.sample(range(1, valid_window+1), valid_size))# valid_e vocab_size …
answer count: 0
type: UnansweredQuestion
tagged with: word2vec
upvote count: 1
tagged with: python
has title: Variant Word2Vec to MetaWord2Vec
score: 1
type: Question
downvote count: 0
has comment: http://stackoverflow.com/comment/94581985

http://stackoverflow.com/q/52097392
has body: I have a multi class classification problem where I want to get the predictions as probabilities that are independent of each other. For example there are 4 classes being predicted, currently the output for first observation looks like: [0.27661473, 0.34121073, 0.25299197, 0.12918257] Where the probabilities sum to 1. Is it possible to get it so they don't depend on each other, i.e. treat each one as a binary without having to make 4 separate binary classifiers?
has comment: http://stackoverflow.com/comment/91148003
tagged with: scikit-learn
has comment: http://stackoverflow.com/comment/91148139
favorite count: 0
has comment: http://stackoverflow.com/comment/91148407
tagged with: prediction
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91147672
tagged with: python
has title: Sklearn: Get probabilities from multi class classification that are independent of each other
answer count: 0
upvote count: 2
score: 1
has comment: http://stackoverflow.com/comment/91146830
has comment: http://stackoverflow.com/comment/91146693
downvote count: 1
has comment: http://stackoverflow.com/comment/91148254
type: Question
tagged with: random-forest
has comment: http://stackoverflow.com/comment/91148475

http://stackoverflow.com/q/52074820
accepted answer: http://stackoverflow.com/a/52075188
has comment: http://stackoverflow.com/comment/91099518
has answer: http://stackoverflow.com/a/66941880
possible better answer: http://stackoverflow.com/a/52075471
answer count: 3
has answer: http://stackoverflow.com/a/52075471
downvote count: 0
has comment: http://stackoverflow.com/comment/118328869
has comment: http://stackoverflow.com/comment/91099498
tagged with: copy
favorite count: 0
has answer: http://stackoverflow.com/a/52075188
tagged with: python
has comment: http://stackoverflow.com/comment/91099630
tagged with: shutil
has body: I need to copy the files with certain patterns. I need to perform the non recursive copy on a given directory using shutil. I tried this code given below with performs recursive copy. Is there any options to specify in it to do the non recursive copy. from fnmatch import fnmatch, filter from os.path import isdir, join from shutil import copytree, ignore_patterns src_directory = r'PATH' dst_directory = r'PATH' copytree(src_directory, ignored_directory,ignore=ignore_patterns('*.txt'))
score: 2
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/18371768
has title: How to perform a non recursive copy using python
upvote count: 2
type: Question
tagged with: non-recursive

http://stackoverflow.com/q/51996701
has comment: http://stackoverflow.com/comment/90942744
tagged with: scipy
has answer: http://stackoverflow.com/a/51997684
has comment: http://stackoverflow.com/comment/90942789
type: Question
tagged with: numpy
answer count: 2
has comment: http://stackoverflow.com/comment/90942785
has answer: http://stackoverflow.com/a/75721046
has comment: http://stackoverflow.com/comment/90943801
has body: I am trying to use loadmat from scipy.io. According to their documentation [LINK], it should be fairly easy to use loadmat. This is how I use it: import scipy.io as sio mat_contents = sio.loadmat('octave_a.mat') I get the following error message: AttributeError: 'module' object has no attribute 'loadmat' I tried uninstalling and installing numpy andscipy. However, it didn't work. My numpy version is 1.15.1 and the scipy version is 1.1.0. Here is how I install: sudo -H pip install numpy sudo -H pip install scipy It is discouraged to install with sudo. Nonetheless, I cannot install with --user flag since I still get permission error. Any help is greatly appreciated.
has comment: http://stackoverflow.com/comment/90942832
possible better answer: http://stackoverflow.com/a/75721046
score: 0
has comment: http://stackoverflow.com/comment/90942889
accepted answer: http://stackoverflow.com/a/51997684
has comment: http://stackoverflow.com/comment/90942950
has comment: http://stackoverflow.com/comment/90942775
has comment: http://stackoverflow.com/comment/90942765
has comment: http://stackoverflow.com/comment/90942855
tagged with: python
has comment: http://stackoverflow.com/comment/90942725
has comment: http://stackoverflow.com/comment/90944575
type: AnsweredQuestion
has title: scipy.io has no attribute 'loadmat'

http://stackoverflow.com/a/63354710
type: Answer
upvote count: 1
score: 1
downvote count: 0
answers question: http://stackoverflow.com/q/52023002
has body: import heapq A=[('a',2),('b',1), ('d', 0), ('c', 2), ('a', 2)] h = [] for el in A: heapq.heappush(h, (el[1], el[0])) print(h) result: [(0, 'd'), (2, 'a'), (1, 'b'), (2, 'c'), (2, 'a')]

http://stackoverflow.com/a/52104461
has comment: http://stackoverflow.com/comment/91163446
upvote count: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/91185261
type: Answer
has comment: http://stackoverflow.com/comment/91192236
has comment: http://stackoverflow.com/comment/91163084
downvote count: 0
has comment: http://stackoverflow.com/comment/91165180
has comment: http://stackoverflow.com/comment/91190647
score: 1
has body: Note: I use Python 2.x, porting this to 3.x shouldn't be difficult. My idea is simple - disk space is plentiful, so let's do some preprocessing and turn that big pickle file into something that is easier to process in small chunks. Preparation In order to test this, I wrote a small script the generates a pickle file that resembles yours. I assumed your input images are grayscale and have 8bit depth, and generated 10000 random images using numpy.random.randint. This script will act as a benchmark that we can compare the preprocessing and processing stages against. import numpy as np import pickle import time IMAGE_WIDTH = 600 IMAGE_HEIGHT = 600 FILE_COUNT = 10000 t1 = time.time() with open('data/raw_data.pickle', 'wb') as f: for i in range(FILE_COUNT): data = np.random.randint(256, size=IMAGE_WIDTH*IMAGE_HEIGHT, dtype=np.uint8) data = data.reshape(IMAGE_HEIGHT, IMAGE_WIDTH) pickle.dump(data, f) print i, t2 = time.time() print '\nDone in %0.3f seconds' % (t2 - t1) In a test run this script completed in 372 seconds, generating ~ 10 GB file. Preprocessing Let's split the input images on a row-by-row basis -- we will have 600 files, where file N contains row N from each input image. We can store the row data in binary using numpy.ndarray.tofile (and later load those files using numpy.fromfile). import numpy as np import pickle import time # Increase open file limit # See https://stackoverflow.com/questions/6774724/why-python-has-limit-for-count-of-file-handles import win32file win32file._setmaxstdio(1024) IMAGE_WIDTH = 600 IMAGE_HEIGHT = 600 FILE_COUNT = 10000 t1 = time.time() outfiles = [] for i in range(IMAGE_HEIGHT): outfilename = 'data/row_%03d.dat' % i outfiles.append(open(outfilename, 'wb')) with open('data/raw_data.pickle', 'rb') as f: for i in range(FILE_COUNT): data = pickle.load(f) for j in range(IMAGE_HEIGHT): data[j].tofile(outfiles[j]) print i, for i in range(IMAGE_HEIGHT): outfiles[i].close() t2 = time.time() print '\nDone in %0.3f seconds' % (t2 - t1) In a…
accepted answer of: http://stackoverflow.com/q/52102181
answers question: http://stackoverflow.com/q/52102181

http://stackoverflow.com/comment/90978105
type: QuestionComment
score: 4
comment on: http://stackoverflow.com/q/52013738
has text: Why do you want to do this with `eval` in the first place? `eval` evaluates arbitrary Python code. It doesn't evaluate things that aren't Python code, while at the same time it does evaluate things that are Python code that you didn't want evaluated like `__import__('sys').exit()`. If you design an expression language that's similar to, but not the same as, a subset of Python, you need to write a parser and interpreter for that language, or at least a parser and a translater-to-Python for that language.
type: Comment

http://stackoverflow.com/a/52027929
answers question: http://stackoverflow.com/q/52027854
has body: If all you need is a count of possible permutations, then just calculate those numbers. That number is simply the factorial of the length of the input: import math permutationcount = math.factorial(len(inputlist)) If you are creating permutations that are shorter than len(inputlist) (say, 3 out of 20), then the formula is n! / (n - k)!: n = len(inputlist) k = 3 permutationcount = math.factorial(n) // math.factorial(n - k) Of course, when k is equal to n, then you divide by 0!, which is 1. You can sort the input list, and turn it into a tuple, to create a key into a mapping: from collections import Counter def count_permutations(lists, k=None): counts = Counter() if k is None: k = len(lists[0]) for l in lists: key = tuple(sorted(l)) permutationcount = math.factorial(len(l)) // math.factorial(len(l) - k) counts[key] += permutationcount return counts Demo: &gt;&gt;&gt; count_permutations(([32,36,41], [36,32,41], [19,31,7]), k=3) Counter({(32, 36, 41): 12, (7, 19, 31): 6}) You don't really need to use a Counter here of course, but it may be convenient to use one anyway if you need the .most_common() method and don't want to look up how to sort a dictionary by value.
downvote count: 0
type: Answer
score: 1
upvote count: 1

http://stackoverflow.com/a/52077870
has comment: http://stackoverflow.com/comment/91130973
type: Answer
upvote count: 1
answers question: http://stackoverflow.com/q/52075464
score: 1
has body: You may be under the impression that Windows understands the "shebang line": #!/usr/bin/env python3 It does not. All Windows knows is that .py files can be run by Python. So you need to update your file association, or run the correct version of Python explicitly, passing the path to your script as an argument.
downvote count: 0

http://stackoverflow.com/comment/90972541
type: Comment
has text: @pault, Yep, I realised this a moment ago and added a recursive function which returns `True` when it finds a match.
type: AnswerComment
comment on: http://stackoverflow.com/a/52010795
score: 0

http://stackoverflow.com/comment/90911591
comment on: http://stackoverflow.com/q/51980776
score: 2
type: Comment
has text: @khelwood not on Windows. It's OS specific.
type: QuestionComment

http://stackoverflow.com/q/52068102
has answer: http://stackoverflow.com/a/65515080
answer count: 2
tagged with: google-cloud-platform
downvote count: 0
score: 4
has title: Google Drive Python API authorization using service account key
favorite count: 0
has body: I have the following service account json credentials file for a Google Cloud Platform project: How would I authenticate to Google Drive API using this service account? For example, when I try doing the following: from googleapiclient.discovery import build from httplib2 import Http from oauth2client import file, client, tools SCOPES = 'https://www.googleapis.com/auth/drive.metadata.readonly' flow = client.flow_from_clientsecrets('mykey.json', SCOPES) creds = tools.run_flow(flow, store) service = build('drive', 'v3', http=creds.authorize(Http())) results = service.files().list(pageSize=10, fields="nextPageToken, files(id, name)").execute() items = results.get('files', []) I get an error when running the flow command that complains about the format of the keyfile not starting with web or installed: Invalid file format. See https://developers.google.com/api-client-library/python/guide/aaa_client_secrets Expected a JSON object with a single property for a "web" or "installed" application Is there a way to use the above key to list my Drive files for my Google Service Account? If so, how would this be done?
tagged with: python
has answer: http://stackoverflow.com/a/52068161
accepted answer: http://stackoverflow.com/a/65515080
tagged with: google-drive-api
tagged with: oauth
possible better answer: http://stackoverflow.com/a/52068161
type: AnsweredQuestion
type: Question
upvote count: 4

http://stackoverflow.com/q/51969077
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51969208
downvote count: 0
score: 1
has answer: http://stackoverflow.com/a/51969638
tagged with: django
type: Question
possible better answer: http://stackoverflow.com/a/51969638
answer count: 2
has body: I am using django2.0 and would like to convert the format of the urls.py from this to from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.post_list , name='post_list'), url(r'^(?P&lt;slug&gt;[\w-]+)/$', views.post_detail, name="detail"), url(r'^category/(?P&lt;hierarchy&gt;.+)/$', views.show_category, name='category'), ] something similar to this: from django.urls import path from . import views app_name='home' urlpatterns = [ path('', views.post_list, name='post_list'), path(&lt;slug:slug&gt;/, views.post_detail, name="detail"), path(???), ] How should I code the last line in the new format. Thank you for any help rendered.
upvote count: 1
has comment: http://stackoverflow.com/comment/90888921
favorite count: 0
accepted answer: http://stackoverflow.com/a/51969208
tagged with: python
has title: Django: Change from using 'url' to 'path' in urls.py for this line (?P<hierarchy>.+)

http://stackoverflow.com/comment/101807464
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51998482
has text: Appreciate your response.just a quick question, what does levels=[0.5] mean in contour?does it mean probability of 0.5. I have some idea of contour but not used levels a lot. Second thing, rather than using p (labels 0 or 1) will it be okay to just use p as predicted probabilities

http://stackoverflow.com/a/51994349
has comment: http://stackoverflow.com/comment/90947243
score: 9
accepted answer of: http://stackoverflow.com/q/51988331
has comment: http://stackoverflow.com/comment/90940296
upvote count: 9
answers question: http://stackoverflow.com/q/51988331
downvote count: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/90940338
has comment: http://stackoverflow.com/comment/90986513
has body: You're halfway there: you have created a mock for the db client, now you have to patch the mongo_stuff.mongo function to return the mock instead of a real connection: @pytest.fixture(autouse=True) def patch_mongo(monkeypatch): db = mongomock.MongoClient() def fake_mongo(): return db monkeypatch.setattr('mongo_stuff.mongo', fake_mongo) Edit: The reason why you get the connection error is that you are importing somewhere_else on module level in test_stuff, and somewhere_else runs connection code also on module level. So patching with fixtures will come too late and will have no effect. You have to patch the mongo client before the import of somewhere_else if you want to import on module level. This will avoid the error raise, but is extremely ugly: from project.mongo_stuff import mongo_stuff import mongomock import pytest from unittest.mock import patch with patch.object(mongo_stuff, 'mongo', return_value=mongomock.MongoClient()): from project.working_class import somewhere_else @patch.object(mongo_stuff, 'mongo', return_value=mongomock.MongoClient()) def test_db1(mocked_mongo): mongo_stuff.mongo() assert True @patch.object(mongo_stuff, 'mongo', return_value=mongomock.MongoClient()) def test_db2(mocked_mongo): somewhere_else.foo() assert True You should rather avoid running code on module level when possible, or run the imports that execute code on module level inside the tests (as you already found out in the comments).
type: Answer
has comment: http://stackoverflow.com/comment/90986585

http://stackoverflow.com/comment/90931921
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51989523
has text: I'm trying to extend the mousePressEvent of any widget to emit a signal in addition to doing the original widget mousePressEvent.

http://stackoverflow.com/q/52094373
score: 1
has body: I have one program in python 2.7 trying to update it to python 3.6. I have found a difficulty on the function df.apply OLD python 2.7 code: date_cols = ['hour', 'begin_date', 'end_date'] df = df[df[date_cols].apply(_in_daterange, axis=1)] What I try to do in python 3.6 code: df = df[df[date_cols].apply(_in_daterange, axis=1)] returns an error variables missing So instead I have tried this on python 3.6: df = df[df[date_cols].apply(lambda row: _in_daterange(row['hour'],row['begin_date'], row['end_date']), axis=1)] But it won't give me the same output. # Function in_date_range def in_daterange( date: datetime, start, end): """ Checks a give date is in the range of two dates """ if isinstance(start, datetime) and isinstance(end, datetime): return date &gt;= start and date &lt; end else: return False What the dataframe looks like: hour begin_date end_date 0 2018-01-01 00:00:00 NaT NaT 1 2018-01-01 00:00:00 2018-01-02 11:29:00 2018-01-02 13:00:00 2 2018-01-01 00:00:00 NaT NaT 3 2018-01-01 00:00:00 NaT NaT 4 2018-01-01 00:00:00 NaT NaT 5 2018-01-01 00:00:00 NaT NaT 6 2018-01-01 00:00:00 NaT NaT 7 2018-01-01 00:00:00 NaT NaT 8 2018-01-01 00:00:00 2018-01-02 11:29:00 2018-01-02 13:00:00 houris generated before to get the range of hours given two dates. Then I perform a merge to get when the events take place Old program: python 2.7 pandas 0.18 New program: python 3.6 pandas 0.23
type: Question
has comment: http://stackoverflow.com/comment/91139665
has title: pandas apply function on 2.7 and 3.6
favorite count: 0
has comment: http://stackoverflow.com/comment/91139175
tagged with: pandas
tagged with: python
has comment: http://stackoverflow.com/comment/91138877
answer count: 0
upvote count: 2
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91139083
downvote count: 1

methods
tags question: http://stackoverflow.com/q/52021372
tag name: methods
type: Tag
tags question: http://stackoverflow.com/q/52105186
tags question: http://stackoverflow.com/q/52079895
tags question: http://stackoverflow.com/q/52013260
tags question: http://stackoverflow.com/q/51974293
tags question: http://stackoverflow.com/q/51992122

http://stackoverflow.com/a/51962193
has comment: http://stackoverflow.com/comment/90874585
has comment: http://stackoverflow.com/comment/90874862
has comment: http://stackoverflow.com/comment/90874512
has body: It means that keep_dims is henceforth not supported by whichever library you are using. It could be true in older versions, but now onwards use keepdims instead of keep_dims in your code. You may read about it here. Actually keepdims does not follow PEP-8's naming convention, so there is kind off controversy between these two.
score: 0
answers question: http://stackoverflow.com/q/51961961
has comment: http://stackoverflow.com/comment/90874983
type: Answer
has comment: http://stackoverflow.com/comment/90874677

http://stackoverflow.com/a/52002643
score: 2
has body: from scipy.spatial.distance import cdist blue = np.array([76, 150, 250]) def crush_color(image, color, thr = np.sqrt(12000), new = np.array([255, 255, 255])); dist_to_color = cdist(image.reshape(-1, 3), color, 'sqeuclidean').reshape(image.shape[:-1]) image[dist_to_color[..., None] &lt; thr**2] = new crush_color(image, blue) 1) instead of doing distance manually, use cdist which will calculate the distances (squared ueclidean in this case) much faster even than numpy broadcasting. 2) Do the replacement in place
answers question: http://stackoverflow.com/q/51997022
downvote count: 0
upvote count: 2
type: Answer

http://stackoverflow.com/q/51984318
tagged with: python
has body: I hope somebody can point me in the right direction. I'm relatively new to Python. I'm using an open Ergast API and am trying to import/parse a json file and filter on some of the elements. I can print the whole json file without issue, but as soon as I try to filter on driverId for example, it fails. What am I doing wrong here? Thanks in advance: import json import requests response = requests.get("https://ergast.com/api/f1/current/last/results.json?") data = response.json() print (data["driverId"]) EDIT: the response I get is: Traceback (most recent call last): File "python", line 6, in &lt;module&gt; KeyError: 'driverId'
tagged with: parsing
type: AnsweredQuestion
has title: Issue with parsing json into Python and filtering on key
upvote count: 0
has comment: http://stackoverflow.com/comment/90918043
has comment: http://stackoverflow.com/comment/90918037
type: Question
score: -2
accepted answer: http://stackoverflow.com/a/51984452
tagged with: http://stackoverflow.com/tag/json
downvote count: 2
has answer: http://stackoverflow.com/a/51984452
answer count: 1
tagged with: key
has comment: http://stackoverflow.com/comment/90918148
favorite count: 0
tagged with: python-3.x

http://stackoverflow.com/q/52036357
favorite count: 0
has answer: http://stackoverflow.com/a/52036589
has comment: http://stackoverflow.com/comment/91023231
tagged with: subclass
has comment: http://stackoverflow.com/comment/91022906
linked to: http://stackoverflow.com/q/576169
has comment: http://stackoverflow.com/comment/91022963
tagged with: python
type: AnsweredQuestion
upvote count: 2
score: 1
downvote count: 1
type: Question
has body: I have a question.I'm learning Python and trying to understand superclasses,subclasses and the hierarchy between them.I have one thing that i didn't understand completely. I'm trying to write a program where there's a "Person" superclass and "Birthday" subclass.I defined init method for both of them.What I want to do is, I want to create an instance of Person.At the same time it should create the same instance for Birthday.Because all people have birthdays :) And i want to use the methods that i defined in "Birthday" class. The code; import datetime class Person(object): def __init__(self,name): self.name=name Birthday.__init__(self,name) def gender(self,gender): self.gender=gender class Birthday(Person): def __init__(self,name): self.objectlike=[] self.birthday=None self.youget={} def setbirth(self,year,month,day): self.birthday=datetime.date(year,month,day) def getbirth(self): return self.birthday def __str__(self): return self.name def setyouget(self,year,thing): self.youget[year]=thing def setlikeob(self,thing): self.objectlike.append(thing) def nextbirth(self): thisyearbirth=getbirth().year.replace(year=datetime.date.today().year) return thisyearbirth def howlong(self): return self.nextbirth()-datetime.date.today() def getage(self): age=datetime.date.today().year-self.birthday.year return age The problem is when i create an instance of Person,for example, joey=Person('Joey Tribiani') Then i try to set a birthday for joey; joey.setbirth(1980,5,5) It says:'Person' object has no attribute 'setbirth' How can i overcome this problem? I think i should add some code to init methods but i don't know what to add.I added "Birthday.init(self,name)" to Person class but it didn't work. (By the way this is my first question.I read many topics on this website.I'm amazed by how helpful the people using it.)
possible better answer: http://stackoverflow.com/a/52036589
has title: Understanding subclasses and __init__ method
has comment: http://stackoverflow.com/comment/91023239
has comment: http://stackoverflow.com/comment/91023036
has answer: http://stackoverflow.com/a/52037496
tagged with: class
accepted answer: http://stackoverflow.com/a/52037496
answer count: 2
has comment: http://stackoverflow.com/comment/91022905

http://stackoverflow.com/a/52058791
has comment: http://stackoverflow.com/comment/91068462
type: AcceptedAnswer
downvote count: 0
type: Answer
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/91067947
answers question: http://stackoverflow.com/q/52058487
has body: When you say your input has a shape of (20204, 2), you mean that you have 20204 training examples, each having 2 dimensions. You need to tell your input to expect 2 dimensions and not 20204. The error occurs because your model expects to receive 20204 features (i.e. parameter input_dim=20204) but actually receives 2 features. To fix this, just change the parameter I mentioned above: model=Sequential() model.add(Dense(output_dim=2, init='uniform', activation='relu', input_dim=2)) model.add(Dense(output_dim=3, init='uniform', activation='softmax')) model.compile(loss='sparse_categorical_crossentropy', optimizer='adam', metrics=['accuracy']) model.fit(x_train, y_train, batch_size=12, epochs=14) loss_and_metrics = model.evaluate(x_test, y_test, batch_size=12) print(loss_and_metrics) Edit: As correctly pointed out by @today and @desertnaut, your figure shows the hidden layer having 4 neurons, not 2 like the code above would produce. To change this you need to replace the parameter output_dim=2 in your hidden layer with output_dim=4: model.add(Dense(output_dim=4, init='uniform', activation='relu', input_dim=2))
accepted answer of: http://stackoverflow.com/q/52058487

http://stackoverflow.com/a/61656340
answers question: http://stackoverflow.com/q/51982735
has comment: http://stackoverflow.com/comment/109965573
score: 1
type: AcceptedAnswer
downvote count: 0
has body: A few pointers from what I see at gem5 d9cb548d83fa81858599807f54b52e5be35a6b03 (May 2020) under gem5/configs/learning_gem5/part1/two_level.py: from common: common is at configs/common which gets found because of the above m5.util.addToPath('../../') call, so add configs/ to the PYTHONPATH as shown at: PyCharm and PYTHONPATH import m5 comes from src/python/m5 so add src/python to the PYTHONPATH as above from caches import * comes from the sibling learning_gem5/part1/caches.py, so likely this will be found automatically by PyCharm. Otherwise add that directory to the PYTHONPATH. from m5.objects import *: this is likely the one you are really interested in as it contains all the interesting objects, but unfortunately PyCharm simply cannot handle it I believe since the SimObjects are added dynamically to that namespace at startup in a very convoluted way via PyBind11 native modules + code generation. A description of how this works in more detail can be found here, but basically every SimObject class goes through some heavy code autogeneration to make this work, say e.g. src/cpu/simple/AtomicSimpleCPU.py due to SimObject('AtomicSimpleCPU.py') in src/cpu/simple/SConscript. As of 2017, PyCharm said they did not have plans for a proper native C/C++ extension setup: https://intellij-support.jetbrains.com/hc/en-us/community/posts/206018984-Developing-Python-extension-in-C-using-PyCharm With that said, I've found that it is not worth to use an IDE for the Python part of gem5. This is because the Python tends to be very simple to understand with IPDB (or impossible to setup an IDE for), and if you just grep stuff you tend to quickly guess what is going on. For C++ though I do recommend setting up Eclipse: How to setup Eclipse IDE for gem5 development? Related: Add custom modules to PyCharm Linter
upvote count: 1
type: Answer
accepted answer of: http://stackoverflow.com/q/51982735

http://stackoverflow.com/q/51994328
has title: How do i run mutiple commands on an else: statement?
has comment: http://stackoverflow.com/comment/90938706
upvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/90938417
has comment: http://stackoverflow.com/comment/90938557
favorite count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90938514
score: -3
has body: i was coding some python and ran into a problem where it only lets me run one command for an else: statement here in this i have to indent all the state after print(" ") and the it will run after g when i want it to run just with else: question = input('Is The Bee Movie Good Or Bad (g/b)') if question == "g": print(" ") print("Good") else: print(" ") import time time.sleep(1) print(".") import time time.sleep(.5) print(".") import time time.sleep(.5) print(".") import time time.sleep(.5) print(".") import time time.sleep(.5) print(".") import time time.sleep(.1) for i in range(50): print("Error, System Shutdown Active")
tagged with: python
has comment: http://stackoverflow.com/comment/90938410
has comment: http://stackoverflow.com/comment/90938408
tagged with: command
has comment: http://stackoverflow.com/comment/90938626
downvote count: 3
type: Question
tagged with: if-statement
has comment: http://stackoverflow.com/comment/90938414
has answer: http://stackoverflow.com/a/51994367

http://stackoverflow.com/q/52034629
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91019503
tagged with: python
upvote count: 4
has comment: http://stackoverflow.com/comment/91019304
has comment: http://stackoverflow.com/comment/91020766
has title: How to correct DataFrame header containing whitespaces.
answer count: 0
downvote count: 0
has comment: http://stackoverflow.com/comment/91021548
type: Question
has comment: http://stackoverflow.com/comment/91019467
has comment: http://stackoverflow.com/comment/91021081
has body: I am new to python and actually started with R. My problem is that I am unable to debug key errors from my pandas dataframes. Here is part of the code: I read in a data frame from excel with following commands. cwd = os.getcwd() os.chdir(directorytofile) os.listdir('.') file = dataset xl = pd.ExcelFile(file) df1 = cl.parse('Sheet1') Now when i want to select a header with a blank space like Lieferung angelegt am (It's German sorry for that) I get the key error. I tried different ways to delete blank spaces in my headers when building the dataframe like: sep='\s*,\s*' But it still occurs. Is there a way for me to see where the problems happen? Obviously its about the blank spaces because for headers without everything works fine.
score: 4
tagged with: pandas
has comment: http://stackoverflow.com/comment/91019661
favorite count: 0

http://stackoverflow.com/q/52079496
type: AnsweredQuestion
has body: On Quora website, i am trying to get upvoters names of each answer, by clicking on 'view upvoters', but i am not getting the right results. For example, On this Quora question link you have two answers, first one with 5 upvoters and second one with 2. The result i am getting from the below code is 5,5 . all_upvotes= browser.find_elements_by_class_name('ExpandedVoterListItem') for p in all_upvotes: p.click() time.sleep(10) wait.until(EC.visibility_of_element_located((By.CSS_SELECTOR, 'div.modal_content.modal_body'))) upvoter_name = wait.until(EC.presence_of_all_elements_located((By.CSS_SELECTOR, 'span.feed_item_answer_user'))) time.sleep(10) print ('number of upvoters found for this answer %d' % len(upvoter_name)) # print upvoters names for line in upvoter_name: print(line.text)
tagged with: selenium
tagged with: web-scraping
has answer: http://stackoverflow.com/a/52082245
type: Question
tagged with: quora
has title: Selenium : getting next button click content
score: 0
answer count: 1
tagged with: http://stackoverflow.com/tag/html
tagged with: python
accepted answer: http://stackoverflow.com/a/52082245

http://stackoverflow.com/comment/90870471
type: QuestionComment
has text: @molbdnilo That's a good answer.
score: 0
comment on: http://stackoverflow.com/q/51960129
type: Comment

http://stackoverflow.com/a/51984336
answers question: http://stackoverflow.com/q/51981095
type: Answer
has body: I had this issue yesterday. I was rather surprised that installing packages did not have an effect. But I realised then that I needed to restart the kernel. In Colab this is called Restart runtime. After restart the new version should be available for you. Here you find the restart:
score: 17
upvote count: 17
downvote count: 0

http://stackoverflow.com/a/52037823
has comment: http://stackoverflow.com/comment/91026567
score: -1
answers question: http://stackoverflow.com/q/52037765
upvote count: 0
has body: you have to use the tuple function, but it has to be a list beforehand Example: l = [4,5,6] tuple(l) RETURNS (4, 5, 6)
type: Answer
has comment: http://stackoverflow.com/comment/91026675
downvote count: 1

http://stackoverflow.com/comment/91143913
has text: This has nothing to do with programming and should be ask on superuser instead
type: Comment
comment on: http://stackoverflow.com/q/52096527
score: 0
type: QuestionComment

http://stackoverflow.com/comment/90932335
has text: I added your line in the function async. Does this look like right? `def async(self): #return grequests.map((grequests.get(u) for u in self.urls), exception_handler=self.exception, size=5) for u in self.urls: req = grequests.get(u) job = grequests.send(req) time.sleep(1)`
type: Comment
comment on: http://stackoverflow.com/a/51991308
score: 0
type: AnswerComment

http://stackoverflow.com/a/52022465
accepted answer of: http://stackoverflow.com/q/52022443
answers question: http://stackoverflow.com/q/52022443
has comment: http://stackoverflow.com/comment/90995310
has body: You should use the int.from_bytes() method to convert a byte back into an integer instead: print(int.from_bytes(array, byteorder='big', signed=True))
upvote count: 7
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/90995348
has comment: http://stackoverflow.com/comment/90995427
has comment: http://stackoverflow.com/comment/90995302
type: Answer
has comment: http://stackoverflow.com/comment/90995391
has comment: http://stackoverflow.com/comment/90995328
has comment: http://stackoverflow.com/comment/90995356
downvote count: 0
score: 7
has comment: http://stackoverflow.com/comment/90995273

http://stackoverflow.com/comment/91172178
type: QuestionComment
score: 1
has text: Does the file 'mail0.txt' actually exist in path?
comment on: http://stackoverflow.com/q/52110842
type: Comment

http://stackoverflow.com/q/52062162
type: Question
has answer: http://stackoverflow.com/a/52063339
has answer: http://stackoverflow.com/a/52066664
linked to: http://stackoverflow.com/q/51143777
answer count: 2
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/91075159
type: UnansweredQuestion
tagged with: python
tagged with: tkinter
score: 1
upvote count: 1
has title: python Tkinter - How to count the quantity of characters can be shown in expanding Label?
has comment: http://stackoverflow.com/comment/91077045
has body: I have some widgets on my Window. The Label lb3 expands with my window. I want to put there some number of characters from the long array. So, if the window is big there must be more chars, if it has been sized smaller, then less chars. Therefore I need to know the current height and width of Label in chars. There is an example for my problem: import Tkinter as tk import tkFont import sys import os last_event_H = 0 last_event_W = 0 LONG_ARRAY = '' # when window sized def sizing(event): global last_event_H global last_event_W global LONG_ARRAY if (event.width == last_event_W and event.height == last_event_H): return last_event_H = event.height last_event_W = event.width width_in_chars = lb3['width'] height_in_chars = lb3['height'] first_shown = int(lb1_text.get()) lb3_text.set(LONG_ARRAY[first_shown:first_shown + width_in_chars * height_in_chars]) lb2_text.set(LONG_ARRAY[first_shown + width_in_chars * height_in_chars] + ' ...') class WrappingLabel(tk.Label): '''a type of Label that automatically adjusts the wrap to the size''' def __init__(self, master=None, **kwargs): tk.Label.__init__(self, master, **kwargs) self.bind('&lt;Configure&gt;', lambda e: self.config(wraplength=self.winfo_width())) if __name__ == '__main__': root = tk.Tk() root.geometry("1280x640") dFont=tkFont.Font(family="Arial", size=30) # fixed Font LONG_ARRAY = 'a' * 100000 # of symbols tb_date = tk.Entry(root, font=dFont) tb_date.grid(column=0, row=0, columnspan=3, sticky=tk.NSEW) bt_find = tk.Button(root, text="...", font=dFont) bt_find.grid(column=9, row=0, columnspan=2, sticky=tk.NSEW) lb1_text = tk.StringVar() lb1_text.set("1") lb1 = tk.Label(root, textvariable=lb1_text, width=10, font=dFont, anchor=tk.NW) lb1.grid(column=0, row=1, sticky=tk.NSEW) lb2_text = tk.StringVar() lb2 = tk.Label(root, textvariable=lb2_text, width=10, font=dFont, anchor=tk.NW) lb2.grid(column=1, row=10, columnspan=9, sticky=tk.NSEW) lb3_text = tk.StringVar() lb3 = WrappingLabel(root, textvariable=lb3_text, font=dFont, an…

http://stackoverflow.com/comment/91121110
type: AnswerComment
comment on: http://stackoverflow.com/a/52084605
type: Comment
has text: Glad to have been helpful!
score: 0

http://stackoverflow.com/a/52022185
score: 4
upvote count: 4
type: AcceptedAnswer
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/52021651
answers question: http://stackoverflow.com/q/52021651
has body: Newer debian distributions (ubuntu included) no longer include 2to3 (and subsequently lib2to3) as part of the default installation of python3. It has been split into a separate package which can be installed as follows: sudo apt install 2to3

http://stackoverflow.com/a/51975334
answers question: http://stackoverflow.com/q/51965316
accepted answer of: http://stackoverflow.com/q/51965316
type: Answer
downvote count: 0
score: 3
has body: The nextCmd returns the next OID relative to the given one. It never returns the value for the given OID. If you need to query specific OID you should use getCmd function instead of nextCmd.
upvote count: 3
type: AcceptedAnswer

http://stackoverflow.com/comment/100560008
type: QuestionComment
comment on: http://stackoverflow.com/q/52009771
has text: Could you explain to me how Instagram js detect which like button you clicked since in one page there are multiple like buttons with same class name ?
score: 0
type: Comment

http://stackoverflow.com/a/51994632
accepted answer of: http://stackoverflow.com/q/51994608
type: Answer
score: 2
downvote count: 0
has body: Sort the dataframe by dates before grouping. The most recent entry will be always the last: df.sort_values('date').groupby('ID').last()
answers question: http://stackoverflow.com/q/51994608
upvote count: 2
type: AcceptedAnswer

http://stackoverflow.com/a/66055172
has body: In airflow.cfg file ( version 2.0 ) set max_num_rendered_ti_fields_per_task = -1 This worked for me.
answers question: http://stackoverflow.com/q/52018029
score: 0
type: Answer

http://stackoverflow.com/q/52072088
has title: FFmpeg create video from images, insert images as frame from timestamp?
tagged with: python
tagged with: video
score: 1
upvote count: 1
type: Question
has answer: http://stackoverflow.com/a/52075436
tagged with: batch-file
answer count: 1
downvote count: 0
has body: So I'm trying to extract every frame of a video, then use ffprobe to see when each frame is played within a video, then be able to stitch that video back together using those extracted images and ffprobe output. Right now, I have this batch file: for %%a in (*.mp4) do ( mkdir "%%~na_images" &gt; NUL ffmpeg.exe -hide_banner -i "%%a" -t 100 "%%~na_images\image-%%d.png" ffprobe.exe "%%a" -hide_banner -show_entries frame=coded_picture_number,best_effort_timestamp_time -of csv &gt; "%%~na_frames.txt" ) First, a directory is made for the images. Then ffmpeg extracts all the frames of the video to individual PNG files, which are numbered appropriately. Lastly, ffprobe sees when each frame is first shown within that video (IE: frame 1 is shown at 0 seconds, but at say 60fps then frame 2 is played at 0.016667 seconds in the video). The output looks like this: frame,0.000000,0 frame,0.000000 frame,0.017000,1 frame,0.023220 Where the first number (IE 0.17000 is the time the second frame appears) and the 2nd number is the frame number. Now my problem is using ffmpeg to take each frame and place it in the proper time within the video. I can do this using another language (probably Python), but my best guess is to make a loop to iterate through the ffprobe output file, get the frame time and image number, place that frame at the points that it appears, then move on to the next frame and time placement. Looking at the frame data I used as an example above, it 'd be something like this: for line in lines: mySplit = line.split(',') # Get image number 0 and insert at time 0.000000 This is the part that I'm not sure how to do in a coding sense. I can read in and parse the lines of the ffprobe output text file, but I have no idea how to insert the frames at certain points in a video using ffmpeg or similar solutions.
favorite count: 0
tagged with: ffmpeg
type: UnansweredQuestion

http://stackoverflow.com/a/52068070
answers question: http://stackoverflow.com/q/52067414
type: Answer
has body: If you do like this what happens? assign "targeturl" as a global variable first. targeturl = "xxxx" def function1(targeturl): driver = webdriver.Chrome() driver.get(targeturl) print('What is the website?') webPage = input() function1(webPage)
score: 0

math
tags question: http://stackoverflow.com/q/52031687
tags question: http://stackoverflow.com/q/52059934
type: Tag
tags question: http://stackoverflow.com/q/52007861
tags question: http://stackoverflow.com/q/52047289
tags question: http://stackoverflow.com/q/52001533
tags question: http://stackoverflow.com/q/51993495
tags question: http://stackoverflow.com/q/52078344
tags question: http://stackoverflow.com/q/51971352
tag name: math
tags question: http://stackoverflow.com/q/52080614

http://stackoverflow.com/q/52010715
has comment: http://stackoverflow.com/comment/90977143
type: Question
score: -2
has answer: http://stackoverflow.com/a/52013625
answer count: 2
downvote count: 4
has title: Find Unique Hex Sequence
has answer: http://stackoverflow.com/a/52013664
favorite count: 0
tagged with: hex
tagged with: python-3.x
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90980682
tagged with: python
has body: I'm trying to find unique hex "strings"(?) (unique occurrence of a hex section). Example input: F6 03 04 AA F3 03 03 AA F7 03 00 AA F4 02 40 F9 F3 03 03 AA F7 03 00 AA F4 02 40 F9 E8 51 00 F0 08 B1 2A 91 E0 03 14 AA E1 03 02 AA 08 B1 2A 91 E0 03 14 AA E1 03 02 AA E2 03 08 AA 2F 01 00 94 F5 03 00 AA 75 01 00 B4 2F 01 00 94 F5 03 00 AA 75 01 00 B4 E0 03 17 AA E1 03 15 AA E2 03 16 AA 66 01 00 94 E1 03 15 AA E2 03 16 AA 66 01 00 94 F6 03 00 AA F6 00 00 34 E0 03 14 AA E1 03 15 AA F6 00 00 34 E0 03 14 AA E1 03 15 AA F9 04 00 94 05 00 00 14 F6 03 1A 32 03 00 00 14 05 00 00 14 F6 03 1A 32 03 00 00 14 16 00 80 52 75 02 00 F9 E0 03 16 AA FD 7B 43 A9 75 02 00 F9 E0 03 16 AA FD 7B 43 A9 F4 4F 42 A9 F6 57 41 A9 F8 5F C4 A8 C0 03 5F D6 F6 57 41 A9 F8 5F C4 A8 C0 03 5F D6 Output: AA F6 00 00 34 E0 03 14 AA E1 03 15 AA F6 00 00 34 E0 03 14 *not the realistic output, since I just picked a random unique I could find, but I essentially want it to find a unique hex section with the length 20, that doesn't show up anywhere else in the code. The sequence is unique because it does not occur anywhere else in the file. And I found 20 to be a reasonable size, to make it easier to find unique sequences. Since in a normal file, short sequences such as, for example, AA F6 or even AA E2 03 16 AA 66 will appear multiple times. Any suggestions on how I can go about doing this?
upvote count: 2

http://stackoverflow.com/q/52013464
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/52034563
has comment: http://stackoverflow.com/comment/90979997
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/52034563
tagged with: selenium
has body: Windows 10Home x64 / Python 3.7.0 win64 / Selenium 3.14.0 / Geckodriver 3.14.0 / Firefox 61.0.2. I'm trying to click on the login button, even though I have copied and pasted the full XPath I am not able to click the Login button. from selenium import webdriver driver = webdriver.Firefox() driver.get('https://library.yonsei.ac.kr/') linkElem = driver.find_element_by_link_text('LOGIN').click() username = driver.find_element_by_id('id') username.send_keys('myuserAbc') password = driver.find_element_by_id('password') password.send_keys('mypass123') linkElem = driver.find_element_by_xpath("/html/body/div[2]/div[2]/div/div[2]/form/fieldset/div[2]/p[@class='loginBtn']/input[@type='submit']").click() Thank you for your help. Update1: The script works up to the point of localizing the login button, I don't have problems with Marionette or having the latest Firefox version. Update2: I added p[@class='loginBtn']/input[@type='submit'] in an effort to make it more specific but still doesn't work.
tagged with: webdriver
type: Question
has answer: http://stackoverflow.com/a/52013590
score: -1
accepted answer: http://stackoverflow.com/a/52013590
answer count: 2
tagged with: css-selectors
linked to: http://stackoverflow.com/q/47992533
has title: How to click on the element with text as LOGIN as per the website through Selenium and Python?
favorite count: 0
tagged with: xpath
has comment: http://stackoverflow.com/comment/90980850
downvote count: 2

http://stackoverflow.com/comment/91133553
score: 0
type: AnswerComment
has text: @JonClements what's the difference between the 2 Jon? But no there is no particular reason I'm using `df.replace`
comment on: http://stackoverflow.com/a/52091030
type: Comment

freecad
tags question: http://stackoverflow.com/q/51965798
type: Tag
tag name: freecad

http://stackoverflow.com/q/51964541
has comment: http://stackoverflow.com/comment/90879543
score: 2
type: AnsweredQuestion
downvote count: 0
favorite count: 0
type: Question
upvote count: 2
tagged with: python
has body: I am trying to make a call to a external Google Cloud Natural Language API from within a Celery task (using the google-cloud-python package). The problem is that the call to the API never returns (hangs): @celery.task() def get_entities_async(): return get_entities() def get_entities(): gcloud_client = LanguageServiceClient() doc = types.Document(content='This is a test.', language='en', type='PLAIN_TEXT') res = gcloud_client.analyze_entities(document=doc) # This call never returns print('Call successful!') # (This never gets printed) return res What I've tried to solve problem: Calling the method get_entities() from a script. This works fine. Added a timeout=1 and retry=False to the API call. It still hangs. Called the API using the requests module instead. This works fine with celery, so the problem has to be something within LanguageServiceClient. Any ideas on how to debug or solve this problem?
answer count: 1
has answer: http://stackoverflow.com/a/52254811
has title: Call to Google Cloud API in Celery task never returns
tagged with: celery
tagged with: flask
accepted answer: http://stackoverflow.com/a/52254811
tagged with: google-cloud-platform

http://stackoverflow.com/comment/91046160
score: 0
type: Comment
type: QuestionComment
has text: Your solution looks great, but why you execute `import` again after reload? For initilization purpose?
comment on: http://stackoverflow.com/q/52047567

http://stackoverflow.com/q/52084133
has answer: http://stackoverflow.com/a/52084203
answer count: 3
tagged with: pandas
possible better answer: http://stackoverflow.com/a/52084203
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/52084195
tagged with: python
has body: I would like to combine records that have an identical id number. For example, suppose I have this DataFrame: df=pd.DataFrame({'id': [1, 2, 2, 4], 'animal': ['dog', 'cat', 'bear', 'mouse']}) # just rearranging the order a bit df=df'id', 'animal', 'name' id animal name 1 dog john 2 cat mary 2 bear mary 4 mouse joe What I'd like to end up with is a way to get the following: id name animal more_animals 1 john dog NaN 2 mary cat bear 4 joe mouse NaN I could use df[df.duplicated('id', 'last')] to find the duplicated rows, then loop through each duplicated id and add details to the new column but wondered if there was something a bit more elegant. Anything come to mind?
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/52084195
score: 3
upvote count: 3
has title: pandas - create new column based on duplicates
has answer: http://stackoverflow.com/a/52084522
type: Question

http://stackoverflow.com/comment/90919177
has text: the xlwt module was written for use with .xls. How would I go about changing the output to be in a .xlsx format? If I change the last line of the code to replace the .txt to .xlsx it doesn't work
comment on: http://stackoverflow.com/q/51984593
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/52005364
has body: Why are you doing toarray() on the output of OneHotEncoder in the first place? Most scikit estimators will be able to handle sparse matrices well. Your pipeline part is exactly doing the same thing, which you were doing above the memory error. First, you have done this: X = DBF2.iloc[:, 0:2].values Here, DBF2 is pandas DataFrame, which has values attribute to get the underlying numpy array. So now X is a numpy array. You cannot do X.values anymore. Thats the reason of your first error. You have now corrected it. Now talking about the warning, its not related to X, but to y. (Its just a warning and nothing to worry) You did this: y = DBF2.iloc[:, 2].values So, y is a numpy array of shape (n_samples, 1). 1 because you selected only single column. But most scikit estimators require y of shape (n_samples, ). Observe the empty value after the comma. So you need to do this: y = DBF2.iloc[:, 2].values.ravel() Update: X is a sparse matrix, so you cannot use numpy operations (np.delete) on that. Do this instead: index_to_drop = [0, 2038] #&lt;=== Just add all the columns to drop here to_keep = list(set(xrange(X.shape[1]))-set(index_to_drop)) X = X[:,to_keep] # Your other code here
has comment: http://stackoverflow.com/comment/90963046
accepted answer of: http://stackoverflow.com/q/52005058
upvote count: 1
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/52005058
has comment: http://stackoverflow.com/comment/90964063
type: Answer
downvote count: 0
score: 1

http://stackoverflow.com/comment/90913618
has text: Thanks for your comment. I have a logout route with a session.pop('logged_in', None) but should I implement a session.pop in the main() even when someone first visits '/'? I tried to throw in a session.pop('logged_in', None) before the @app.route('/') but got a "Working outside of request context" error.
comment on: http://stackoverflow.com/a/51981044
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/a/52034494
type: Answer
has comment: http://stackoverflow.com/comment/91022972
score: 0
has body: This is the loop that is being executed when the problem occurs. Remember the code works and produces the correct output, except for when the blue circle replaces the mouse pointer at that point the code continues to execute correctly, its just that the screen is not updated during the 30 second delay and when the blue circle finally disappears the net result of the 30 seconds of execution is displayed. No where in my code do I change the mouse pointer. This is a Windows 10 machine, and python 3.6. while (fx != tx or fy != ty): if fx == tx: dx = 0 elif fx &gt; tx: dx = -2 if fx != tx+1 else -1 else: dx = 2 if fx != tx-1 else 1 if fy == ty: dy = 0 elif fy &gt; ty: dy = -2 if fy != ty+1 else -1 else: dy = 2 if fy != ty-1 else 1 steps += 1 if steps &gt; 0: if sAngle != eAngle: if eAngle &lt; sAngle: sAngle -= 2 else: sAngle += 2 im = Image.new("RGBA",(int(tileHeight+tileWidth/2),int(tileHeight+tileWidth/2))) if til.direction == North or til.direction == South: im.paste(til.dom.raw[til.direction],(int((tileHeight+tileWidth/2-tileWidth)/2),int(tileWidth/4))) else: im.paste(til.dom.raw[til.direction],(int(tileWidth/4),int((tileHeight+tileWidth/2-tileWidth)/2))) im = im.rotate(sAngle) imm = ImageTk.PhotoImage(im) CANVAS.delete(til.canvasID) tags.remove(til.canvasID) til.canvasID = CANVAS.create_image(fx,fy,anchor=tk.CENTER,image=imm) tags.append(til.canvasID) CANVAS.move(til.canvasID,dx,dy) fx += dx fy += dy CANVAS.update_idletasks() time.sleep(0.0000001)
answers question: http://stackoverflow.com/q/52021882
has comment: http://stackoverflow.com/comment/91022813

http://stackoverflow.com/comment/91035862
type: QuestionComment
comment on: http://stackoverflow.com/q/52042370
has text: @sophros, Thanks for providing me useful links, they look very helpful!
score: 0
type: Comment

http://stackoverflow.com/q/52020493
linked to: http://stackoverflow.com/q/51507794
has answer: http://stackoverflow.com/a/52020819
has comment: http://stackoverflow.com/comment/90992615
tagged with: django
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/52020815
score: 1
has body: I'm not really experienced in Django and graph databases. But I need to set up user authentication with MongoDB in Django. I'm using pymongo for connection to database bypassing Django db settings. But I still want to use Django authentication. In order to do so, I actually should create a user model extended from AbstractBaseUser, create custom user manager extended from BaseUserManager, and register AUTH_USER_MODEL in settings. I've also created and registered custom backend which returns my custom User object. But the problem is that it seems like Django tries to verify my User model using its database (sqlite in settings) and it can't find USERNAME_FIELD (because actually I'm not using this db. I don't know how to tell Django that it don't need to care about it. Can you provide any suggestions, please?
type: Question
tagged with: mongodb
answer count: 2
upvote count: 1
has answer: http://stackoverflow.com/a/52020815
has title: Django user authentication with custom model and mongo db
downvote count: 0
has comment: http://stackoverflow.com/comment/91008963
favorite count: 0
possible better answer: http://stackoverflow.com/a/52020819

http://stackoverflow.com/q/52056247
tagged with: python
has body: I'm following https://conda.io/docs/user-guide/tutorials/build-pkgs.html to build my first (private) Python package. I do not have it hosted on PyPi, nor I would like to. I figured out that the problem I'm running into is the same as with the demo at the linked tutorial. I.e., I follow the steps, create the meta.yaml and build.bat (skipping the .sh as Im Windows only), move into the directory with Anaconda prompt, and run conda-build .. The error message is the following: (base) C:\Users\jvanzundert\conda-bld\pyinstrument_1535453523573\test_tmp&gt;call "C:\ProgramData\Anaconda3\Scripts\activate.bat" "C:\Users\jvanzundert\conda-bld\pyinstrument_1535453523573\_test_env" (C:\Users\jvanzundert\conda-bld\pyinstrument_1535453523573\_test_env) C:\Users\jvanzundert\conda-bld\pyinstrument_1535453523573\test_tmp&gt;IF 0 NEQ 0 exit 1 (C:\Users\jvanzundert\conda-bld\pyinstrument_1535453523573\_test_env) C:\Users\jvanzundert\conda-bld\pyinstrument_1535453523573\test_tmp&gt;"C:\Users\jvanzundert\conda-bld\pyinstrument_1535453523573\_test_env\python.exe" -s "C:\Users\jvanzundert\conda-bld\pyinstrument_1535453523573\test_tmp\run_test.py" import: 'pyinstrument' Traceback (most recent call last): File "C:\Users\jvanzundert\conda-bld\pyinstrument_1535453523573\test_tmp\run_test.py", line 2, in &lt;module&gt; import pyinstrument ModuleNotFoundError: No module named 'pyinstrument' (C:\Users\jvanzundert\conda-bld\pyinstrument_1535453523573\_test_env) C:\Users\jvanzundert\conda-bld\pyinstrument_1535453523573\test_tmp&gt;IF 1 NEQ 0 exit 1 Tests failed for pyinstrument-0.13.1-py36_0.tar.bz2 - moving package to C:\Users\jvanzundert\conda-bld\broken WARNING:conda_build.build:Tests failed for pyinstrument-0.13.1-py36_0.tar.bz2 - moving package to C:\Users\jvanzundert\conda-bld\broken removing: pyinstrument-0.13.1-py36_0.tar.bz2 TESTS FAILED: pyinstrument-0.13.1-py36_0.tar.bz2 Is this a problem with my setup, or the tutorial? For my own package, I think my layout should be such (note that I'm r…
score: 2
has title: Building Conda package from scratch (tutorial) fails on tests / package layout
tagged with: anaconda
downvote count: 0
answer count: 0
type: Question
tagged with: conda
upvote count: 2
favorite count: 0
type: UnansweredQuestion

http://stackoverflow.com/q/52072588
has title: How to downgrade python 3.7 to 3.6?
type: UnansweredQuestion
score: 1
has answer: http://stackoverflow.com/a/54141285
has body: After updating my system via pacman (arch linux 4.18) most of the python scripts aren't working anymore (errors about missing modules, pipenv errors, vim plugins errors). How can I revert python to 3.6? Google didn't offer any satisfying solutions on that issue
has answer: http://stackoverflow.com/a/53091322
type: Question
answer count: 3
downvote count: 3
favorite count: 0
has comment: http://stackoverflow.com/comment/91101802
tagged with: archlinux
has comment: http://stackoverflow.com/comment/93296367
linked to: http://stackoverflow.com/q/52584907
tagged with: python
upvote count: 4
has answer: http://stackoverflow.com/a/52072654

http://stackoverflow.com/a/52081452
downvote count: 0
answers question: http://stackoverflow.com/q/52081331
type: Answer
accepted answer of: http://stackoverflow.com/q/52081331
score: 2
upvote count: 2
has body: resp = requests.get(url, headers=headers, json=json, timeout=6) getmetadata = resp.json()['objects'][1]['metadata'] newdata = base64.b64decode(getmetadata).decode('UTF-8') data = json.loads(newdata) print(data['complete']) base64.b64decode(str).decode(str) returns a string str. If that string should be json then you can use json.loads to transform the string str to a dict where you can get a single value by it's key.
has comment: http://stackoverflow.com/comment/91113931
type: AcceptedAnswer

http://stackoverflow.com/comment/90913605
type: Comment
comment on: http://stackoverflow.com/a/51980746
score: 0
type: AnswerComment
has text: I'm sorry, I am not too sure how I can post a clearer explanation of the error in the comments section because of the limited formatting but basically the error points at the . in data.to_csv and saying that it has invalid syntax. And when I comment that line out, it will point at a : in else: also saying that it is a syntax error. However, when I remove the lines of code that you suggested to me, the program is able to run without those syntax errors. I hope this explains it better.

http://stackoverflow.com/q/51989108
has comment: http://stackoverflow.com/comment/90930438
has title: How to find out the full path to the python interpreter on mac and how to build a system on the Sublime Text 3?
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/90929261
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90928206
tagged with: python
tagged with: sublimetext3
has answer: http://stackoverflow.com/a/51995484
has comment: http://stackoverflow.com/comment/90928434
has comment: http://stackoverflow.com/comment/90928845
type: Question
has comment: http://stackoverflow.com/comment/90947065
has comment: http://stackoverflow.com/comment/90928782
has comment: http://stackoverflow.com/comment/90929577
has body: I followed the instruction on the Python Crash Course: A Hands-On Project-Based Introduction by Eric Matthes to configure Sublime Text for Python 3 on Page 9. $ type -a python3 python3 is /usr/local/bin/python3 Here is the instruction on the book: I encounter the following problems. Could someone explain every details of the command "$ type -a python3", especially the sign "$", and what does this command mean? Because when I type this command in the IDLE, it returns SyntaxError: invalid syntax to me, and when I type it in the Terminal, it returns File "&lt;stdin&gt;", line 1 $ type -a Python3 ^ SyntaxError: invalid syntax to me. Then I tried to launch Python Launcher and I find the full path of the interpreter. Then I followed the command to build a new system. But when I built the command print("Hello World"), it returns /Library/Frameworks/Python.framework/Versions/3.6/bin/python3.6: can't find '__main__' module in '' [Finished in 0.1s with exit code 1] [cmd: ['/Library/Frameworks/Python.framework/Versions/3.6/bin/python3.6', '-u', '']] [dir: /Applications/Sublime Text.app/Contents/MacOS] [path: /Library/Frameworks/Python.framework/Versions/3.6/bin:/Library/Frameworks/Python.framework/Versions/3.7/bin:/Library/Frameworks/Python.framework/Versions/3.7/bin:/Library/Frameworks/Python.framework/Versions/3.6/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin] to me.
has comment: http://stackoverflow.com/comment/90940483
score: 0
answer count: 1

http://stackoverflow.com/q/52063996
tagged with: anaconda
score: 1
has comment: http://stackoverflow.com/comment/101840003
has answer: http://stackoverflow.com/a/52064810
accepted answer: http://stackoverflow.com/a/52064810
type: Question
answer count: 1
downvote count: 0
tagged with: windows
has title: Installing Anaconda on a Secondary Drive (Windows)
has comment: http://stackoverflow.com/comment/102056243
favorite count: 0
upvote count: 1
tagged with: python
has body: I'm running Windows 10 Home, and I recently downloaded Anaconda because I wanted to be able to use Spyder, and wasn't really anticipating how much storage space it would take up, so I had to uninstall it. However, my computer has two hard drives--a 100gb C:/ drive that windows boots off of and a much larger D:/ drive meant for storage. A lot of anaconda's largest files seem to be saved to C:/Users/[User], which is still on my C drive. And taking up space that I don't really have to spare. Is there a way to tell Anaconda during installation (or initial run, possibly, it looks like) that it should save those files somewhere else? One of the environment variables, maybe? If not I guess I'm open to suggestions for other Python IDEs that are smaller or can be put entirely on a secondary drive.
type: AnsweredQuestion

error-handling
tags question: http://stackoverflow.com/q/52059137
tags question: http://stackoverflow.com/q/51970506
tag name: error-handling
tags question: http://stackoverflow.com/q/52046654
tags question: http://stackoverflow.com/q/51981608
tags question: http://stackoverflow.com/q/52057446
tags question: http://stackoverflow.com/q/51976394
tags question: http://stackoverflow.com/q/51959370
tags question: http://stackoverflow.com/q/51959635
tags question: http://stackoverflow.com/q/51958145
type: Tag

http://stackoverflow.com/q/52108056
type: AnsweredQuestion
score: 3
downvote count: 0
has answer: http://stackoverflow.com/a/52108151
has body: I have an array with dict tag_list = [{'Key': 'backup', 'Value': 'true'}, {'Key': 'backup_daily', 'Value': '7'}] I'd like to convert it to variables, such as: tag_backup = 'true' tag_backup_daily = '7' Any easy way to do that? If no need to convert it to variables, any other better way to reference these key/value directly? The best I want to do is to reference as below ways. tag_list['backup'] = "true" tag_list['backup_daily'] = "7" UPDATE #1 Thanks to @Lev Zakharov 's answer, I did with below ways. &gt;&gt;&gt; new_list = {x['Key']: x['Value'] for x in tag_list} &gt;&gt;&gt; new_list['backup'] 'true' &gt;&gt;&gt; new_list['backup_daily'] '7'
type: Question
has answer: http://stackoverflow.com/a/52108081
has answer: http://stackoverflow.com/a/52108118
accepted answer: http://stackoverflow.com/a/52108081
possible better answer: http://stackoverflow.com/a/52108118
upvote count: 3
answer count: 3
has title: convert array with dict to variables
favorite count: 0
tagged with: python

http://stackoverflow.com/comment/91153813
comment on: http://stackoverflow.com/a/52084933
score: 0
type: AnswerComment
has text: @Andersson Please forgive my ignorance about that, I'm a student who is trying to give answers which my efforts in them. I should not have bring up things I do not know though.
type: Comment

http://stackoverflow.com/a/52012628
downvote count: 0
answers question: http://stackoverflow.com/q/52012564
has body: I'd take a look in the references I posted in the comments for more detailed information on % and .format(). For the lazy evaluation question, the answer is no. A simple test will do def func1(x): time.sleep(5) return(x) def func2(x): #time.sleep(5) return(x) %timeit 'debug1: %s' % func1(3) 5 s ± 1.31 ms per loop (mean ± std. dev. of 7 runs, 1 loop each) %timeit 'debug2: {}'.format(func1(3)) 5 s ± 1.45 ms per loop (mean ± std. dev. of 7 runs, 1 loop each) %timeit 'debug1: %s' % func2(3) 297 ns ± 11.2 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each) %timeit 'debug2: {}'.format(func2(3)) 404 ns ± 4.56 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each) In both .format (obviously) and % approaches,func() is calculated anyway.
type: Answer
upvote count: 5
score: 5

http://stackoverflow.com/q/52025460
linked to: http://stackoverflow.com/q/2164069
type: UnansweredQuestion
tagged with: django
tagged with: python
score: 3
has answer: http://stackoverflow.com/a/76925707
has comment: http://stackoverflow.com/comment/131716064
upvote count: 3
type: Question
has title: how can i make login required for an entire urlconf in django
has body: I have the following code in root url conf path('dashboard/', include('frontend.urls')), so inorder to make a url login protected I have to go to the frontend-&gt;urls.py and add the following code (the login_required decorator) for each of the paths path('lists', login_required(EmailListView.as_view(),login_url='/login'), name="list"), which is quiet tedious, and we might forget as well. So my question is how can I enable login_required protection for a urlconf group? is there any way I can enable it from the root urlconf? like below? path('dashboard/', login_required(include('frontend.urls'))), #something like this? #for now I am not able to access any urls if I do this so that the entire set is protected !!, NB: I read this answer here Best way to make Django&#39;s login_required the default, still, this requires specification of urls in some other place, Django 2.1, Python 3.6
has comment: http://stackoverflow.com/comment/91031399
downvote count: 0
answer count: 1
favorite count: 0

pygobject
type: Tag
tags question: http://stackoverflow.com/q/51974845
tags question: http://stackoverflow.com/q/51975256
tag name: pygobject

http://stackoverflow.com/comment/90925330
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51982417
has text: @max9111, That's *very* interesting; goes beyond, in fact, my precise question. I assume `numba` will only work with numeric inputs, which is fine for my use case. If there's a temporary mask array, I'd imagine `mask` / `where` can *never* outperform `np.where`.
score: 0

http://stackoverflow.com/q/52003889
tagged with: pydot
type: Question
has title: Error when try to install pydot in Python
linked to: http://stackoverflow.com/q/26349314
has body: today is my first day in learning ML i am using Anaconda I want to use pydot to visualize data i tried this to install pydot pip install pydot but got this error Collecting pydot Downloading https://files.pythonhosted.org/packages/c3/f1/e61d6dfe6c1768ed2529761a68f70939e2569da043e9f15a8d84bf56cadf/pydot-1.2.4.tar.gz (132kB) 100% |████████████████████████████████| 133kB 2.6MB/s Requirement already satisfied: pyparsing&gt;=2.1.4 in c:\program files (x86)\microsoft visual studio\shared\anaconda3_64\lib\site-packages (from pydot) Building wheels for collected packages: pydot Running setup.py bdist_wheel for pydot ... done Stored in directory: C:\Users\ASMGX\AppData\Local\pip\Cache\wheels\6a\a5\14\25541ebcdeaf97a37b6d05c7ff15f5bd20f5e91b99d313e5b4 Successfully built pydot Installing collected packages: pydot Exception: Traceback (most recent call last): File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Anaconda3_64\lib\site-packages\pip\basecommand.py", line 215, in main status = self.run(options, args) File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Anaconda3_64\lib\site-packages\pip\commands\install.py", line 342, in run prefix=options.prefix_path, File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Anaconda3_64\lib\site-packages\pip\req\req_set.py", line 784, in install **kwargs File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Anaconda3_64\lib\site-packages\pip\req\req_install.py", line 851, in install self.move_wheel_files(self.source_dir, root=root, prefix=prefix) File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Anaconda3_64\lib\site-packages\pip\req\req_install.py", line 1064, in move_wheel_files isolated=self.isolated, File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Anaconda3_64\lib\site-packages\pip\wheel.py", line 345, in move_wheel_files clobber(source, lib_dir, True) File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Anaconda3_64\lib\site-packages\pip\wheel.py", line 323, in clobber shutil…
answer count: 1
accepted answer: http://stackoverflow.com/a/52004006
score: 0
has answer: http://stackoverflow.com/a/52004006
tagged with: python
has comment: http://stackoverflow.com/comment/90957314
type: AnsweredQuestion
tagged with: anaconda

http://stackoverflow.com/comment/90981713
score: 0
comment on: http://stackoverflow.com/a/52015032
type: AnswerComment
has text: @user10272359 *args allows you to pass a variable number of arguments to a function, So in your case, you can pass more than one parameters to the function. Read this link: https://pythontips.com/2013/08/04/args-and-kwargs-in-python-explained/. If it worked, please accept the answer :)
type: Comment

matplotlib
tags question: http://stackoverflow.com/q/51977217
tags question: http://stackoverflow.com/q/51991048
tags question: http://stackoverflow.com/q/52004460
tags question: http://stackoverflow.com/q/52067833
tags question: http://stackoverflow.com/q/51986528
tags question: http://stackoverflow.com/q/52106307
tags question: http://stackoverflow.com/q/51977053
tags question: http://stackoverflow.com/q/51975737
tags question: http://stackoverflow.com/q/52111775
tags question: http://stackoverflow.com/q/52009997
tags question: http://stackoverflow.com/q/51991204
tags question: http://stackoverflow.com/q/52035956
tags question: http://stackoverflow.com/q/52073276
tags question: http://stackoverflow.com/q/52103226
tags question: http://stackoverflow.com/q/52027297
tags question: http://stackoverflow.com/q/51958743
tags question: http://stackoverflow.com/q/51998504
tags question: http://stackoverflow.com/q/52059233
tags question: http://stackoverflow.com/q/52045121
tags question: http://stackoverflow.com/q/52010069
tags question: http://stackoverflow.com/q/52020347
tags question: http://stackoverflow.com/q/52102562
tags question: http://stackoverflow.com/q/52108558
tags question: http://stackoverflow.com/q/51991592
tags question: http://stackoverflow.com/q/52049438
tags question: http://stackoverflow.com/q/51980366
tags question: http://stackoverflow.com/q/52095337
tags question: http://stackoverflow.com/q/51959066
tags question: http://stackoverflow.com/q/52014678
tags question: http://stackoverflow.com/q/52018374
tag name: matplotlib
tags question: http://stackoverflow.com/q/52055673
tags question: http://stackoverflow.com/q/52067792
tags question: http://stackoverflow.com/q/51984299
tags question: http://stackoverflow.com/q/51976729
tags question: http://stackoverflow.com/q/52102105
tags question: http://stackoverflow.com/q/52067785
tags question: http://stackoverflow.com/q/51964256
tags question: http://stackoverflow.com/q/51958177
tags question: http://stackoverflow.com/q/51999396
tags question: http://stackoverflow.com/q/52097967
tags question: http://stackoverflow.com/q/52096050
tags question: http://stackoverflow.com/q/52058695
tags question: http://stackoverflow.com/q/52098537
tags question: http://stackoverflow.com/q/52093610
tags question: http://stackoverflow.com/q/52036184
tags question: http://stackoverflow.com/q/52043711
tags question: http://stackoverflow.com/q/52092090
tags question: http://stackoverflow.com/q/51974601
tags question: http://stackoverflow.com/q/52107106
tags question: http://stackoverflow.com/q/52088018
tags question: http://stackoverflow.com/q/52111413
tags question: http://stackoverflow.com/q/52037738
tags question: http://stackoverflow.com/q/52020474
tags question: http://stackoverflow.com/q/52072770
tags question: http://stackoverflow.com/q/52003107
tags question: http://stackoverflow.com/q/52061097
tags question: http://stackoverflow.com/q/52082814
tags question: http://stackoverflow.com/q/52082351
tags question: http://stackoverflow.com/q/52079185
tags question: http://stackoverflow.com/q/52067700
tags question: http://stackoverflow.com/q/52066886
tags question: http://stackoverflow.com/q/51985921
tags question: http://stackoverflow.com/q/52015845
tags question: http://stackoverflow.com/q/52073564
tags question: http://stackoverflow.com/q/52060625
tags question: http://stackoverflow.com/q/52004433
tags question: http://stackoverflow.com/q/52066863
tags question: http://stackoverflow.com/q/52046524
tags question: http://stackoverflow.com/q/52059849
tags question: http://stackoverflow.com/q/52061699
tags question: http://stackoverflow.com/q/52015794
tags question: http://stackoverflow.com/q/52019883
tags question: http://stackoverflow.com/q/52035184
tags question: http://stackoverflow.com/q/52083431
tags question: http://stackoverflow.com/q/52004075
tags question: http://stackoverflow.com/q/51967278
tags question: http://stackoverflow.com/q/52083373
tags question: http://stackoverflow.com/q/52100747
tags question: http://stackoverflow.com/q/51991474

http://stackoverflow.com/q/52024847
tagged with: numpy-ndarray
has title: How to index several 2d numpy arrays with different number of rows in a 3d array?
score: 0
tagged with: multidimensional-array
has comment: http://stackoverflow.com/comment/91002255
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91001486
tagged with: python
has comment: http://stackoverflow.com/comment/91002013
tagged with: indexing
has comment: http://stackoverflow.com/comment/91000175
answer count: 0
has body: I have the following problem in python: I have several numpy 2d-arrays where all have same number of columns ,but different number of rows.I want to index all these 2d-array in a unique numpy 3d-array where the first index keeps into account each 2d-array. For example : let's suppose I got two 2d-arrays like this : [[1,2,3][4,5,6][7,8,9]] (3X3 array) [[11,12,13][14,15,16]] (2X3 array) I want to get a numpy 3d-array name,for example, c where : c[0] has shape (3,3), c[1] (2,3) and so on...So I expect a 3d-array whose shape is (number of 2d matrices,number of rows of one matrix,number of columns of one matrix) How can I reshape since each 2d-arrays have different number of rows each other? Thanks
has comment: http://stackoverflow.com/comment/91000991
type: Question

http://stackoverflow.com/comment/91056472
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52052293
has text: `(https:\/\/smtgvs\.weathernews\.jp\/s\/topics\/img\/\d+\/\w+\.(jpg|png))` will do it. check it in regex101.com, take yhe full match.

http://stackoverflow.com/a/56488435
downvote count: 0
upvote count: 2
type: Answer
score: 2
has body: This might solve your problem as it always helps me with new packages. Update the numpy package and others required. (version) Install visual studio c++ modules. (recommended) Try installing from the source package (which you can learn online) rather than downloading and installing using pip or pip3. Read the documentation of the package again.
answers question: http://stackoverflow.com/q/52005509

http://stackoverflow.com/comment/91072377
type: QuestionComment
has text: It was the link of the duplicate answer which @ImportanceOfBeingErnst shared now.
comment on: http://stackoverflow.com/q/52060625
score: 0
type: Comment

http://stackoverflow.com/q/52106643
type: Question
score: 0
tagged with: pandas
answer count: 1
has body: I have a file with about 25 sheets and each sheet contains 5-30 columns with system names as headers. I want to iterate through a list of about 170 systems (the list is on one of the sheets in the main file) and with each system search each tab for columns with the matching system as the header. I have the code below and it works great for the first iteration, but for some reason after it loops through all the sheets and moves on to the second system it pulls the sheet name rather than the second system name. Anyone see what i'm doing wrong? import pandas as pd matrix = pd.ExcelFile('file') names_tab = pd.read_excel(matrix, sheet_name='Name_Test') sheets_list = {} for (y, sysRows) in names_tab.iterrows(): print(sysRows['header']) for sheets in matrix.sheet_names[1:]: sheets_list['{}'.format(sheets)] = pd.read_excel(matrix, sheet_name='{}'.format(sheets), skiprows=2) print(sheets) for column in sheets_list[sheets]: if column == sysRows['header']: for idx, row in sheets_list[sheets][column].iteritems(): if sheets_list[sheets].iloc[idx][column] == 'x': print('{} has X in row {} column {} on sheet {}' .format(sysRows['header'], idx, column, sheets)) elif sheets_list[sheets].iloc[idx][column] == 'X': print('{} has X in row {} column {} on sheet {}' .format(sysRows['header'], idx, column, sheets)) print(column + ' works') else: print(column + ' doesnt work')
type: UnansweredQuestion
tagged with: python
has title: nested iterations in Pandas
has answer: http://stackoverflow.com/a/52108024

http://stackoverflow.com/q/52092953
downvote count: 0
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/117198988
has answer: http://stackoverflow.com/a/64139897
linked to: http://stackoverflow.com/q/16740385
type: Question
has answer: http://stackoverflow.com/a/55544698
has title: Redirection is not supported
score: 4
has comment: http://stackoverflow.com/comment/91137040
upvote count: 4
answer count: 2
has body: I want to program the game Snake, but when I test, the code shows this message: Redirection is not supported. I saw it on YouTube and it went straight to him. I googled it but that did not help me any further. import random import curses s = curses.initscr() curses.curs_set(0) sh, sw = s.getmaxyx() w = curses.newwin(sh, sw, 0, 0) w.keypad(1) w.timeout(100) snk_x = sw/4 snk_y = sh/2 snake = [ [snk_y, snk_x], [snk_y, snk_x-1], [snk_y, snk_x-2] ] food = [sh / 2, sw / 2] w.addch(food[0], food[1], curses.ACS_PI) key = curses.KEY_RIGHT while True: next: key = w.getch() key = key if next_key == -1 else next_key if snake[0][0] in [0, sh] or snake[0][1] in [0, sw] or snake[0] in snake[1:]: curses.endwin() quit() new: head = [snake[0][0], snake[0][1]] if key == curses.KEY_DOWN: new_head[0] += 1 if key == curses.KEY_UP: new_head[0] -= 1 if key == curses.KEY_LEFT: new_head[1] -= 1 if key == curses.KEY_RIGHT: new_head[1] += 1 snake.insert(0, new_head) if snake[0] == food: food = None while food is None: nf = [ random.randint(1, sh - 1), random.randint(1, sh - 1) ] food = nf if nf not in snake else None w.addch(food[0], food[1], curses.ACS, PI) else: tail = snake.pop() w.addch(tail[0], tail[1], ' ') w.addch(snake[0][0], snake[0][1], curses.ACS, CKBOARD)

http://stackoverflow.com/a/51968392
type: AcceptedAnswer
type: Answer
upvote count: 4
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51968293
answers question: http://stackoverflow.com/q/51968293
has body: On training, Keras expects your data to include a dimension for the batch size. In your case, this means the data should be of shape (batch_size, 130517). However, you are passing a np array of shape (130517), which is causing your error. You can reshape your data to include a batch shape as follows: X_reshaped = X[0].reshape(1, -1)
score: 4
has comment: http://stackoverflow.com/comment/90887301

http://stackoverflow.com/a/52623034
score: 2
downvote count: 0
has body: Have you tried comparing the two with some tolerance? I believe the two MFCCs are arrays of floating point numbers, and testing for exact equality might not be wise. Try using numpy.testing.assert_allclose with some tolerance, and decide if the tolerance is good enough. Nevertheless, I missed you saying that even the shapes mismatch, and I am not experienced with bob.ap to comment on that confidently. However, there's often the case that some libraries pad the input with zeros either in the beginning or the end of the input array for windowing reasons, and that may be responsible if one of these is doing it differently.
has comment: http://stackoverflow.com/comment/92179893
upvote count: 2
answers question: http://stackoverflow.com/q/52112204
type: Answer

http://stackoverflow.com/a/51961782
score: 2
type: AcceptedAnswer
downvote count: 0
type: Answer
upvote count: 2
has comment: http://stackoverflow.com/comment/90873874
has body: I think need extract first value and then compare with str.contains or by str.endswith: first = df['Col 1'].iloc[0].split('-')[1] #if want check first today day #first = pd.datetime.now().strftime('%a') print (first) Mon df = df[~df['Col 1'].str.contains(first)] #Jon Clements suggestion, thank you df = df[~df['Col 1'].str.endswith(first)] print (df) Col 1 Col 2 2 val3-Tues A 3 val4-Tues B
answers question: http://stackoverflow.com/q/51961650
has comment: http://stackoverflow.com/comment/90873885
accepted answer of: http://stackoverflow.com/q/51961650

http://stackoverflow.com/q/52027033
score: 5
has title: Convert datetime to another format without changing dtype
upvote count: 5
tagged with: pandas
answer count: 1
downvote count: 0
favorite count: 0
tagged with: series
tagged with: python-3.x
has answer: http://stackoverflow.com/a/52027599
tagged with: datetime
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/52027599
type: Question
has body: I'm just learning Pandas myself and I have met few problems. In a DataFrame, which it was reads from a csv file, I have one column includes date data that in different format(like '%m/%d/%Y' and '%Y-%m-%d', may be blank.) and I want to unify the format of this column. But I don't know if there are any other formats. So when I using pd.to_datetime(),it raised some errors like format not matching and not timelike data. How can I unify the format of this column? I have converted part of that column into datetime dtype, and it's in YYYY-mm-dd format. Can I keep the datetime dtype, and change the format into '%m/%d/%Y'? I have used pd.dt.strftime(), it will change the format, but also change the dtype into str, not keeping the datetime dtype.

http://stackoverflow.com/q/52000530
answer count: 1
tagged with: appkit
type: UnansweredQuestion
has title: AppKit not dynamically sensing the frontmost app
tagged with: python
has body: I'm using Appkit in Python to have the computer sense the frontmost app. It will correctly sense the frontmost app at first but when I change the frontmost app and leave the terminal running, it will not update the new information. For example, the following code will work: from AppKit import NSWorkspace active_app_name = NSWorkspace.sharedWorkspace().frontmostApplication().localizedName() But now suppose I make Chrome rather than Excel the frontmost app and run the following program on terminal. Then after the terminal prints 'Chrome', I click on the app 'Excel', the terminal will continue to print 'Chrome' and it will never sense that Excel is the frontmost app. from AppKit import NSWorkspace while True: active_app_name = NSWorkspace.sharedWorkspace().frontmostApplication().localizedName() print (active_app_name) if active_app_name == 'Microsoft Excel': pass # do stuff else: time.sleep(5) I want AppKit to be able to sense the new frontmost app when I make changes to which the frontmost app is.
type: Question
has answer: http://stackoverflow.com/a/52042266
score: 0

http://stackoverflow.com/q/52053868
has title: Pandas OHLCV to JSON format
type: Question
score: 1
tagged with: http://stackoverflow.com/tag/json
has answer: http://stackoverflow.com/a/52053922
tagged with: pandas
has body: I have real time data that I resample with pandas in order to get OHLCV data: ohlcv = df.resample(_period).agg({'bid': 'ohlc', 'volume': 'sum'}) The dataframe looks like this: volume bid volume open high low close timestamp 2016-09-01 300.0 77.644997 78.320331 77.638 78.320331 and the JSON output using ohlcv.to_json(orient='index') is: {"1472688000000":{"["volume","volume"]":300.0,"["bid","open"]":77.644997,"["bid","high"]":78.320331,"["bid","low"]":77.638,"["bid","close"]":78.320331}} How can I convert the dataframe in the following JSON: { "timestamp":1472688000000, "open":77.644997, "high":78.320331, "close":78.320331, "low":77.638, "volume":300 }
answer count: 1
downvote count: 0
favorite count: 0
accepted answer: http://stackoverflow.com/a/52053922
tagged with: resampling
tagged with: python
type: AnsweredQuestion
upvote count: 1

http://stackoverflow.com/comment/90929028
score: 0
comment on: http://stackoverflow.com/q/51978463
type: Comment
type: QuestionComment
has text: i do need the fingerprint for a specific protocol such as SSH. as my current key is a RSA key and the example given here https://stackoverflow.com/questions/6682815/deriving-an-ssh-fingerprint-from-a-public-key-in-python uses the SSH key. Is there a way to convert the RSA key to Open SSH in python

http://stackoverflow.com/comment/91010643
has text: @E235 If you use a `multiprocessing.Pool`, the worker processes are re-used rather than restarted for each calculation. And how "leightweight" creating a new process is depends very much on the operating system. For systems that use `fork()` to create new processes and use copy-on-write memory management, creating a new process is not all that expensive.
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52028649

http://stackoverflow.com/q/51978077
answer count: 1
has body: i got some scroll-available screen example. and i am testing this example to apply to my application. and when i launch this python file, i can get this screen like below but what i want is like this above. I want to make as many buttons as numberoflist And put three lines of TESTTEST.txt in one button as shown above. 6, 2, 159, 6, 6, 467 each number is list of Businfo so i can access each number as a businfolist[0], businfolist[1], businfolist[2] and so on.. so first, i coded like this for the test. BoxLayout: orientation: 'vertical' size_hint: 1, 0.35 padding: 0 on_parent: for i in range(root.numberoflist): txt = root.businfolist[i]; self.add_widget(Button(text= txt, id=txt)) but it didn't work. Here is Traceback Traceback (most recent call last): File "t2.py", line 65, in &lt;module&gt; presentation = Builder.load_file("t2.kv") File "/usr/local/lib/python2.7/dist-packages/kivy/lang/builder.py", line 301, in load_file return self.load_string(data, **kwargs) File "/usr/local/lib/python2.7/dist-packages/kivy/lang/builder.py", line 368, in load_string parser = Parser(content=string, filename=fn) File "/usr/local/lib/python2.7/dist-packages/kivy/lang/parser.py", line 392, in __init__ self.parse(content) File "/usr/local/lib/python2.7/dist-packages/kivy/lang/parser.py", line 501, in parse objects, remaining_lines = self.parse_level(0, lines) File "/usr/local/lib/python2.7/dist-packages/kivy/lang/parser.py", line 605, in parse_level level + 1, lines[i:], spaces) File "/usr/local/lib/python2.7/dist-packages/kivy/lang/parser.py", line 605, in parse_level level + 1, lines[i:], spaces) File "/usr/local/lib/python2.7/dist-packages/kivy/lang/parser.py", line 615, in parse_level 'Invalid property name') kivy.lang.parser.ParserException: Parser: File "/root/Desktop/hi/t2.kv", line 54: ... 52: padding: 0 53: on_parent: &gt;&gt; 54: for i in range(root.lenbil): txt = root.businfolist[i]; self.add_widget(Button(text= txt, id=txt)) 55: 56:&lt;MyButton@Button&gt;: ... Invalid proper…
tagged with: kivy
tagged with: kivy-language
tagged with: python
has answer: http://stackoverflow.com/a/51989063
accepted answer: http://stackoverflow.com/a/51989063
type: AnsweredQuestion
type: Question
has title: Kivy : Apply function variables to Button Text
score: 0

http://stackoverflow.com/comment/91134661
comment on: http://stackoverflow.com/q/52089618
type: Comment
type: QuestionComment
has text: Does adding ```From: ``` and ```To: ``` to the email text change anything? Like [this](https://stackabuse.com/how-to-send-emails-with-gmail-using-python/) tutorial shows
score: 0

http://stackoverflow.com/comment/91159670
comment on: http://stackoverflow.com/a/52099937
score: 0
type: AnswerComment
type: Comment
has text: @venky513 exactly. same for octal, e.g. ``var = 0o45``. All of them will be handled as integer. It's just the representation during the assignment that differs.

http://stackoverflow.com/comment/91051006
has text: We can't tell you without knowing what is a "symbol" in context
score: 0
comment on: http://stackoverflow.com/q/52050191
type: Comment
type: QuestionComment

http://stackoverflow.com/a/52049670
type: Answer
has body: Use regexp_replace: df.withColumn("sDate", regexp_replace($"sDate", "([0-9]{4})/([0-9]{2})/([0-9]{2})", "$2/$3/$1")) The regular expression will match the year, month and day in three capture groups. The rearranged date will then be used to replace the old one. Since the regex will only match string with the format that is to be replaced, nothing will happen to the other rows.
answers question: http://stackoverflow.com/q/52049512
score: 2
upvote count: 2
accepted answer of: http://stackoverflow.com/q/52049512
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/95276655
has text: This answer points to very useful information, but I would not call it an answer.
type: AnswerComment
comment on: http://stackoverflow.com/a/52043159
type: Comment
score: 2

http://stackoverflow.com/comment/136496495
comment on: http://stackoverflow.com/a/67112402
type: AnswerComment
has text: @ZecongHu You're right. At least in the minimal example, `sys.last_value` is available. I think my specific situation was more complicated and I oversimplified it when attempting to distill a reproducer. I suspect that "fixtures" were in play that affected the exception state. I should have linked to the project I was attempting to debug, because at this point, I don't recall how I encountered the issue, but IIRC, neither `sys.last_value` nor `sys.exc_info()` had the necessary context. I'll continue to investigate in the pytest bug.
type: Comment
score: 1

http://stackoverflow.com/q/51987856
answer count: 1
score: 0
has answer: http://stackoverflow.com/a/51988365
tagged with: sqlalchemy
accepted answer: http://stackoverflow.com/a/51988365
tagged with: marshmallow
type: AnsweredQuestion
has body: I have the sqlalchemy model with jsonb field and marshmallow schema for this model: class Settings(db.Model): id = db.Column(UUID, primary_key=True, server_default=text("uuid_generate_v4()")) settings = db.Column(JSONB) class SettingsSchema(ma.ModelSchema): class Meta: model = Settings I'm serializing it in json like: settings = Settings(settings={'qwerty': 'test'}) settings_schema = SettingsSchema(many=False, exclude=('id', )) body = settings_schema.dump(settings).data and json view of the model looks like this: { "settings": { "qwerty": "test" } } When I'm using this schema as nested I have result like { "id": 123456, "some_field": "some_field_value", "other_field": "other_field_value", "settings": { "settings": { "qwerty": "test" } } } and this "settings.settings" looks ugly. Is there a way said to marshmallow that I need only value as dump result, I mean { "qwerty": "test" } Probably I need to do something with metaclasses, but I have no idea what should I do.
type: Question
has title: Marshmallow result customization
tagged with: python
tagged with: psycopg2

http://stackoverflow.com/comment/90970825
has text: Could you include the rest of your attempted code?
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/52010016
type: Comment

http://stackoverflow.com/comment/91003404
score: 0
type: AnswerComment
has text: Is your y_pred the prediction from GaussianNB? If yes then it should give you a list of class labels, whose number is the same as the input number of classes. For multi-label you can run that on each column, but the prediction for each class should be binary. If you could provide a complete training code and reproduce the problem, that would be more helpful for other people to understand your problem.
type: Comment
comment on: http://stackoverflow.com/a/52022682

http://stackoverflow.com/comment/91047715
type: Comment
comment on: http://stackoverflow.com/a/52048187
type: AnswerComment
has text: @HarisKhaliq you should play with the part where it prints the list to achieve that. I'm sure that JSON is as clean as it can get for the data itself.
score: 0

http://stackoverflow.com/comment/91017917
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/52031838
has text: I kept angularApp.config(["$httpProvider", function($httpProvider) { $httpProvider.defaults.xsrfCookieName = 'csrftoken'; $httpProvider.defaults.xsrfHeaderName = 'X-CSRFToken'; }]); in beginning of charkilla.js. But the form disappear.
score: 0

http://stackoverflow.com/q/52039703
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52039926
has body: I have a column which contains numbers and strings. E.g: Result: Failed 8.05 9 7 How can I change the data to show two decimals i.e. as following? Result: Failed 8.05 9.00 7.00 I am trying the following but it doesn't work. Thanks for your help! df['Result'] = df['Result'].apply('{:.2f}'.format)
accepted answer: http://stackoverflow.com/a/52039926
downvote count: 0
tagged with: apply
type: Question
upvote count: 2
tagged with: decimal
answer count: 2
possible better answer: http://stackoverflow.com/a/52039753
tagged with: series
tagged with: pandas
favorite count: 0
tagged with: python
has answer: http://stackoverflow.com/a/52039753
has title: pandas apply decimal in column with numbers and strings
score: 2

http://stackoverflow.com/q/52030713
type: Question
upvote count: 2
has body: I have a dataframe and I'd like to groupby a field and then select only values which is not zero as my aggregate function and then convert them into a list. Here is the code I have df.sort_values(by='col1').groupby('col2').apply(lambda x: x if x!=0).apply(list) However if says invalid syntax. What am I doing wrong?
tagged with: pandas-groupby
tagged with: pandas
answer count: 1
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/52030733
accepted answer: http://stackoverflow.com/a/52030733
tagged with: python
has title: How to filter values after groupby in pandas
type: AnsweredQuestion
score: 2

http://stackoverflow.com/a/52097106
downvote count: 0
answers question: http://stackoverflow.com/q/52097083
has body: you should not name your function input() since it is an internal function already! your function should be called my_user_input() or something similar. By calling your own function input(), you shadow and therefore "overwrite" the existing, BuiltIn-input()-function. This way, you won't be able to access it's functionality any more inside the script.
has comment: http://stackoverflow.com/comment/91144505
type: Answer
has comment: http://stackoverflow.com/comment/91144586
has comment: http://stackoverflow.com/comment/91144760
has comment: http://stackoverflow.com/comment/91157833
has comment: http://stackoverflow.com/comment/91171535
has comment: http://stackoverflow.com/comment/91144714
score: 4
upvote count: 4
accepted answer of: http://stackoverflow.com/q/52097083
type: AcceptedAnswer

http://stackoverflow.com/a/52079440
answers question: http://stackoverflow.com/q/52074398
type: Answer
has body: You can trigger your bot any way you like, e.g. via cron job. However, there are a couple things to consider. First, your bot needs to run from the same virtual environment as your Django project. Second, your Django project root must be available in sys.path. Something like this: import os import sys import django sys.path.append('/path/to/your/django-project-root') os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'your_project.settings') django.setup() # Do your stuff, e.g: from my_app.models import MyModel value1, value2 = get_data_from_somewhere() MyModel.objects.create(param1=value1, param2=value2) After running django.setup() you can execute any code in the context of your Django project, including saving your data via models API as shown in the example above.
score: 0

http://stackoverflow.com/q/52001997
has comment: http://stackoverflow.com/comment/97220272
tagged with: tensorflow
has comment: http://stackoverflow.com/comment/97214721
type: Question
upvote count: 5
has comment: http://stackoverflow.com/comment/97033842
tagged with: encoding
has comment: http://stackoverflow.com/comment/97038854
downvote count: 0
has body: Let's say I have the following pandas dataframe: | col1 | col2 | col3 | --------------------------------- 0 | 5 | 4 | [0,2,4] | 1 | 3 | 8 | [7,3] | 2 | 2 | 1 | [7,3,6,9] | in 'col3' I have lists with different sizes which I also want to import into my Tensorflow Estimator. These lists also must be k-hot encoded, I am not sure if this is how people call it: [1,4,6] ---&gt; [0, 1, 0, 0, 1, 0, 1] The problem comes because the maximum number in col3 is 600_000 so my k-hot encoded vector will have size of 600_000 thus I cannot encode my entire dataframe (due to MemoryError) and pass col3 to Tensorflow as tf.feature_column.numeric_column('col3', 600_000) Do you have any ideas how can I feed this column in my DNNRegressor ? To share some code, this is how I normally do it for 'standard' columns: # reading the columns from the pandas_input_fn col1 = tf.feature_column.numeric_column('col1', default_value=0.0) col2 = tf.feature_column.numeric_column('col2', default_value=0.0) # converting them to categorical col1_b = tf.feature_column.bucketized_column(col1, [0,5,10,20]) col1_2 = tf.feature_column.bucketized_column(col2, [0,4,8,16]) # make crosses cross = tf.feature_column.crossed_colum([col1_b, col2_b], 4*4) # define what will go in my estimator features = [ tf.feature_column.embedding_column(cross, 10) tf.feature_column.indicator_column(col1_b) tf.feature_column.indicator_cilumn(col2_b) ] # and finally estimator = tf.estimator.DNNRegressor( model_dir=model_dir, feature_columns=features, hidden_units=[512,256,256,128,32])
favorite count: 0
type: UnansweredQuestion
score: 5
has comment: http://stackoverflow.com/comment/97079196
has title: k-hot encoded feature Tensorflow Estimator
has comment: http://stackoverflow.com/comment/97259501
tagged with: python
has comment: http://stackoverflow.com/comment/97089423
answer count: 0

http://stackoverflow.com/comment/91117972
comment on: http://stackoverflow.com/q/52083431
score: 0
has text: `line.split(" ")` What do you think this is doing? `split` will return a list. fetch your data based on the index. That would be the easiest way to deal with this.
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51963671
has body: I have this program: funcs = { idx: lambda: print(idx) for idx in range(5) } In essence, we have a dictionary of indices and functions: {0: &lt;function __main__.&lt;dictcomp&gt;.&lt;lambda&gt;()&gt;, 1: &lt;function __main__.&lt;dictcomp&gt;.&lt;lambda&gt;()&gt;, 2: &lt;function __main__.&lt;dictcomp&gt;.&lt;lambda&gt;()&gt;, 3: &lt;function __main__.&lt;dictcomp&gt;.&lt;lambda&gt;()&gt;, 4: &lt;function __main__.&lt;dictcomp&gt;.&lt;lambda&gt;()&gt;} However, the following function calls have the same result: funcs[4]() 4 funcs[0]() 4 Why do I get 4 as output both times, even though I am using different inputs?
has comment: http://stackoverflow.com/comment/90877743
type: AnsweredQuestion
score: 3
has comment: http://stackoverflow.com/comment/90877901
has comment: http://stackoverflow.com/comment/90878014
type: Question
duplicate of: http://stackoverflow.com/q/3431676
has comment: http://stackoverflow.com/comment/90877713
has comment: http://stackoverflow.com/comment/90877995
has comment: http://stackoverflow.com/comment/90877868
has title: Python variable scope,why does funcs prints same value?
accepted answer: http://stackoverflow.com/a/51963884
linked to: http://stackoverflow.com/q/38369470
downvote count: 1
answer count: 1
linked to: http://stackoverflow.com/q/12423614
favorite count: 0
has comment: http://stackoverflow.com/comment/90877959
has answer: http://stackoverflow.com/a/51963884
has comment: http://stackoverflow.com/comment/90877919
has comment: http://stackoverflow.com/comment/90877710
tagged with: python
upvote count: 4

http://stackoverflow.com/comment/91300573
type: QuestionComment
has text: Could you put together a snippet to reproduce? Does look like something weird going on with while_loop gradients. Is the while_loop in a restored MetaGraph (random guess)?
comment on: http://stackoverflow.com/q/52085617
score: 0
type: Comment

http://stackoverflow.com/a/52044588
has body: Solution found by myself: IIS -> select server -> Default App Pool -> Advanced Settings -> set 0 to "Idle time out" and "regular time interval"
downvote count: 0
has comment: http://stackoverflow.com/comment/108332081
type: Answer
score: 2
answers question: http://stackoverflow.com/q/52025236
upvote count: 2

http://stackoverflow.com/q/52066916
upvote count: 1
type: Question
linked to: http://stackoverflow.com/q/26970422
has title: Pandas can't read excel encoding
score: 1
has answer: http://stackoverflow.com/a/52066957
has answer: http://stackoverflow.com/a/52067227
answer count: 2
has comment: http://stackoverflow.com/comment/91084204
tagged with: encoding
has comment: http://stackoverflow.com/comment/91084332
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/91084317
tagged with: pandas
tagged with: python
has body: I'm trying to import an excel file into Pandas. I'm using df=pd.read_excel(file_path) but it keeps getting me this error: *** No CODEPAGE record, no encoding_override: will use 'ascii' *** No CODEPAGE record, no encoding_override: will use 'ascii' Traceback (most recent call last): File "/Users/santanna_santanna/PycharmProjects/KlooksExplore/FindCos/FindCos_Functions.py", line 5468, in &lt;module&gt; adjust_sheet(y1,y2,y3) File "/Users/santanna_santanna/PycharmProjects/KlooksExplore/FindCos/FindCos_Functions.py", line 5130, in adjust_sheet y1=pd.read_excel(y1) File "/Users/santanna_santanna/anaconda3/lib/python3.6/site-packages/pandas/util/_decorators.py", line 118, in wrapper return func(*args, **kwargs) File "/Users/santanna_santanna/anaconda3/lib/python3.6/site-packages/pandas/io/excel.py", line 230, in read_excel io = ExcelFile(io, engine=engine) File "/Users/santanna_santanna/anaconda3/lib/python3.6/site-packages/pandas/io/excel.py", line 294, in __init__ self.book = xlrd.open_workbook(self._io) File "/Users/santanna_santanna/anaconda3/lib/python3.6/site-packages/xlrd/__init__.py", line 162, in open_workbook ragged_rows=ragged_rows, File "/Users/santanna_santanna/anaconda3/lib/python3.6/site-packages/xlrd/book.py", line 119, in open_workbook_xls bk.get_sheets() File "/Users/santanna_santanna/anaconda3/lib/python3.6/site-packages/xlrd/book.py", line 719, in get_sheets self.get_sheet(sheetno) File "/Users/santanna_santanna/anaconda3/lib/python3.6/site-packages/xlrd/book.py", line 710, in get_sheet sh.read(self) File "/Users/santanna_santanna/anaconda3/lib/python3.6/site-packages/xlrd/sheet.py", line 815, in read strg = unpack_string(data, 6, bk.encoding or bk.derive_encoding(), lenlen=2) File "/Users/santanna_santanna/anaconda3/lib/python3.6/site-packages/xlrd/biffh.py", line 249, in unpack_string return unicode(data[pos:pos+nchars], encoding) File "/Users/santanna_santanna/anaconda3/lib/python3.6/site-packages/xlrd/timemachine.py", line 30, in &lt;lambda&gt; uni…
type: UnansweredQuestion

http://stackoverflow.com/comment/91040342
comment on: http://stackoverflow.com/q/52032189
has text: @T.Woody So it's run without crashing when I wrote just 'bar' instead of the r.text and statuscode. I didn't even write /n for it. I wouldn't think it would be the r.text or the status code, since if the value wasn't right, it wouldn't give me a permission error, but rather a fault in converting a number or text or something, right?
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/a/51998973
has body: Welcome to Stackoverflow! All you have to do is change your URL to https://search.asx.com.au/s/search.html?query=WOW&amp;collection=asx-meta&amp;profile=web, which is formed in the website while you search any term. Because the website uses GET method to pass data to form which accepts arguments by string parameters in URL itself (?query=WOW&amp;collection=asx-meta&amp;profile=web). So the code will be like, import requests url = 'https://search.asx.com.au/s/search.html?query=WOW&amp;collection=asx-meta&amp;profile=web' with open("requests_results.html","wb") as f: f.write(requests.get(url).content) Cheers!
type: Answer
answers question: http://stackoverflow.com/q/51997608
has comment: http://stackoverflow.com/comment/90976494
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/90976503
upvote count: 1

http://stackoverflow.com/comment/90871227
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51960132
type: Comment
has text: @Mithril - Is possible add some sample data, e.g. 10 rows? Because code was writing without testing ;)

http://stackoverflow.com/comment/90965591
type: QuestionComment
comment on: http://stackoverflow.com/q/51991891
score: 0
has text: @PatrickMevzek thanks, I tried something along those lines that I'm not sure is right though (and has led me to the same error as before): `class Tls1HttpAdapter(HTTPAdapter): def init_poolmanager(self, connections, maxsize, block=False): self.poolmanager = PoolManager( num_pools=connections, maxsize=maxsize, block=block, ssl_version=ssl.PROTOCOL_TLSv1)` then I `mount`ed a `requests.Session()` with that `Tls1HttpAdapter()` and tried a `get` on that session, to no avail.
type: Comment

http://stackoverflow.com/comment/91132306
type: Comment
comment on: http://stackoverflow.com/q/52089796
score: 0
has text: Are you sure you are using the same key? (could you print encoded value of the keys used in Java and in Python?) (using the "encodeRules" is very strange IMHO)
type: QuestionComment

http://stackoverflow.com/q/52087206
score: 2
answer count: 1
downvote count: 0
tagged with: matrix
accepted answer: http://stackoverflow.com/a/52087449
has body: My end goal is to train a 4D multivariate gaussian distribution parameterized on the mean and covariance where, and, Currently I have the following code: import tensorflow as tf import numpy as np value = [[1,2.0,3,4,5],[0,2,4,6,8],[80,7,6,5,4]] value=tf.constant(value) cov= tf.slice(value,[0,int(value.shape[1])-1],[int(value.shape[0]),1]) mean= tf.slice(value,[0,0],[int(value.shape[0]),int(value.shape[1])-1]) eyes=tf.eye(int(mean.shape[1]),batch_shape=[int(value.shape[0])]) #eyes = tf.multiply(eyes,cov) normal = tf.contrib.distributions.MultivariateNormalFullCovariance( loc=mean, covariance_matrix=eyes) value = [[1,2.0,3,4,5],[0,2,4,6,8],[80,7,6,5,4]] is an example of what the rest of the code may be receiving. In the example above cov = &lt;tf.Tensor 'Slice_2:0' shape=(3, 1) dtype=float32&gt; eyes = &lt;tf.Tensor 'eye_1/MatrixDiag:0' shape=(3, 4, 4) dtype=float32&gt; cov = [[5.] [8.] [4.]]` eyes = [[[1. 0. 0. 0.] [0. 1. 0. 0.] [0. 0. 1. 0.] [0. 0. 0. 1.]] [[1. 0. 0. 0.] [0. 1. 0. 0.] [0. 0. 1. 0.] [0. 0. 0. 1.]] [[1. 0. 0. 0.] [0. 1. 0. 0.] [0. 0. 1. 0.] [0. 0. 0. 1.]]]` My question is, How can I obtain result given cov and eyes? where result is as follows: result = [[[5., 0., 0., 0.], [0., 5., 0., 0.], [0., 0., 5., 0.], [0., 0., 0., 5.]], [[8., 0., 0., 0.], [0., 8., 0., 0.], [0., 0., 8., 0.], [0., 0., 0., 8.]], [[4., 0., 0., 0.], [0., 4., 0., 0.], [0., 0., 4., 0.], [0., 0., 0., 4.]]] Thanks, in advance.
has title: Multiply a set of constants (1D array) with a set of matrixes (3D array) in Tensorflow
favorite count: 0
upvote count: 2
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52087449
tagged with: tensorflow
tagged with: matrix-multiplication
type: Question

http://stackoverflow.com/a/51995408
has body: You can use pd.Series methods gt (greater than) and sum: df[column].pct_change().fillna(0).gt(0).sum() In general, this is a better idea than using built-in functions with Pandas series / NumPy arrays.
score: 5
upvote count: 5
answers question: http://stackoverflow.com/q/51995287
type: Answer
downvote count: 0

http://stackoverflow.com/a/52081591
score: 1
upvote count: 1
has body: You can also use numpy for this: first_valid = (~np.isnan(df.values)).argmax(1) Then use indexing: df.assign(valid=df.values[range(len(first_valid)), first_valid]) a b c d e valid 0 2.0 NaN NaN NaN 12.0 2.0 1 NaN 5.0 55.0 NaN NaN 5.0 2 NaN NaN 13.0 NaN NaN 13.0 3 NaN NaN 14.0 4.0 22.0 14.0
type: Answer
answers question: http://stackoverflow.com/q/52080799
downvote count: 0

http://stackoverflow.com/comment/90908882
type: QuestionComment
has text: Just all commas in the file/row, or all delimiting commas? (Some could be quoted.)
score: 0
type: Comment
comment on: http://stackoverflow.com/q/51979368

http://stackoverflow.com/q/52100572
has comment: http://stackoverflow.com/comment/91153027
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/52100918
has comment: http://stackoverflow.com/comment/91152038
type: Question
has comment: http://stackoverflow.com/comment/91151900
has body: As a Just startup learner and student i'm working on the some basics and got into pandas read_html function, while searching through web I tried to get the data from html source via a url with below code. import pandas as pd df = pd.read_html('http://prodserverlist/pod.html', header=0, flavor='bs4') df1 = df[0] I would like to know what what exactly df[0] in df1 = df[0].
answer count: 1
has comment: http://stackoverflow.com/comment/91152514
has comment: http://stackoverflow.com/comment/91152006
has comment: http://stackoverflow.com/comment/91152679
score: 0
tagged with: pandas
has comment: http://stackoverflow.com/comment/91151922
has comment: http://stackoverflow.com/comment/91152167
has comment: http://stackoverflow.com/comment/91152108
has comment: http://stackoverflow.com/comment/91152107
has comment: http://stackoverflow.com/comment/129967484
has title: What is df[0] in Pandas DataFrame
has answer: http://stackoverflow.com/a/52100918

http://stackoverflow.com/comment/91659281
has text: Didn't my answer resolve your issue?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52058944

http://stackoverflow.com/comment/91101854
comment on: http://stackoverflow.com/q/52076109
type: QuestionComment
type: Comment
has text: Interesting question. However, it might fit better on codereview.
score: 0

http://stackoverflow.com/q/52050605
has comment: http://stackoverflow.com/comment/91051456
has body: Models.py class Restaurant(models.Model): name=models.CharField(max_length=500) email=models.CharField(max_length=500) web=models.CharField(max_length=500) short_description=models.CharField(max_length=500) description=models.CharField(max_length=500) phone=models.IntegerField(blank=True,null=True,default=0) lat =models.FloatField(blank=True,null=True) lng =models.FloatField(blank=True,null=True) # location = models.PointField(null=False, blank=False, srid=4326, verbose_name="Location") address1 = models.CharField(max_length=100) address2 = models.CharField(max_length=100,blank=True) city = models.CharField(max_length=100) state = models.CharField(max_length=2) postalcode = models.CharField(max_length=20) avg_rating=models.FloatField(blank=True,null=True) restaurant_type=models.ForeignKey(RestaurantType,on_delete=models.CASCADE) price=models.IntegerField(blank=True,null=True,default=0) keywords=models.ManyToManyField(RestaurantKeyword,blank=True) def __str__(self): return self.name Raw Query: SELECT id,name,( 3959 * acos ( cos ( radians(" +lat +")) * cos( radians( lat ) ) * cos( radians( lng ) - radians("+lng+") ) + sin ( radians("+lat+") ) * sin( radians( lat ) ) ) ) AS distance FROM newbackend_restaurant In this code raw query is working fine but I'm looking for ORM query in Django.
answer count: 0
tagged with: django-models
has comment: http://stackoverflow.com/comment/91053123
type: Question
has title: Calculate lat long Distance ORM query python django
tagged with: postgresql
score: 0
tagged with: python-3.x
type: UnansweredQuestion
tagged with: django
tagged with: python

http://stackoverflow.com/q/52074329
tagged with: python
accepted answer: http://stackoverflow.com/a/52074395
has answer: http://stackoverflow.com/a/52074561
possible better answer: http://stackoverflow.com/a/52074409
has comment: http://stackoverflow.com/comment/91098355
has comment: http://stackoverflow.com/comment/91098323
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91099252
has answer: http://stackoverflow.com/a/52074409
linked to: http://stackoverflow.com/q/7794208
has comment: http://stackoverflow.com/comment/91098610
upvote count: 1
has title: Searching for duplicates and remove them
type: Question
has comment: http://stackoverflow.com/comment/91098483
has body: sometimes I have a string like this string = "Hett, Agva," and sometimes I will have duplicates in it. string = "Hett, Agva, Delf, Agva, Hett," how can I check if my string has duplicates and then if it does remove them? UPDATE. So in the second string i need to remove Agva, and Hett, because there is 2x of them in the string
has answer: http://stackoverflow.com/a/52074395
tagged with: python-2.7
downvote count: 0
score: 1
favorite count: 0
has answer: http://stackoverflow.com/a/52074547
has comment: http://stackoverflow.com/comment/91098474
answer count: 5
has answer: http://stackoverflow.com/a/52075687

http://stackoverflow.com/comment/91039973
comment on: http://stackoverflow.com/q/52027956
score: 0
type: Comment
type: QuestionComment
has text: Did you save the df as csv first and then reload it? I had done `df2.id = df2.id.astype("object")` and `df_loaded.combine_first(df2.set_index(["key1", "id"]))`, but I just tried your code (with semicolon on one line) and I get the same garbled index result.

http://stackoverflow.com/comment/91111413
score: 0
type: AnswerComment
type: Comment
has text: Thank you. I'll take a look
comment on: http://stackoverflow.com/a/52079746

http://stackoverflow.com/a/52167790
has comment: http://stackoverflow.com/comment/91286567
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/91336274
has comment: http://stackoverflow.com/comment/91332358
has body: Why would the presence of other columns make a difference in this kind of assignment? The simple answer is because Pandas checks for mixed types within a dataframe. You can check this for yourself using the same method used in the source code: print(df1._is_mixed_type) # False print(df2._is_mixed_type) # False print(df3._is_mixed_type) # True The logic used differs based on the value of _is_mixed_type. Specifically, the following test in _setitem_with_indexer fails when _is_mixed_type is True for the inputs you have provided: if len(labels) != value.shape[1]: raise ValueError('Must have equal len keys and value ' 'when setting with an ndarray') In other words, there are more columns in the array than there are columns to assign to in the dataframe. Is this a bug? In my opinion, any use of lists or arrays in a Pandas dataframe is fraught with danger.1 The ValueError check was added to fix a more important issue (GH 7551). Why are the different versions of the assignment not equivalent? The reason why assignment via df3['col1'] = x works is because col1 is an existing series. Try df3['col3'] = x and your code will fail with ValueError. Digging deeper, the __setitem__ method for a datframe, for which df[] is syntactic sugar, converts the 'col1' label to a series (if it exists) via key = com._apply_if_callable(key, self): def _apply_if_callable(maybe_callable, obj, **kwargs): """ Evaluate possibly callable input using obj and kwargs if it is callable, otherwise return as it is """ if callable(maybe_callable): return maybe_callable(obj, **kwargs) return maybe_callable The logic can then sidestep the checking logic in _setitem_with_indexer. You can infer this because we jump to _setitem_array instead of _set_item when we provide a label for an existing series: def __setitem__(self, key, value): key = com._apply_if_callable(key, self) if isinstance(key, (Series, np.ndarray, list, Index)): self._setitem_array(key, value) elif isinstance(key, DataFrame): self._setitem_frame(…
type: Answer
score: 10
answers question: http://stackoverflow.com/q/52080334
has comment: http://stackoverflow.com/comment/91338110
accepted answer of: http://stackoverflow.com/q/52080334
upvote count: 10
has comment: http://stackoverflow.com/comment/91332118
has comment: http://stackoverflow.com/comment/91287865

http://stackoverflow.com/q/52064443
downvote count: 1
answer count: 1
has comment: http://stackoverflow.com/comment/91167615
favorite count: 0
has comment: http://stackoverflow.com/comment/91107099
has body: I have my django admin as -- User Name City Number John_Lincoln_roma_1.0 John_Lincoln_roma roma 1.0 Eddie_paul_roma_1.1 Eddie_paul_roma roma 1.1 Shin_roma_1.2 Shin_roma roma 1.2 Sinclair_madrid_1.0 Sinclair_madrid madrid 1.0 Jessie_madrid_1.1 Jessie_madrid madrid 1.1 I want to apply query which should return me the User on the basis of Max number which is 1.2 &amp; 1.1 and the record it should give me are Shin_roma_1.2 and Jessie_madrid_1.1 Below is the snippet which I tried - some_object.values('name').annotate(number=Max('number')).order_by() Getting the result as - result = [{'number': u'1.2', 'name': u'Shin_roma'}, {'number': u'1.1', 'name': u'Jessie_madrid'}, print type(result) &lt;class 'django.db.models.query.QuerySet'&gt; I want a query or filter that returns the User based on filtering the dictionary values which is in result. Basically I want to group by on the basis of CITY and on the basis of City Shin_roma_1.2 and Jessie_madrid_1.1 is Max. So it should return me the User with Max number on order of City I tried something like this which I didn't get the result (I know this is wrong) - result.filter(result__number="number",result__city="city") Gone through the stackoverflow but didn't get the solution. Please let me know if anything is unclear. I hope the above is clear. Thanks.!
has comment: http://stackoverflow.com/comment/91087616
type: UnansweredQuestion
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/91080636
has answer: http://stackoverflow.com/a/52070766
tagged with: orm
type: Question
has title: Django : Filter on the basis of dictionary values
has comment: http://stackoverflow.com/comment/91082763
score: 0
has comment: http://stackoverflow.com/comment/91087654
upvote count: 1

http://stackoverflow.com/a/65295983
downvote count: 0
score: 4
has body: In most networks you have a batchnorm layer after the conv layer, which has a bias. So if you have a batchnorm layer there is no gain. See: Can not use both bias and batch normalization in convolution layers Otherwise, from a math perspective you are learning different functions. However, it turns out that in particular if you have a very complex network for a simple problem, you might achieve almost the same thing without biases than with biases but ending up using more parameters. In my experience, using a factor of 2-4 more parameters than needed rarely hurts performance in deep learning - in particular if you regularize. So, it is hard to notice any difference. However, you might try to use few channels (I don't think depth of the network matters as much as number of channels of the convolution) and see if bias make a difference. I would guess so.
type: Answer
answers question: http://stackoverflow.com/q/51959507
upvote count: 4

http://stackoverflow.com/comment/90923523
has text: Did you tyr https://stackoverflow.com/questions/41400934/handle-notifications-in-python-selenium-chrome-webdriver ?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51986354
score: 1

http://stackoverflow.com/a/52067210
downvote count: 0
has body: Looks like this function does what you want: def shift_function(n, shift): return numbers[(numbers.index(n) + shift) % len(numbers)]
accepted answer of: http://stackoverflow.com/q/52067136
has comment: http://stackoverflow.com/comment/91084719
score: 4
type: AcceptedAnswer
type: Answer
upvote count: 4
answers question: http://stackoverflow.com/q/52067136

http://stackoverflow.com/q/51979368
type: UnansweredQuestion
tagged with: python-2.7
has answer: http://stackoverflow.com/a/51979676
downvote count: 0
has answer: http://stackoverflow.com/a/51979510
score: 1
favorite count: 0
tagged with: python-3.x
type: Question
has comment: http://stackoverflow.com/comment/90908882
has answer: http://stackoverflow.com/a/51979470
has comment: http://stackoverflow.com/comment/90909215
has comment: http://stackoverflow.com/comment/90910596
tagged with: python
has answer: http://stackoverflow.com/a/51979440
has body: I'm trying to count the commas row by row in a .csv file. Unfortunately it always comes up to zero. import csv with open('Test.csv') as csv_file: csv_reader = csv.reader(csv_file, delimiter=',') for row in csv_reader: numCommas = row.read().count(',') print numCommas But I am always getting 0.
has answer: http://stackoverflow.com/a/51979547
upvote count: 1
answer count: 7
has answer: http://stackoverflow.com/a/51979499
has title: Count commas in a csv file using python
has answer: http://stackoverflow.com/a/51979566

http://stackoverflow.com/comment/90956909
type: QuestionComment
type: Comment
has text: this is not the way to go in Python. Have a look at the [classes documentation](https://docs.python.org/3/tutorial/classes.html#class-objects)
score: 0
comment on: http://stackoverflow.com/q/52003643

http://stackoverflow.com/comment/91108364
type: QuestionComment
has text: I think you want `dir(some_object)` but it's unclear to me what you're asking
comment on: http://stackoverflow.com/q/52079129
score: 2
type: Comment

http://stackoverflow.com/a/52102743
downvote count: 0
score: 4
type: Answer
upvote count: 4
answers question: http://stackoverflow.com/q/52088966
has body: Here's the final code that I ended up using. Thanks to kevinkayaks and everyone else who responded! Your help is very much appreciated!!! The first half of this function simply converts the two collections of points and angles to direction vectors. I believe the rest of it is basically the same as what Eric and Eugene proposed. I just happened to have success first with Kevin's and ran with it until it was an end-to-end solution for me. import numpy as np def LS_intersect(p0,a0,p1,a1): """ :param p0 : Nx2 (x,y) position coordinates :param p1 : Nx2 (x,y) position coordinates :param a0 : angles in degrees for each point in p0 :param a1 : angles in degrees for each point in p1 :return: least squares intersection point of N lines from eq. 13 in http://cal.cs.illinois.edu/~johannes/research/LS_line_intersect.pdf """ ang = np.concatenate( (a0,a1) ) # create list of angles # create direction vectors with magnitude = 1 n = [] for a in ang: n.append([np.cos(np.radians(a)), np.sin(np.radians(a))]) pos = np.concatenate((p0[:,0:2],p1[:,0:2])) # create list of points n = np.array(n) # generate the array of all projectors nnT = np.array([np.outer(nn,nn) for nn in n ]) ImnnT = np.eye(len(pos[0]))-nnT # orthocomplement projectors to n # now generate R matrix and q vector R = np.sum(ImnnT,axis=0) q = np.sum(np.array([np.dot(m,x) for m,x in zip(ImnnT,pos)]),axis=0) # and solve the least squares problem for the intersection point p return np.linalg.lstsq(R,q,rcond=None)[0] #sample data pa = np.array([[-7.07106638, 7.07106145, 1. ], [-7.34817263, 6.78264524, 1. ], [-7.61354115, 6.48336347, 1. ], [-7.86671133, 6.17371816, 1. ], [-8.10730426, 5.85419995, 1. ]]) paa = [-44.504854321138524, -42.02922380123842, -41.27857390748773, -37.145774853341386, -34.097022454778674] pb = np.array([[-8.98220431e-07, -1.99999962e+01, 1.00000000e+00], [ 7.99789129e-01, -1.99839984e+01, 1.00000000e+00], [ 1.59830153e+00, -1.99360366e+01, 1.00000000e+00], [ 2.39423914e+00, -1.98561769e+01, 1.00000000e+00],…

http://stackoverflow.com/a/52058713
upvote count: 1
type: Answer
has body: Here is a solution i came up with for you, you need to use command=myfunction without the parantheses def getval(): var = e.get() print(var) c = Checkbutton(master, text="Expand", variable=var) c = Checkbutton( master, text="Color image", variable=var, onvalue=var, offvalue="L",command=getval) This code will print the value in the entry field when the box is clicked
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/52058277

http://stackoverflow.com/comment/90921410
has text: Yes it should be. But that lib missed when you installed manually with yum. Can you try with pip.
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51985828

http://stackoverflow.com/comment/91052918
has text: Hi @Stanley, any resource for OpenCV facial tracking? please!
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52050917

http://stackoverflow.com/q/52002607
type: Question
tagged with: neural-network
has answer: http://stackoverflow.com/a/52003820
score: 0
has body: I already have a neural network that is trained, clf = neural_network.MLPClassifier( activation='relu', hidden_layer_sizes=(40,40,40,40), learning_rate='adaptive', learning_rate_init=0.01, solver='sgd', alpha=1e-6, max_iter=20000, warm_start=True, ) I have trained it, clf.fit(X,Y) This classifier has two classes [0,1]. Now when i train it further by using one data from data set at a time. clf.fit([features_1],[1]) The error pops up Traceback (most recent call last): File "&lt;pyshell#20&gt;", line 1, in &lt;module&gt; fav_clf.fit(X_, Y) File "D:\Python3.5\lib\site-packages\sklearn\neural_network\multilayer_perceptron.py", line 973, in fit hasattr(self, "classes_"))) File "D:\Python3.5\lib\site-packages\sklearn\neural_network\multilayer_perceptron.py", line 331, in _fit X, y = self._validate_input(X, y, incremental) File "D:\Python3.5\lib\site-packages\sklearn\neural_network\multilayer_perceptron.py", line 924, in _validate_input (self.classes_, classes)) ValueError: warm_start can only be used where `y` has the same classes as in the previous call to fit. Previously got [0 1], `y` has [1]
tagged with: python-3.5
answer count: 1
tagged with: scikit-learn
has comment: http://stackoverflow.com/comment/90955143
favorite count: 0
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/52003820
tagged with: python
has title: How to train single data present in a data set to a already trained neural network?
type: AnsweredQuestion
upvote count: 1
downvote count: 1

http://stackoverflow.com/q/52094672
score: -1
tagged with: python-3.6
has answer: http://stackoverflow.com/a/52094812
favorite count: 0
type: UnansweredQuestion
has title: NameError: name 'status' is not defined
tagged with: python
upvote count: 3
type: Question
answer count: 2
downvote count: 4
has answer: http://stackoverflow.com/a/52094765
has comment: http://stackoverflow.com/comment/91139455
has body: this code throw NameError def prime(x): global status for i in range(2, x): if x % i == 0: status = False break else: status = True return status mylist = [] for j in range(50): if prime(j): mylist.append() print(mylist)

http://stackoverflow.com/comment/91077161
type: Comment
has text: Then how do you want the yes sorted?
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52062986

http://stackoverflow.com/comment/91079571
has text: @LukePolson git is the system behind github, bitbucket etc. It is how you store, update and manage programming files.
type: QuestionComment
comment on: http://stackoverflow.com/q/52064475
score: 0
type: Comment

http://stackoverflow.com/a/60941312
upvote count: 5
type: Answer
has comment: http://stackoverflow.com/comment/107819594
score: 4
answers question: http://stackoverflow.com/q/52059974
has comment: http://stackoverflow.com/comment/107818407
downvote count: 1
has body: import tkinter import time root =Tk() label = Label(root, text="Text on the screen", font=('Times New Roman', '80'), fg="black", bg="white") time.sleep(1000) label.destroy() root.mainloop()

http://stackoverflow.com/comment/90892158
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51970871
has text: I want to use this with the talib which requires nd array
score: 0

http://stackoverflow.com/a/52082765
has body: def fname(start, end, inc): return list(range(start, end, inc)) print(fname(0,51,5)) In the above code the function fname returns the list of values from 'start' to 'end' with the increment 'inc' op: [0, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50]
score: 0
type: Answer
answers question: http://stackoverflow.com/q/52082414

http://stackoverflow.com/a/52125189
has body: The problem is solved. Somehow my /bin/sh had been symlinked to /usr/bin/zsh. Pyenv installation fixed after linking /bin/sh back to /usr/bin/bash.
score: 0
type: Answer
answers question: http://stackoverflow.com/q/52069624

http://stackoverflow.com/a/52076556
has comment: http://stackoverflow.com/comment/91124762
upvote count: 4
downvote count: 0
score: 4
type: Answer
answers question: http://stackoverflow.com/q/52073874
has body: @Marcell Erasmus's answer is nice, but it's not covered the status code part (how to return a HTTP 403 status code) First, you need to add a Custom exception class as below, from rest_framework import exceptions from rest_framework import status class CustomAPIException(exceptions.APIException): status_code = status.HTTP_403_FORBIDDEN default_code = 'error' def __init__(self, detail, status_code=None): self.detail = detail if status_code is not None: self.status_code = status_code and use the class wherever you want by , if some_condition: raise CustomAPIException({"some": "data"}) One of the most advantage of this particular class is that you could raise API exception with custom status codes by specifying the status_code parameter Ex. if some_condition: raise CustomAPIException({"some": "data"},status_code=status.HTTP_409_CONFLICT)
has comment: http://stackoverflow.com/comment/91123285

http://stackoverflow.com/comment/91243523
comment on: http://stackoverflow.com/a/52091740
score: 0
type: Comment
has text: what if I wanted to color data other than the original dataframe 'df9', which has similar structure i.e. has Category column and another column onto which I want to apply the colors on category by category basis taking the 'Month_low' and 'Month_up' values from our calculation?
type: AnswerComment

http://stackoverflow.com/q/51971352
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/90991905
has comment: http://stackoverflow.com/comment/90995521
tagged with: math
has body: Right now I am plotting a streographic projection with a center at the z axis by getting a P vector (Px, Py, Pz) from different directional indices in a unit sphere. The following process converts these to 2d coordinates. (Python) x2,y2,z2=P theta2=np.arccos(abs(z2)/(x2**2+y2**2+z2**2)**.5) phi2=np.arctan((y2/x2)) xp=theta2*np.cos((phi2)) yp=theta2*np.sin((phi2)) Plot xp,yp What transformations do I apply in order to change the P vector (or a different aspect of the code) so that the center is on a different direction (x-axis for example)? Thanks.
type: Question
tagged with: projection
has comment: http://stackoverflow.com/comment/90893230
score: 0
has title: How to change the center of a stereographic projection?
tagged with: geometry
tagged with: mapping
answer count: 0

http://stackoverflow.com/q/52045100
has comment: http://stackoverflow.com/comment/91053464
has answer: http://stackoverflow.com/a/64392337
has comment: http://stackoverflow.com/comment/91066137
answer count: 3
tagged with: cascading-deletes
has title: Delete parent if the child is deleted
has answer: http://stackoverflow.com/a/64401347
has answer: http://stackoverflow.com/a/64308882
linked to: http://stackoverflow.com/q/5033547
favorite count: 0
tagged with: one-to-many
type: UnansweredQuestion
has body: I want to delete the parent row if the associated rows in child tables have been removed. class Child(Base): __tablename__ = "children" id = Column(Integer, primary_key=True) parent_id = Column(Integer, ForeignKey("parents.id", ondelete='CASCADE')) class Parent(Base): __tablename__ = "parents" id = Column(Integer, primary_key=True) child = relationship(Child, backref="parent", passive_deletes=True) If I remove the child child_obj = session.query(Child).first() session.delete(child_obj) session.commit() It does delete the child obj but parent remains as it is. I want to remove the parent as well using cascading.
tagged with: python
has comment: http://stackoverflow.com/comment/113834109
linked to: http://stackoverflow.com/q/22471172
tagged with: sqlalchemy
type: Question
score: 9
has comment: http://stackoverflow.com/comment/113840418
upvote count: 9
downvote count: 0

http://stackoverflow.com/q/52046447
tagged with: vi
has body: So I'm happily "hacking" away in the command line using vim. I'm working on some JSON text, I'm deleting objects, trimming down an API response to isolate a snippet to work more closely with. At some point I'm pretty happy I've cut out all of the rubbish from the JSON and I've only got what I need to carry on working... So I go ahead and type in :%!python -m json.tool and boom. So my JSON text wasn't a valid JSON text after I poked around with it, looks like I forgot a comma somewhere. :%!python -m json.tool shell returned 1 Press ENTER or type command to continue So I hit enter or any other key and then my buffer is replaced with a nice error message... Expecting , delimiter: line 3 column 5 (char 20) Oh so I did forget a comma, on line 3, thanks! Oh but where's my JSON text gone? And that ladies and gentlemen is what I seek help with. This is usually where I :q! and reopen the JSON file and try to get it right this time. But surely I must be able to recover my buffer from just BEFORE I had the audacity to try and use the python json tool to format a blob of non-JSON text!
downvote count: 3
upvote count: 1
type: Question
score: -2
tagged with: http://stackoverflow.com/tag/json
answer count: 2
has answer: http://stackoverflow.com/a/52061604
linked to: http://stackoverflow.com/q/22511451
has answer: http://stackoverflow.com/a/52052774
favorite count: 0
type: UnansweredQuestion
tagged with: python
has title: json.tool shell returned 1 and I lost my vim buffer
tagged with: vim

keystroke
type: Tag
tags question: http://stackoverflow.com/q/51966516
tag name: keystroke

http://stackoverflow.com/comment/90999320
has text: Hmm, alright. Well, if you are able to expose services over web interfaces, then you could package and deploy a Python2 web server (e.g. Flask) that acts as a proxy to be called by Python3 code. Otherwise, you cannot package them together and by using Popen, you're requiring both be installed on the same system
score: 0
comment on: http://stackoverflow.com/q/52024351
type: Comment
type: QuestionComment

http://stackoverflow.com/a/51986220
upvote count: 3
accepted answer of: http://stackoverflow.com/q/51962262
type: Answer
answers question: http://stackoverflow.com/q/51962262
score: 3
downvote count: 0
has body: Well, I took an entirely different approach to the problem. Below is the adjustment to the code: def new_line(self): row = self.hours_model.rowCount() record = self.hours_model.record() record.setGenerated('id', False) record.setValue('empid', self.ui.emp_id.text()) record.setValue('weekending', self.ui.weekending.date()) record.setValue('department', self.ui.department.currentText()) record.setValue('pay_type', 'Regular') record.setValue('starttime', QDateTime.currentDateTime()) record.setValue('endtime', QDateTime.currentDateTime()) self.hours_model.insertRecord(row, record) self.hours_view.edit(QModelIndex(self.hours_model.index(row, self.hours_model.fieldIndex('department')))) This seems to work. However, it begets more questions than it answers. It seems to me that the approach in my question, although more verbose, is more model/view. So I am still stumped.
type: AcceptedAnswer

http://stackoverflow.com/comment/91038668
comment on: http://stackoverflow.com/q/52043677
has text: Starts with ^ not $.
type: QuestionComment
type: Comment
score: 1

http://stackoverflow.com/q/52027687
tagged with: python
has comment: http://stackoverflow.com/comment/91005917
has comment: http://stackoverflow.com/comment/91005762
has comment: http://stackoverflow.com/comment/91005809
has comment: http://stackoverflow.com/comment/91005691
upvote count: 2
downvote count: 2
has comment: http://stackoverflow.com/comment/91005874
has comment: http://stackoverflow.com/comment/91005978
has comment: http://stackoverflow.com/comment/91005633
has comment: http://stackoverflow.com/comment/91005676
has comment: http://stackoverflow.com/comment/91005814
has comment: http://stackoverflow.com/comment/91006024
has comment: http://stackoverflow.com/comment/91005717
type: Question
has answer: http://stackoverflow.com/a/52027902
has comment: http://stackoverflow.com/comment/91005582
has comment: http://stackoverflow.com/comment/91005600
has comment: http://stackoverflow.com/comment/91005651
has comment: http://stackoverflow.com/comment/91005936
has comment: http://stackoverflow.com/comment/91005732
has comment: http://stackoverflow.com/comment/91005815
has comment: http://stackoverflow.com/comment/91005780
has comment: http://stackoverflow.com/comment/91005647
score: 0
has comment: http://stackoverflow.com/comment/91005584
has comment: http://stackoverflow.com/comment/91005596
has comment: http://stackoverflow.com/comment/91005979
has comment: http://stackoverflow.com/comment/91005663
has comment: http://stackoverflow.com/comment/91005724
answer count: 1
has body: I just started coding, so I don't know if this is normal or not... but I was experimenting on Python 3.7 shell. Anyways, I typed in: name = "Martin" print(name) and as a result I got the number 3514524017891864227. I don't know if this is some sort of error or something and I'm hoping that someone could explain this to me.
favorite count: 0
has comment: http://stackoverflow.com/comment/91005704
has title: Is the number 3514524017891864227 an error?
type: UnansweredQuestion

http://stackoverflow.com/q/52073054
has answer: http://stackoverflow.com/a/52073111
tagged with: pandas-groupby
tagged with: pandas
has title: Group by a column to find the most frequent value in another column?
downvote count: 0
possible better answer: http://stackoverflow.com/a/52073183
duplicate of: http://stackoverflow.com/q/15222754
has answer: http://stackoverflow.com/a/52073183
favorite count: 0
linked to: http://stackoverflow.com/q/44481768
tagged with: python
has comment: http://stackoverflow.com/comment/91095882
accepted answer: http://stackoverflow.com/a/52073111
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91095898
upvote count: 10
type: Question
tagged with: group-by
score: 10
has body: Group by a column to find most frequent value in another column. Example: import pandas as pd d = {'col1': ['green','green','green','blue','blue','blue'],'col2': ['gx','gx','ow','nb','nb','mj']} df = pd.DataFrame(data=d) df gives: col1 col2 green gx green gx green ow blue nb blue nb blue xv results: for green to have gx and for blue to have nb
linked to: http://stackoverflow.com/q/15222754
answer count: 2

http://stackoverflow.com/q/51957917
type: Question
has comment: http://stackoverflow.com/comment/90888168
accepted answer: http://stackoverflow.com/a/51959906
has comment: http://stackoverflow.com/comment/90886944
downvote count: 0
answer count: 1
score: 1
favorite count: 0
tagged with: python
has comment: http://stackoverflow.com/comment/90870761
type: AnsweredQuestion
has title: sqlalchemy query related tables: to join or not to join (and then to loop)?
has answer: http://stackoverflow.com/a/51959906
upvote count: 1
has body: Objective: Retrieve a list of query results from one table (call it "groups"). Retrieve lists of results from a related table (call it "items"). One results list for each of the results from step 1. Combine the "items" lists from step 2 with the corresponding "groups" result from step 1 in a tuple that contains both the "group" data and a list of all the related "items" data. Question: Is it more efficient to combine steps 1 and 2 above with a join query and then loop through to sift and aggregate the results by group? Or is it more efficient to query the results for step 1, then loop to query the results for step 2 and and aggregate the results? Examples of each approach follow, hoping there is some other much better way... Single query with loop approach (with join): # query all "groups" in "category1" and all related "items" results = session.query(Group.id, Group.name, Item.id, Item.name).\ outerjoin(Item, Group.items).\ filter(Group.category == 'category1').\ order_by(Group.id).\ all() groups = list() group_ids = set(results[0][0]) current_group = results[0][:2] current_group_items = list() for result in results: # for each result, combine "group" with all related "items" if result[0] in group_ids: current_group_items.append(result[2:]) else: groups.append(current_group + (current_group_items,)) group_ids.add(result[0]) current_group = result[:2] current_group_items = [result[2:]] Multiple query with loop approach (no join): # query all "groups" in "category1" groups = session.query(Group.id, Group.name).\ filter(Group.category == 'category1').\ all() results = [] for group in groups: # for each "group", query all related "items" items = session.query(Item.id, Item.name).\ filter(Item.group_id == group[0]).\ all() # append list of related "items" to "group" result results.append(group + (items,)) Example schema for reference: from sqlalchemy import Column, Integer, String, ForeignKey from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm im…
tagged with: sqlalchemy

http://stackoverflow.com/comment/90953030
comment on: http://stackoverflow.com/q/51963760
type: Comment
type: QuestionComment
has text: @9769953 how can the be done?
score: 0

http://stackoverflow.com/q/51993495
has title: Finding average of elements with the previous elements and summing it and averaging
has comment: http://stackoverflow.com/comment/90936961
tagged with: math
score: 0
answer count: 1
has body: I have a set of numbers, just to make it easier: import numpy as np A = np.array([0, 1, 2, 3, 4, 5, ...]) I want to: ((0+1)/2 + (2+1)/2)/2 , ((1+2)/2 + (3+2)/2)/2, .... I am not sure how to go about this. What I got so far: B = (A[1:]+A[:-1])/2.0 I would expect to get: B = [1, 2, 3, 4, 5 ...] Any help would be great. Thank you.
tagged with: python
has comment: http://stackoverflow.com/comment/90936934
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90936722
has answer: http://stackoverflow.com/a/51993551
has comment: http://stackoverflow.com/comment/90936659
type: Question

http://stackoverflow.com/a/52474844
type: Answer
has body: This issue has been fixed in Pyperclip 1.6.5. You just need to upgrade by running pip install -U pyperclip
answers question: http://stackoverflow.com/q/52045064
score: 0

http://stackoverflow.com/comment/94125431
comment on: http://stackoverflow.com/a/52166410
type: Comment
has text: You can rate the answer as +1, because in the situation explained above is the correct answer
score: 0
type: AnswerComment

http://stackoverflow.com/a/52030327
accepted answer of: http://stackoverflow.com/q/52029864
answers question: http://stackoverflow.com/q/52029864
has comment: http://stackoverflow.com/comment/91011757
upvote count: 2
type: AcceptedAnswer
type: Answer
score: 2
downvote count: 0
has body: Here is an alternative... it uses list comprehension which is generally faster than for-loops l = 2 # Define the bounds beforehand, its marginally faster than doing it in the loop upper = np.array(patt_idx) + l + 1 lower = np.array(patt_idx) - l - 1 # List comprehension... new_inds = [price[low:hi].argmax() + low if lab == -2 else price[low:hi].argmin() + low for low, hi, lab in zip(lower, upper, label)] # Find maximum within each interval new_max = price[new_inds] new_global_max = np.max(new_max)

http://stackoverflow.com/comment/90942346
type: Comment
type: QuestionComment
score: 0
has text: I'm definitely importing it to the right file. How would I deal with the name duplication?
comment on: http://stackoverflow.com/q/51996464

http://stackoverflow.com/comment/90949550
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/51999765
score: 0
has text: Series([], Name: id1, dtype: object) - it's empty if i use your method

http://stackoverflow.com/a/52069789
answers question: http://stackoverflow.com/q/52069592
has body: When module2.run(example) was called, it created an object that occupies space in ram and returned a pointer to that object. # Inside module2.py import pandas as pd def run(example): return pd.DataFrame(1, range(10), range(10)) # Inside module1.py import module2 df_1 = module2.run(example) df_1.loc[:] = 2 print(df_1) 0 1 2 3 4 5 6 7 8 9 0 2 2 2 2 2 2 2 2 2 2 1 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 3 2 2 2 2 2 2 2 2 2 2 4 2 2 2 2 2 2 2 2 2 2 5 2 2 2 2 2 2 2 2 2 2 6 2 2 2 2 2 2 2 2 2 2 7 2 2 2 2 2 2 2 2 2 2 8 2 2 2 2 2 2 2 2 2 2 9 2 2 2 2 2 2 2 2 2 2
type: Answer
downvote count: 0
score: 1
accepted answer of: http://stackoverflow.com/q/52069592
upvote count: 1
type: AcceptedAnswer

http://stackoverflow.com/comment/90901853
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51975664
has text: You don't strictly _need_ a third-party library, but serialization is more complicated than you appear to think (hence the existence of Marshmallow and other similar libraries). I suggest looking at the link I provided and making your own decision. For example, Marshmallow wants you to define schemas and Django REST Framework wants you to build serializers. Why do you think both of those make you do manual work?
score: 0

http://stackoverflow.com/q/52014056
upvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/90979029
has comment: http://stackoverflow.com/comment/90978842
tagged with: django-views
tagged with: django-models
has answer: http://stackoverflow.com/a/52014282
has comment: http://stackoverflow.com/comment/90978877
answer count: 1
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/90978750
has comment: http://stackoverflow.com/comment/90978736
has body: I can't seem to figure this out. My view takes an argument for Team.id, and I want to return a context object with each User object with a certain value in User.profile.team and the associated date from Reports. I feel like I started on the right track, but am missing something. The output of my template contains all the data I'm trying to get, but not in a way that can be displayed logically. Basically, I'm using models similar to the following: class Reports(models.Model): user = models.ForeignKey(User, null=True, on_delete=models.PROTECT) product = models.CharField(max_length=15) apps_activated = models.IntegerField(blank=True, null=True) prem_submitted = models.DecimalField(max_digits=30, decimal_places=2) class Team(models.Model): name = models.CharField(max_length=255) leader = models.ForeignKey(User,on_delete=models.PROTECT) Extended user profile: class Profile(models.Model): COORDINATOR = 1 LEADER = 2 ADMIN = 3 ROLE_CHOICES = ( (COORDINATOR, 'Coordinator'), (LEADER, 'Leader'), (ADMIN, 'Admin'), ) user = models.OneToOneField(User, on_delete=models.CASCADE) team = models.ForeignKey(Team, on_delete=models.PROTECT,null=True) role = models.PositiveSmallIntegerField(choices=ROLE_CHOICES, null=True, blank=True) The closest I got in my view to return the desired data is with the following: team = 1 team_name = Team.objects.get(id=team) team_users = User.objects.filter(profile__team=team).all() team_stats = [] for user in team_users: team_stats.append(Reports.objects.filter(user_id=user.id)) With a template that looks like: {% block content %} {{ team }} {% for user in team_users %} {{ user.first_name }} {{ user.last_name }} {% endfor %} {% for stat in team_stats %} {% for line in stat %} {{ line.product }} {{ line.type }} #etc #etc {% endfor %} {% endfor %} {% endblock %} I thought I was on to something with prefetch_related(), but couldn't figure it out. Ideally, I'd only have to return one context object to my template. Edit: If it makes it more clear, this query …
tagged with: python
accepted answer: http://stackoverflow.com/a/52014282
has comment: http://stackoverflow.com/comment/90978664
has title: Creating a context object with values from several related models
type: AnsweredQuestion
tagged with: django-templates
score: 1
tagged with: django

http://stackoverflow.com/a/52038506
type: Answer
has body: Not sure if there is any particular command for it. But generally it can be done using shell. Number of workers mean number of processes. Hence you can simple check all the active process, then find all the process which has gunicorn in it and then count all such entries. Do remember to exclude the grep search because it is also has gunicorn. You command would look something like this. ps aux | grep gunicorn | grep -v grep | wc -l
score: 4
upvote count: 4
answers question: http://stackoverflow.com/q/52025195
has comment: http://stackoverflow.com/comment/91077908
has comment: http://stackoverflow.com/comment/107607149
downvote count: 0
has comment: http://stackoverflow.com/comment/91078058

http://stackoverflow.com/a/52628380
has comment: http://stackoverflow.com/comment/115689761
downvote count: 0
has comment: http://stackoverflow.com/comment/134716783
has comment: http://stackoverflow.com/comment/126839843
has comment: http://stackoverflow.com/comment/134716804
type: AcceptedAnswer
has body: isnull is an alias for isna. Literally in the code source of pandas: isnull = isna Indeed: &gt;&gt;&gt; pd.isnull &lt;function isna at 0x7fb4c5cefc80&gt; So I would recommend using isna.
has comment: http://stackoverflow.com/comment/99125430
score: 172
has comment: http://stackoverflow.com/comment/116354048
has comment: http://stackoverflow.com/comment/93354894
has comment: http://stackoverflow.com/comment/93378648
has comment: http://stackoverflow.com/comment/121205021
type: Answer
has comment: http://stackoverflow.com/comment/132140435
accepted answer of: http://stackoverflow.com/q/52086574
upvote count: 172
has comment: http://stackoverflow.com/comment/136265909
answers question: http://stackoverflow.com/q/52086574

http://stackoverflow.com/comment/91170302
type: Comment
has text: It [defaults to the intersection of the columns in both DataFrames](https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.merge.html) when not merging on indexes.
score: 0
comment on: http://stackoverflow.com/q/52109791
type: QuestionComment

http://stackoverflow.com/comment/90942135
has text: You are so right. Apparently Python accepts this without generating an error. Why is it a valid statement anyway even if it doesn't do what is expected? (At least not by me?). If you post this as an answer I can upvote it.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51996229

http://stackoverflow.com/q/52058503
tagged with: modulo
favorite count: 0
score: 0
duplicate of: http://stackoverflow.com/q/39983695
has comment: http://stackoverflow.com/comment/91091878
linked to: http://stackoverflow.com/q/39983695
answer count: 0
type: UnansweredQuestion
tagged with: python
has body: I'm trying to figure out why the list comprehension below returns what it returns. I get a little confuse with the modulo indicator. Example: The output below i cant understand the output. print([i for i in range(11) if i%2]) Output: [1, 3, 5, 7, 9] However in the example below I perfectly understand the return of even numbers. print([i for i in range(11) if i%2==0]) [0, 2, 4, 6, 8, 10]
has comment: http://stackoverflow.com/comment/91085417
type: Question
upvote count: 2
downvote count: 2
has comment: http://stackoverflow.com/comment/91067472
has title: Using modulo python

http://stackoverflow.com/comment/90865031
comment on: http://stackoverflow.com/q/51957188
has text: FWIW most people use `pip` for installing third-party Python packages these days, so it's unusual to install a package like `pywin32` using a standalone installer. And I thought that newer versions of Python distributions for Windows came with win32 support built in?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/90868333
type: QuestionComment
has text: @Amadan I agree that speed in a given runtime can be a small factor but for this particular algorithm, there is no better possible runtime than O(N).
score: 0
comment on: http://stackoverflow.com/q/51958798
type: Comment

http://stackoverflow.com/comment/90903099
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/51976328
type: Comment
has text: (They should really be regular hyphens instead of soft hyphens, but that's a different issue.)

logfile
tags question: http://stackoverflow.com/q/52036914
type: Tag
tag name: logfile

http://stackoverflow.com/comment/91077545
has text: Welcome, It looks like you want us to write some code for you. While many users are willing to produce code for a coder in distress, they usually only help when the poster has already tried to solve the problem on their own. A good way to demonstrate this effort is to include the code you've written so far, example input (if there is any), the expected output, and the output you actually get (console output, tracebacks, etc.). The more detail you provide, the more answers you are likely to receive. Check the [FAQ] and [ask].
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52063578
score: 1

http://stackoverflow.com/comment/91152511
type: QuestionComment
comment on: http://stackoverflow.com/q/52100734
score: 0
has text: See my edit above ^
type: Comment

http://stackoverflow.com/q/51971328
linked to: http://stackoverflow.com/q/36429875
score: 4
linked to: http://stackoverflow.com/q/13743785
answer count: 1
favorite count: 0
tagged with: mpmath
has answer: http://stackoverflow.com/a/51971786
tagged with: python
accepted answer: http://stackoverflow.com/a/51971786
upvote count: 4
type: AnsweredQuestion
has title: How to evaluate a numpy array inside an mpmath fuction?
downvote count: 0
type: Question
tagged with: numpy
has body: I get an error when I try to use a numpy array inside mpmath function, this example fails when it reaches the line: C = (f*L/D) + 2*mp.log(P1/P2) Where P1 is an array. With the error: cannot create mpf from array([**P1_array**]) I'm aware of this and this treads, which are related. But I cant get my code to work. Can someone help me to correct this mistake? import numpy as np import mpmath as mp mp.mp.dps = 20 # State equation --&gt; pV = nZRT P1 = np.linspace(101325,10*101325,100) P2 = 101325 T = 300 D = 0.0095 A = mp.power(D,2)*mp.pi/4 L = 300 R = 8.31446 f = 0.05 Z1 = 0.9992 Z2 = 0.9999 Zm = 0.5*(Z1+Z2) C = (f*L/D) + 2*mp.log(P1/P2) w2 = (mp.power(P1,2)-mp.power(P2,2))*mp.power(A,2)/(Zm*R*T*C) w = mp.power(w2,0.5)

http://stackoverflow.com/comment/91129379
type: AnswerComment
type: Comment
has text: Sorry, maybe i'm not being clear enough. I'm not looking for a way to load data from Pandas or check numbers -- it's just an example. Will edit the question to reflect the real issue.
comment on: http://stackoverflow.com/a/52089689
score: 0

http://stackoverflow.com/q/51966366
tagged with: django
has comment: http://stackoverflow.com/comment/90901387
type: AnsweredQuestion
has body: I was trying to make the custom password reset view for django.contrib.auth.views.password_reset. I made it by myself (Of course, I see some tutorial articles.) But when I request the password reset form to the development server, It shows like this (on the development server log): Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit Subject: Hello From: &lt;My email address&gt; (Outlook) To: &lt;My another email address&gt; (GMail) Date: Wed, 22 Aug 2018 11:44:55 -0000 Message-ID: &lt;20180822114455.3320.17387@Yeonhos-MacBook-Pro.local&gt; I am testing Django EmailMessage Class But, It doesn't send anything to my address which is marked as My another email address. Can anyone help me? Why doesn't Django send this e-mail?
type: Question
has title: What should I do if Django doesn't send any email when I requested?
score: 0
answer count: 2
tagged with: django-email
has comment: http://stackoverflow.com/comment/90888626
has answer: http://stackoverflow.com/a/51996212
has answer: http://stackoverflow.com/a/51976868
has comment: http://stackoverflow.com/comment/90882839
tagged with: python
possible better answer: http://stackoverflow.com/a/51976868
accepted answer: http://stackoverflow.com/a/51996212

http://stackoverflow.com/q/52109720
has body: I would like to plot several boxplots. For that I have a pandas series containing float64 values. (example: last values of timeoverall1) timeoverall1 1352 89.611111 1353 95.964167 1354 71.482222 1355 94.788611 1356 71.475278 1357 70.289167 Length: 1057, dtype: float64 I transform the series into arrays (i dont know if its even needed but my source suggested it so i better did). bpoverall 94.78861111, 71.47527778, 70.28916667]) Now here is what I did exactly for you to reproduce: #put into arrays to make plotready bpoverall = np.array(timeoverall1) bpstockout = np.array(timestockout1) bpindig = np.array(timeindig1) bppacking = np.array(timepacking1) bpend = np.array(timeend1) #print boxplots boxplot1 = plt.boxplot(bpoverall) boxplot2 = plt.boxplot(bpindig) boxplot3 = plt.boxplot(bpstockout) boxplot4 = plt.boxplot(bppacking) boxplot5 = plt.boxplot(bpend) So when I run the code step by step i get 5 several boxplots, as i like. But when i run all of the code at once i get this: Where does this mistake occur? How can I avoid this?
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/52110246
type: Question
tagged with: numpy
answer count: 1
tagged with: arrays
has title: My boxplots merge all in one plot when i run the code
score: 0
tagged with: python

http://stackoverflow.com/comment/91084105
type: Comment
type: AnswerComment
has text: It would help to have the binary input file (or a way to create one), and the expected results. The R-code does give the correct expected output?
score: 0
comment on: http://stackoverflow.com/a/52046283

http://stackoverflow.com/comment/91081239
type: Comment
type: QuestionComment
has text: You could create the image using PIL.
comment on: http://stackoverflow.com/q/52065249
score: 0

http://stackoverflow.com/comment/90961893
comment on: http://stackoverflow.com/a/51994438
has text: @S.V great , I did not test the timing on my side , thank for share the information.
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/91061617
score: 0
comment on: http://stackoverflow.com/q/52055442
has text: Yes, but `mean` is not what need, because always returned same value `for i in a.words: print( a.sentiment.polarity)`. And it is same for each sentence. So there has to be soemthing wrong, no idea what
type: QuestionComment
type: Comment

http://stackoverflow.com/q/52092842
has title: Running twice the libraries to have interactive plots on jupyter
downvote count: 1
type: Question
accepted answer: http://stackoverflow.com/a/52093007
has comment: http://stackoverflow.com/comment/91135623
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/91135830
has comment: http://stackoverflow.com/comment/91135668
has body: Every time I want to have an interactive plot on Jupyter, I have to run the libraries twice. The libraries are as simple as this: import matplotlib.pyplot as plt %matplotlib notebook The first time I make a plot I have a static image (like shown here). If I run again the libraries, the figure is now interactive. Do you know why? Static image: Interactive image:
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/52093007
tagged with: python
tagged with: jupyter
score: 2
type: AnsweredQuestion
upvote count: 3

http://stackoverflow.com/comment/90883982
comment on: http://stackoverflow.com/a/51966616
type: AnswerComment
score: 0
type: Comment
has text: "100 loops, best of 3: 2.65 ms per loop". Too late bud ;)

http://stackoverflow.com/comment/91140517
score: 0
type: Comment
has text: Your method also need `predictions` as probabilities between 0,1. Only then it will work.
comment on: http://stackoverflow.com/a/52094705
type: AnswerComment

http://stackoverflow.com/q/52058478
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/56116318
has body: I am running the following code: from io import StringIO dot_data = StringIO() export_graphviz(DT, out_file=dot_data, filled=True, rounded=True, special_characters=True) graph = pydotplus.graph_from_dot_data(dot_data.getvalue()) Image(graph.create_png()) and getting the following error message: InvocationException: GraphViz's executables not found Based on looking at other stackoverflow answers, it is my understanding that I can try to resolve this by adding things to PATH. I do not have administrative rights (username and password) on my work computer so I was wondering if there is another way to resolve this error message?
tagged with: python
tagged with: python-3.x
tagged with: stringio
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/png
tagged with: pydot
score: 1
type: Question
has title: Can I resolve "InvocationException: GraphViz's executables not found" without adding anything to system PATH?
upvote count: 1
downvote count: 0

http://stackoverflow.com/comment/90986870
score: 2
type: Comment
has text: Why implement this in python when we have numpy? I don't see the benefit of messing with syntax
type: QuestionComment
comment on: http://stackoverflow.com/q/52018265

http://stackoverflow.com/a/52013477
downvote count: 0
answers question: http://stackoverflow.com/q/52013266
type: Answer
upvote count: 2
score: 2
has body: First, the simplest change to your existing code is to get rid of that nested loop. Just have the for loop and an if: for i in range(1, maximum+1): if i*i &gt; maximum: break print(i*i) Or just have the while loop and increment manually: i = 1 while i*i &lt;= maximum: print(i*i) i += 1 One thing: Notice I used range(1, maximum+1)? Ranges are half-open: range(1, maximum) gives us all the numbers up to but not including maximum, and we need to include maximum itself to have all the numbers up to maximum squared, in case it's 1. (That's the same reason to use &lt;= instead of &lt; in the while version. But let’s have a bit more fun. If you had all of the natural numbers: numbers = itertools.count(1) … you could turn that into all of the squares: squares = (i*i for i in numbers) Don’t worry about the fact that there are an infinite number of them; we’re computing them lazily, and we’re going to stop once we pass maximum: smallsquares = itertools.takewhile(lambda n: n&lt;=maximum, squares) … and now we have a nice finite sequence that we can just print out: print(*smallsquares) Or, if you’d prefer if all on one line (in which case you probably also prefer a from itertools import count, takewhile): print(*takewhile(lambda n: n&lt;=maximum, (i*i for i in count(1))) But really, that lambda expression is kind of ugly; maybe (with from functools import partial and from operator import ge) it’s more readable like this: print(*takewhile(partial(ge, maximum), (i*i for i in count(1)))

http://stackoverflow.com/q/52093988
downvote count: 0
has comment: http://stackoverflow.com/comment/91236905
favorite count: 0
tagged with: python
tagged with: pycharm
upvote count: 3
type: UnansweredQuestion
tagged with: remote-debugging
type: Question
score: 3
has title: PyCharm remote debugging about double SSH
has answer: http://stackoverflow.com/a/55337052
has body: Using PyCharm remote debugging is one of my favorite choices when doing deep learning jobs on Server platform. But recently I face a problem is that I have to first use SSH to login the platform then I will need another SSH to access the computing node. I may have to do this using my shell. ssh myname@myip ssh mynode python myfile.py Thus, usually when I use PyCharm. I can only do as the following: ssh myname@myip python myfile.py My question is: how I can use PyCharm to double my SSH operation?
has comment: http://stackoverflow.com/comment/91175069
answer count: 1

http://stackoverflow.com/q/52045801
downvote count: 2
tagged with: python
has body: First of all, bear with me as I'm very new to Python/Flask and SQLAlchemy. I'm trying to create a one to many relationship between two models, here are they: class Stock(db.Model): __tablename__ = 'stocks' id = db.Column(db.Integer, primary_key=True) ... users = db.relationship('User', secondary=user_identifier) historical_prices = db.relationship('HistoricalPrice', backref='stock', lazy=True) class HistoricalPrice(db.Model): __tablename__ = 'historical_prices' id = db.Column(db.Integer, primary_key=True) ... stock_id = db.Column(db.Integer, db.ForeignKey('stock.id'), nullable=False) Please note that there is a relationship between User and Stock which currently works fine. The issue I'm having is between Stock and HistoricalPice. After I have done the migration and update, in my code I have: stock = Stock.query.last() historical = HistoricalPrice(name='Test') stock.historical_prices.append(historical) But then I get the following error: sqlalchemy.exc.NoForeignKeysError: Could not determine join condition between parent/child tables on relationship Stock.historical_prices - there are no foreign keys linking these tables. Ensure that referencing columns are associated with a ForeignKey or ForeignKeyConstraint, or specify a 'primaryjoin' expression. I used the info on this page to create the relationship. What am I missing here?
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52045861
accepted answer: http://stackoverflow.com/a/52045861
score: -1
has title: Issue while adding many to one relationship with Flask, SQLAlchemy
tagged with: sqlalchemy
type: Question
upvote count: 1
answer count: 1
tagged with: flask
tagged with: flask-sqlalchemy
favorite count: 0

http://stackoverflow.com/a/52076092
type: Answer
score: 2
accepted answer of: http://stackoverflow.com/q/52075870
answers question: http://stackoverflow.com/q/52075870
downvote count: 0
has body: Use GroupBy.size with unstack: df1= df.groupby(['Name','Experiment Start','Food']).size().unstack() df1['All'] = df1.sum(axis=1) Or crosstab: df1 = pd.crosstab([df['Name'],df['Experiment Start']], df['Food'], margins=True) df = df.sort_values(by='Time', ascending=False) df = df.drop_duplicates(subset=['Name', 'Experiment Start']) df['Last Meal in Experiment'] = df['Experiment Start'].dt.floor('D') + df['Time'] df = df.join(df1, on=['Name','Experiment Start']) print (df) Name Time Food Experiment Start Last Meal in Experiment \ Index 6 Peter 15:00:00 Nut 2018-08-06 07:30:00 2018-08-06 15:00:00 9 Peter 13:10:00 Nut 2018-08-12 10:30:00 2018-08-12 13:10:00 Cheese Nut Count Index 6 2 5 7 9 1 2 3
type: AcceptedAnswer
upvote count: 2

http://stackoverflow.com/q/52009967
tagged with: for-loop
has comment: http://stackoverflow.com/comment/90975545
has title: Two loops with same variable but different range
answer count: 1
score: 0
tagged with: python
has answer: http://stackoverflow.com/a/52012826
has body: I want to make a program that prints n sections and x_1, x_2,..., x_n subsections for each section in LaTeX. With this I mean that I named a variable numsec, which asks me how many sections I want, easy enough. Then after, a variable numsubsec asks me how many subsections I want. Now the answer to that input ought to be like this: say I want 3 sections, my answer to the subsection has to be a 3 digit number, so that the first digit determines how many subsections should be in the first section and so on. As an example numsec could be 3, and numsubsec could be 101. That means 1 subsec in the 1st sec, 0 subsec in 2nd sec, 1 subsec in 3rd sec. However, I don't know how to make Python print that, exact answer. Here is my code: def sections(numsec, numsubsec): for n, i in range(1, numsec+1), range(0,len(numsubsec)): print("") print("\section{Opgave "+str(n)+"}") print("") print("\subsection{}" * int(numsubsec[i])) def runprogram(): numsec = int(input("How many sections? ")) numsubsec = input("How many subsections? ") sections(numsec,numsubsec) runprogram() EDIT: I solved the issue by using to for loops simultaneously with two variables as such: def sections(numsec, numsubsec): numbers = [] numbers.extend(numsubsec) #Splitting the string numsubsec in to a list of its digits print("") print("Preamble") print("") for n,i in zip(range(1, numsec+1),range(0,numsec)): #zip the ranges print("") print("\section{Opgave "+str(n)+"}") print("") for x in range(int(numsubsec[i])): print("\subsection{}") print("")
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90976182
accepted answer: http://stackoverflow.com/a/52012826
type: Question

http://stackoverflow.com/q/51994134
answer count: 5
has comment: http://stackoverflow.com/comment/90938459
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/90938444
has comment: http://stackoverflow.com/comment/90938848
has answer: http://stackoverflow.com/a/51994268
type: Question
has answer: http://stackoverflow.com/a/51994278
has title: Write an integer or boolean value in text files
has comment: http://stackoverflow.com/comment/90938568
has comment: http://stackoverflow.com/comment/90938331
has answer: http://stackoverflow.com/a/51994172
score: 0
has answer: http://stackoverflow.com/a/51994181
has answer: http://stackoverflow.com/a/51994202
has body: I have this function contained in a class: def new_config(self): dict_dat = {"Display Set": self.main.id[20], "Display Width": self.main.id[4], "Display Height": self.main.id[5], "Fullscreen": self.main.id[9], "Music Volume": self.main.id[11], "Sound Volume": self.main.id[13], "Voice Volume": self.main.id[15], "Ambient Volume": self.main.id[17], "Other Volume": self.main.id[19]} cgo = open(self.path, "w") for name, dat in dict_dat.items(): cgo.write(name + ":" + dat) cgo.close() In the various "self.main.id" contains Integer and Boolean values. I would like to know how I can write in a text file, line by line, the value name (example "Display Set") and the value (self.main.id [20]), without having to convert everything into a string. As I wrote above, I get the error: TypeError: Can't convert 'int' object to str implicitly The fact, however, is that if possible, I would like to write data without having to convert it. With another file I used the Pickle module, but reading the file by opening it manually, it is unreadable for any person, so it makes it useless in this case.
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/90938802

http://stackoverflow.com/a/53217950
has comment: http://stackoverflow.com/comment/93324206
upvote count: 0
answers question: http://stackoverflow.com/q/52007455
has body: msg = _Connection.recv(1024) Change server to msg = _Connection.recv(0) Is a buffer problem, I have same. Try: msg = _Connection.recv(10) And send message from Android to server "1234567890server" The server only show "server".
type: Answer
score: -1
downvote count: 1

http://stackoverflow.com/comment/90952421
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/52001567
score: 0
has text: Is `julian` the list at the start of your question?

http://stackoverflow.com/comment/124513937
type: AnswerComment
type: Comment
has text: This is also something to be aware of when using read_sql_query() : a column name in a table could have leading or trailing spaces. Ugh.
comment on: http://stackoverflow.com/a/69845812
score: 0

http://stackoverflow.com/q/51966798
has answer: http://stackoverflow.com/a/51967117
score: 0
answer count: 1
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/51967117
tagged with: python
has title: Fastest way to check whether a uint16 is in range including wrapping on overflow
type: AnsweredQuestion
has body: I got a range of values from 0 to 65535 (like uint16). The values wrap around if they exceed the boundary, f. e. 65535 + 1 = 0. What is the fastest way to check whether a number x is in a given range(y, y+20)? Where x and y are in the range of values, but y+20 could be wrapped. For example when x = 2 and y = 65533, the return value should be True. I'm using Python3 and try to avoid importing any modules. I got already: def test1(num, min): r = [x % 2**16-1 for x in range(min, min+20)] if num in r: return True return False def test2(num, min): return True if min &lt;= num &lt; min+20 or min &lt;= num+2**16-1 &lt; min+20 else False timeit (one million executions) reports 7.558 s for test1, respectively 1.071 s for test2.
type: Question

http://stackoverflow.com/comment/126323867
type: Comment
comment on: http://stackoverflow.com/a/55474376
has text: i think is call for the first function "setup_method"
type: AnswerComment
score: 0

twilio
tag name: twilio
tags question: http://stackoverflow.com/q/51957429
tags question: http://stackoverflow.com/q/51985401
type: Tag

http://stackoverflow.com/comment/91089722
type: AnswerComment
has text: I broke that line into two lines, and tried to make it more clear. Can you tell what it's doing now?
type: Comment
comment on: http://stackoverflow.com/a/52068094
score: 0

http://stackoverflow.com/comment/91012348
comment on: http://stackoverflow.com/a/52030534
type: Comment
has text: @Divakar I've filtered for values, that differ more than 1e-2 from scipy output. There are hundreds of cases, where `pdist_squareformed_numpy_v2()` returns values around 0.01 (eg. 0.01512599308381024 or 0.010880743067281888, etc...) but scipy returns 0.00. If i lower the treshold to 1e-5 it gets even more error cases. Is there way to increase matrix-mult precision?
score: 0
type: AnswerComment

http://stackoverflow.com/a/52071033
answers question: http://stackoverflow.com/q/52070528
score: 2
accepted answer of: http://stackoverflow.com/q/52070528
downvote count: 0
upvote count: 2
has body: The issue is that you are not keeping a check of nodes already visited. For example you start from a node "S" and then go to its neighbors, you should mark it as visited and do a check while appending to the OPEN list, so that you don't try to come to it again. If you don't do it, your code will get stuck in infinite loop as you will keep on jumping between two nodes. Further, there was some issue in the ADJ that you had created, particularly in '22'. I have tried to make minimal changes to your code(keeping the removed parts as comments), though there are several other places where it can be improved. Corrected code: ADJ = {} """" SRRXG RXRXR RRRXR XRXRR RRRRX """ ADJ['S'] = ['2', '6'] ADJ['2'] = ['S', '3'] ADJ['3'] = ['2','8'] ADJ['G'] = ['10'] ADJ['6'] = ['S', '11'] ADJ['8'] = ['3', '13'] ADJ['10'] = ['G', '15'] ADJ['11'] = ['6', '12'] ADJ['12'] = ['11', '13', '17'] ADJ['13'] = ['8', '12'] ADJ['15'] = ['10', '20'] ADJ['17'] = ['12','22'] ADJ['19'] = ['20', '24'] ADJ['20'] = ['15','19'] ADJ['21'] = ['22'] ADJ['22'] = ['17','21','23'] ADJ['23'] = ['22', '24'] ADJ['24'] = ['19','23'] print (ADJ) # keep track of visited nodes visited = {str(i) : False for i in range(1,26)} visited['S'] = False visited['G'] = False def dls(start, goal): depth = 0 limit = 200 OPEN=[] CLOSED=[] OPEN.append(start) visited["S"] = True while OPEN != []: # Step 2 if depth&lt;=limit: current = OPEN.pop() # visited[current] = False if current == goal: # CLOSED.append(current) print("Goal Node Found") # print(CLOSED) return True else: # CLOSED.append(current) lst = successors(current) for i in lst: # try to visit a node in future, if not already been to it if(not(visited[i])): OPEN.append(i) visited[i] = True depth +=1 else: print("Not found within depth limit") return False return False Further, you can write a function to calculate ADJ given the maze very easily, instead of hard coding it.
type: AcceptedAnswer
type: Answer

http://stackoverflow.com/q/52094264
has title: Python file counter script not working correctly
has comment: http://stackoverflow.com/comment/91142818
answer count: 1
has body: Why does 'cycleNumber' not count above 10? import os cycleNumber = 1 for files in os.listdir('Cycles'): if files.startswith('Cycle' + str(cycleNumber)): cycleNumber += 1
accepted answer: http://stackoverflow.com/a/52094408
favorite count: 0
score: 0
has comment: http://stackoverflow.com/comment/91138673
tagged with: python
has comment: http://stackoverflow.com/comment/95180622
type: AnsweredQuestion
tagged with: file
tagged with: count
upvote count: 1
downvote count: 1
type: Question
has answer: http://stackoverflow.com/a/52094408

http://stackoverflow.com/q/52073767
has answer: http://stackoverflow.com/a/52074050
tagged with: python
has title: Joining tables to a raster attribute table to create new raster with the reclassified values python or R
type: AnsweredQuestion
tagged with: join
tagged with: classification
type: Question
accepted answer: http://stackoverflow.com/a/52074050
tagged with: http://stackoverflow.com/tag/r
score: 0
has body: I'm trying to join a .csv file with a raster classification to create a raster with the new information. The PatchID in the .csv file corresponds to the raster DN. The .csv file looks like: PatchID area shape_index 0 11592800 24.78 1 2556440 7.02 2 3562800 14.70 3 2945450 2.48 4 3892610 6.36 5 7678785680 11.68 6 1756784547 2.43 the Raster can look like: 0 0 0 0 0 0 1 1 1 1 0 0 0 2 2 0 0 1 1 0 0 0 0 0 0 2 2 0 0 0 0 3 3 0 0 2 0 2 0 4 4 0 3 3 0 0 0 0 2 0 0 4 0 0 3 0 5 0 0 0 0 4 4 0 0 0 0 5 5 5 0 0 0 0 0 6 6 the new raster should look like: 24.78 24.78 24.78 24.78 24.78 24.78 7.02 7.02 7.02 7.02 24.78 24.78 24.78 14.70 14.70 24.78 24.78 7.02 7.02 24.78 24.78 24.78 24.78 24.78 24.78 14.70 14.70 24.78 24.78 24.78 24.78 2.48 2.48 24.78 24.78 14.70 24.78 14.70 24.78 6.36 6.36 24.78 2.48 2.48 24.78 24.78 24.78 24.78 14.70 24.78 24.78 6.36 24.78 24.78 2.48 24.78 11.68 24.78 24.78 24.78 24.78 6.36 6.36 24.78 24.78 24.78 24.78 11.68 11.68 11.68 24.78 24.78 24.78 24.78 24.78 2.43 2.43 I can do the job by polygonizing the raster and join the table to the shapefile but this procedure is CPU-intensive.
answer count: 1
tagged with: raster

http://stackoverflow.com/q/51967989
has comment: http://stackoverflow.com/comment/90898018
type: UnansweredQuestion
tagged with: python
answer count: 0
has title: Python path on VS Code on macOS
has comment: http://stackoverflow.com/comment/90937705
type: Question
tagged with: visual-studio-code
has body: I'm configuring VS Code on macOS to work with Python. I installed Python 3.7 and configured everything with the help of the VS Code tutorial. So far it seems to work fine but when I debug some Python code on VS Code Terminal it returns this output: iMacdiVincenzo:hello antedoro$ cd /Users/antedoro/Desktop/hello ; env "PYTHONIOENCODING=UTF-8" "PYTHONUNBUFFERED=1" /Library/Frameworks/Python.framework/Versions/3.7/bin/python3 /Users/antedoro/.vscode/extensions/ms-python.python-2018.7.1/pythonFiles/PythonTools/visualstudio_py_launcher_nodebug.py /Users/antedoro/Desktop/hello 52047 34806ad9-833a-4524-8cd6-18ca4aa74f14 RedirectOutput,RedirectOutput /Users/antedoro/Deskto p/hello/hello.py Hello World I think there is problem with the PATH variable. How I can solve this? Thanks.
has comment: http://stackoverflow.com/comment/91056258
has comment: http://stackoverflow.com/comment/91042898
score: 0
tagged with: python-3.7
tagged with: macos

http://stackoverflow.com/comment/91177138
type: Comment
has text: As I understand from all, the best way to handle it, is only that way. Thank you
type: AnswerComment
comment on: http://stackoverflow.com/a/51974050
score: 0

http://stackoverflow.com/q/51974711
score: 0
has answer: http://stackoverflow.com/a/53533928
tagged with: toolbar
tagged with: mayavi
has comment: http://stackoverflow.com/comment/90937540
type: UnansweredQuestion
tagged with: python
has title: Removing toolbar from mayavi scene
linked to: http://stackoverflow.com/q/15444458
has answer: http://stackoverflow.com/a/58600266
type: Question
answer count: 2
has body: Is it possible to remove/hide the standard toolbar which is created by default when you plot something with mayavi? I found this: How to remove Mayavi toolbar in python using code But I don't understand where I should insert this code. Is there something easier like mlab.toolbar.setVisible(False)?

http://stackoverflow.com/comment/91172343
comment on: http://stackoverflow.com/q/52110428
type: QuestionComment
has text: Here are a couple links from the sklearn documentation on [hyperparameter search](http://scikit-learn.org/stable/modules/grid_search.html) and [cross-validation](http://scikit-learn.org/stable/modules/cross_validation.html#cross-validation). You'll most likely be using sklearn's [GridSearchCV](http://scikit-learn.org/stable/modules/generated/sklearn.model_selection.GridSearchCV.html#sklearn.model_selection.GridSearchCV) which does both the hyperparam tuning and cross validation.
score: 0
type: Comment

http://stackoverflow.com/q/52088966
linked to: http://stackoverflow.com/q/46563004
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91128591
has comment: http://stackoverflow.com/comment/91128115
has comment: http://stackoverflow.com/comment/91128269
upvote count: 10
has comment: http://stackoverflow.com/comment/91128291
downvote count: 1
type: Question
accepted answer: http://stackoverflow.com/a/52089867
tagged with: numpy
score: 9
has comment: http://stackoverflow.com/comment/91129410
has comment: http://stackoverflow.com/comment/91128063
has comment: http://stackoverflow.com/comment/91144139
has body: I need a good algorithm for calculating the point that is closest to a collection of lines in python, preferably by using least squares. I found this post on a python implementation that doesn't work: Finding the centre of multiple lines using least squares approach in Python And I found this resource in Matlab that everyone seems to like... but I'm not sure how to convert it to python: https://www.mathworks.com/matlabcentral/fileexchange/37192-intersection-point-of-lines-in-3d-space I find it hard to believe that someone hasn't already done this... surely this is part of numpy or a standard package, right? I'm probably just not searching for the right terms - but I haven't been able to find it yet. I'd be fine with defining lines by two points each or by a point and a direction. Any help would be greatly appreciated! Here's an example set of points that I'm working with: initial XYZ points for the first set of lines array([[-7.07107037, 7.07106748, 1. ], [-7.34818339, 6.78264559, 1. ], [-7.61352972, 6.48335745, 1. ], [-7.8667115 , 6.17372055, 1. ], [-8.1072994 , 5.85420065, 1. ]]) the angles that belong to the first set of lines [-44.504854, -42.029223, -41.278573, -37.145774, -34.097022] initial XYZ points for the second set of lines array([[ 0., -20. , 1. ], [ 7.99789129e-01, -19.9839984, 1. ], [ 1.59830153e+00, -19.9360366, 1. ], [ 2.39423914e+00, -19.8561769, 1. ], [ 3.18637019e+00, -19.7445510, 1. ]]) the angles that belong to the second set of lines [89.13244, 92.39087, 94.86425, 98.91849, 99.83488] The solution should be the origin or very near it (the data is just a little noisy, which is why the lines don't perfectly intersect at a single point).
possible better answer: http://stackoverflow.com/a/52089698
has comment: http://stackoverflow.com/comment/91128074
has answer: http://stackoverflow.com/a/52089698
has answer: http://stackoverflow.com/a/52102743
answer count: 3
favorite count: 0
has answer: http://stackoverflow.com/a/52089867
tagged with: python
has title: nearest intersection point to many lines in python
has comment: http://stackoverflow.com/comment/91128216

http://stackoverflow.com/a/52010523
has comment: http://stackoverflow.com/comment/90988436
type: Answer
answers question: http://stackoverflow.com/q/51991378
accepted answer of: http://stackoverflow.com/q/51991378
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/90996636
has body: I believe that your problem is more related to threading + GUI, than GTK. As far as I know, when you modify the liststore that is the model for the treeview, the latter should be updated instantly. So, there should be no problem there. A fundamental principle when working with threads and a GUI, is that you should only update the GUI from within its own thread (main loop). So what you need to do, is have your worker thread (serial port connection thread) send the update to the main GUI thread and let it update the treeview. The update can be scheduled with the GLib.idle_add function to let GTK do it when most convenient. Now, to communicate between threads, you could use the queue module. I don't quite understand your code. So I'll write a simple example (using gtk3 PyGObject, since you didn't specify). import threading import queue import gi gi.require_version('Gtk', '3.0') gi.require_version('GLib', '2.0') from gi.repository import Gtk, GLib def do_work(com_queue): # do some work com_queue.put("update for your treeview") # continue class MainGUI(object): def __init__(self): self.com_queue = queue.Queue() self.worker_thread = None self.liststore = None # more gui initialization... def launch_worker_thread(self): self.worker_thread = threading.Thread(target=do_work, args=(self.com_queue,)) self.worker_thread.start() Glib.timeout_add(1000, self.check_queue) # run check_queue every 1 second def check_queue(self): if self.worker_thread.is_alive(): try: update = self.com_queue.get() GLib.idle_add(self.update_treeview, (update,)) # send tuple except queue.Empty: pass return True # to keep timeout running else: return False # to end timeout def update_treeview(self, update): self.liststore.append(update) # here update the treeview model with tuple if __name__ == "__main__": gui = MainGUI() Gtk.main() I hope this helps.
has comment: http://stackoverflow.com/comment/90988551
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/a/52067073
upvote count: 1
score: 1
has body: ***Answering my own question after finding an answer. The best way to do this if you can't download and upload files is to convert the columns of the dataframe into a list and then copy the output of those lists on to a seperate system, where you can then rezip the columns with each other and thereby recreate the dataframe for usage there. Temp = [79.0, 77.4, 76.4, 75.7] (this list could theoretically have any number of values no matter how high) this was converted from the dataframe within the kernel by doing print(df['Temperature (deg F)'].values.tolist()) and the lists can be recopied elsewhere and then converted back into a dataframe by using dataFrame = pd.DataFrame({'Temperature (deg F)': Temp})
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/52048854

http://stackoverflow.com/q/52001964
has answer: http://stackoverflow.com/a/52002090
score: -1
has comment: http://stackoverflow.com/comment/90953422
answer count: 3
has answer: http://stackoverflow.com/a/52002064
upvote count: 0
has comment: http://stackoverflow.com/comment/92070592
has comment: http://stackoverflow.com/comment/92057214
favorite count: 0
has body: def entity_mappings(mapping, entities_list): entity_mapped = [] for (key, value) in mapping.items(): for i in entities_list: if i == key: entity_mapped.append(value) return entity_mapped I want to match the key from the entities list of ids and append the values of the key in the entity mapped list and return it is there any better way to perform this task?? Mapping is a dict.
tagged with: python-3.x
has answer: http://stackoverflow.com/a/52002426
tagged with: python
has comment: http://stackoverflow.com/comment/92081569
has comment: http://stackoverflow.com/comment/92056857
tagged with: dictionary
has comment: http://stackoverflow.com/comment/90953931
has comment: http://stackoverflow.com/comment/90953053
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/52002064
has comment: http://stackoverflow.com/comment/92056954
has comment: http://stackoverflow.com/comment/92048217
downvote count: 1
type: Question
possible better answer: http://stackoverflow.com/a/52002090
has comment: http://stackoverflow.com/comment/90953327
has title: Any better way to perform this task?
has comment: http://stackoverflow.com/comment/90953160

http://stackoverflow.com/q/52083539
has answer: http://stackoverflow.com/a/52083671
type: Question
has comment: http://stackoverflow.com/comment/91117554
linked to: http://stackoverflow.com/q/6666748
answer count: 1
has body: I want to read the inputs line by line for n element and i would want them to be inside a nested list. for 3 elements Input: Anna 1 Hath 2 Nick 3 Expected output [["Anna",1]["Hath",2]["Nick",3]] I planned to run a for loop of n*2 to take the inputs for 6 elements, but every 2 element i wanted to create a list, and all these seperate lists would be a part of a bigger list.
has comment: http://stackoverflow.com/comment/91117649
tagged with: python
favorite count: 0
score: -1
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/91117360
type: UnansweredQuestion
has title: Reading input into nested list
downvote count: 2
upvote count: 1
has comment: http://stackoverflow.com/comment/91117445

http://stackoverflow.com/comment/98201075
comment on: http://stackoverflow.com/a/55757884
type: Comment
score: 1
has text: Upvote for an interesting workaround, but there are two issues with that solution - 1. It doesn't retrieve sensors which have null for last record (e.g. user wants to know which sensors aren't working yet). 2. In my case the serializers are in following order Sensor -> Record. Changing the serializers would break the app for client (mobile) devices. So I would have to manually change the order of objects in python to return them to Sensor -> Record order.
type: AnswerComment

http://stackoverflow.com/comment/91056327
score: 0
type: AnswerComment
has text: hi thanks for answering, if i understood correctly that would be executing the exact same shell script over and over again. Is there a way to slightly manipulate that "some shell script" like, have some slight variation?
type: Comment
comment on: http://stackoverflow.com/a/52053050

http://stackoverflow.com/comment/90876111
type: Comment
type: QuestionComment
has text: @tobias_k : I never use itertools.groupby
comment on: http://stackoverflow.com/q/51962038
score: 0

http://stackoverflow.com/q/52013706
answer count: 3
linked to: http://stackoverflow.com/q/1832940
tagged with: python
possible better answer: http://stackoverflow.com/a/52013732
has answer: http://stackoverflow.com/a/52013757
has body: In Python is it possible to use a string as an operator in an if statement condition? I would like to have an object with two values and an operator to test them. For Example: class Condition: def __init__(self, value1, operator, value2): self.value1 = value1 self.operator = operator self.value2 = value2 def test(self): if self.value1 self.operator self.value2: &lt;- THIS IS NOT CORRECT. return True else: return False condition = Condition(5, "&gt;", 4) if condition.test() == True: print("passed") else: print("failed") Thanks.
type: AnsweredQuestion
tagged with: if-statement
has answer: http://stackoverflow.com/a/52013732
type: Question
has answer: http://stackoverflow.com/a/52013750
accepted answer: http://stackoverflow.com/a/52013750
has title: Python - Using Strings As A Condition Operator In An If Statements
score: 0

http://stackoverflow.com/a/52076411
type: Answer
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/52076109
type: AcceptedAnswer
has body: You must use the .sqrt() method of your decimals: from decimal import * getcontext().prec = 50 pi = 0 PolySides = 6 SideLen = 1 Perim = 6 Dia = 2 while PolySides &lt; 1000000000000: SideLen2 = Decimal(SideLen) / Decimal(2) radius_a = (1 - SideLen2**2).sqrt() radius_b = Decimal(1) - Decimal(radius_a) SideLenNew = (SideLen2**2 + radius_b**2).sqrt() PolyCircum = Decimal(PolySides * SideLen) pi = PolyCircum / Dia print('Polygon Sides:', PolySides, 'Pi = ', pi) SideLen = SideLenNew PolySides = 2 * PolySides Output: Polygon Sides: 824633720832 Pi = 3.1415926535897932384626357839340399511415560167917 has 22 exact decimals.
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52076109

http://stackoverflow.com/comment/90903407
score: 0
type: Comment
has text: Just click on the `Edit` link.
type: QuestionComment
comment on: http://stackoverflow.com/q/51976394

http://stackoverflow.com/a/56195968
has body: You can also use list comprehension to get this data. Example: #!/usr/bin/env python3 import boto3 # Creating the boto client client = boto3.client('ec2') # Get the instance list instance_details = client.describe_instances( InstanceIds=[ instance_id, ], ) # Get all the Instance details from the Reservations # wrapping instances in [] prevents creating a outer list [instances] = [x['Instances']for x in instance_details['Reservations']]
type: Answer
answers question: http://stackoverflow.com/q/52018545
score: 0

http://stackoverflow.com/comment/90886174
comment on: http://stackoverflow.com/q/51967739
has text: I'm confused and I do not understand what you want. Can you please provide what your expectations are given the input you've already provided?
score: 2
type: QuestionComment
type: Comment

http://stackoverflow.com/q/51992844
type: Question
tagged with: python
has comment: http://stackoverflow.com/comment/90935849
tagged with: datetimeindex
has comment: http://stackoverflow.com/comment/90935492
has body: Hi why do I get this error and how do I correct it? File "&lt;ipython-input-451-471e59eff2c7&gt;", line 1, in &lt;module&gt; range(6,31,7) TypeError: 'DatetimeIndex' object is not callable weekend_prime = [] weekends = [] weekday_prime=[] def createWeekendData_Jan(): for dayy in range(6,31,7): #all Sat. and Sun. of Jan. day_str = str(dayy) if(len(day_str)==1): day_str = '0'+day_str for hours in range(1,24): hours_str = str(hours) if(len(hours_str)==1): hours_str = ' 0'+hours_str else: hours_str = ' '+hours_str weekends.append('2018-01-'+day_str+hours_str) createWeekendData_Jan() print(weekends)
score: 0
has title: Not using the datetime module and even then get this, TypeError: 'DatetimeIndex'
answer count: 0
has comment: http://stackoverflow.com/comment/90935427
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90935435

http://stackoverflow.com/a/75371090
downvote count: 1
has body: python3 -m pip is an explicit way of ensuring you will use the pip you intended to use $ pyenv version 3.9.16 (set by /home/lucjan/.pyenv/version) 2.7.18 (set by /home/lucjan/.pyenv/version) $ python3 -m pip --version pip 23.0 from /home/lucjan/.pyenv/versions/3.9.16/lib/python3.9/site-packages/pip (python 3.9) $ python2 -m pip --version pip 19.2.3 from /home/lucjan/.pyenv/versions/2.7.18/lib/python2.7/site-packages/pip (python 2.7) Example of installing a package python3 -m pip install requests If you have trouble making pyenv version return proper versions use pyenv global $ pyenv global 3.9.16 2.7.18 $ pyenv version 3.9.16 (set by /home/lucjan/.pyenv/version) 2.7.18 (set by /home/lucjan/.pyenv/version) The first entry in pyenv global will be the default python version $ pyenv global 3.9.16 2.7.18 $ python --version Python 3.9.16 $ python -m pip --version pip 23.0 from /home/lucjan/.pyenv/versions/3.9.16/lib/python3.9/site-packages/pip (python 3.9)
type: Answer
upvote count: 4
has comment: http://stackoverflow.com/comment/140065806
has comment: http://stackoverflow.com/comment/133086202
score: 3
has comment: http://stackoverflow.com/comment/134866404
answers question: http://stackoverflow.com/q/52060867

http://stackoverflow.com/comment/91229499
comment on: http://stackoverflow.com/q/52098085
score: 0
type: Comment
type: QuestionComment
has text: You can use `rostopic info /topic_name` in a terminal to get details about the topic publishing the message. In this, you will also get the message type. So, you can use `rosmsg show Message_type` and get the description of the message.

http://stackoverflow.com/comment/90886756
type: QuestionComment
comment on: http://stackoverflow.com/q/51968221
has text: If you post this as the answer, I'll mark it as the solution. Jezrael
score: 0
type: Comment

http://stackoverflow.com/comment/91011619
has text: I'd like that in ipython, IDE-independent. The point is to interact with the dataframe, and display it from time to time. I could dump the dataframe into a csv and open it with a spreadsheet software, but that's not what I want here.
comment on: http://stackoverflow.com/q/52029187
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52072181
possible better answer: http://stackoverflow.com/a/52072304
favorite count: 0
tagged with: python
has comment: http://stackoverflow.com/comment/91094135
type: AnsweredQuestion
has body: The function is supposed to take a string like: 'kkikkd' and return a list of the letters and their repetitive values i.e. [[k,2],[i,1],[k,2],[d,1]] but it isn't working. Any ideas? def chnum(xtrr): lis2 = [] for n in xtrr: if lis2[0][0] == n: continue lis1 = [n] for m in xtrr: if n == m: i += 1 lis1 += [i] lis2 += [lis1] return lis2
has answer: http://stackoverflow.com/a/52072304
type: Question
has answer: http://stackoverflow.com/a/52072552
accepted answer: http://stackoverflow.com/a/52072552
score: -1
has answer: http://stackoverflow.com/a/52073266
upvote count: 2
answer count: 3
downvote count: 3
has comment: http://stackoverflow.com/comment/91093959
has title: I was trying to write a letter repetition counting function but it is not working

http://stackoverflow.com/comment/90964023
score: 1
has text: So, k is always no. of unique bins?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52006947

http://stackoverflow.com/a/52067493
has body: One of your dataframes in feature_dfs probably has a non-datetime dtype.
upvote count: 1
answers question: http://stackoverflow.com/q/52067424
score: 1
downvote count: 0
type: Answer

http://stackoverflow.com/q/51962001
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/52038617
tagged with: tensorflow
has comment: http://stackoverflow.com/comment/91316558
type: Question
answer count: 2
tagged with: google-cloud-platform
has comment: http://stackoverflow.com/comment/91200843
downvote count: 0
has comment: http://stackoverflow.com/comment/91141286
has body: I've just started learning tensorflow, and basically I'm learning to do various numerical computations using tensorflow rather than directly jumping into its use in ML. I'm doing this on the Google Cloud Platform, where I came across this problem and got stuck. I'm using lazy evaluation and I can make instances of a0, a1, a2...,a4 in the tensorflow graph using placeholders, also I can write out the function. But how do I make the initial guess using tensorflow? And moreover, even if I get value of x0 how do I apply loop using tf.while_loop I went through its documentation and this post, but I'm still clueless as to how do I proceed. I tried to find a post with similar question or content but couldn't find a one in which tensorflow is used. It would be great if I could get insights or way to use intrinsic tensorflow functions and commands :) Thanks in advance!
score: 4
tagged with: polynomials
favorite count: 0
linked to: http://stackoverflow.com/q/43792961
has title: Finding roots of 4th degree polynomial using tensorflow by Halley's method
tagged with: python
upvote count: 4
has answer: http://stackoverflow.com/a/54739086

http://stackoverflow.com/q/52003858
has title: Add value for key in dictionary which is inside the list in python
has answer: http://stackoverflow.com/a/52003921
accepted answer: http://stackoverflow.com/a/52003921
type: Question
tagged with: http://stackoverflow.com/tag/json
score: 0
answer count: 1
has body: I have to prepare JSON files to send using POST, but I have faced the following format to handle: offer { "location": { "city": "Kharkov", "address": "street" } "dates": [ { "start_date": "2018-10-10 14:00", "end_date": "2018-11-11 14:00" }] } Before it, to set the Value for the city field I used the following implementation: offer['location']['city'] = "Kharkov" But now I can't figure out how to add the value to the key start_date since the dictionary is inside the list.
tagged with: python
tagged with: dictionary
type: AnsweredQuestion
tagged with: list

http://stackoverflow.com/comment/90946739
type: Comment
comment on: http://stackoverflow.com/q/51998631
type: QuestionComment
has text: > You could probably get away with hashing the raw code object's bytes < Maybe, have to test it extensively
score: 0

http://stackoverflow.com/comment/91174765
has text: Think of it this way... if you had a 20gb file and wanted to have a look at it... would you `cat` the file to screen... or would you do `head -10`, `tail -10` or use `less` which can paginate and not try and show you everything at once?
score: 0
type: Comment
comment on: http://stackoverflow.com/q/52111660
type: QuestionComment

http://stackoverflow.com/a/51986322
upvote count: 2
accepted answer of: http://stackoverflow.com/q/51986187
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/51986187
has body: You cannot consume standard input from two distinct processes; they need to receive a copy each. My approach to this would be to write the string to a temporary file and take it from there. In addition, your subprocess calls have a couple of problems. You need to pass in either a string or a list of tokens. What you have looks like it's working, but it's really not well-defined. The cat performs no useful purpose here; the purpose of cat is to combine multiple files, and you only have one file. (It wasn't useful in the shell either.) import tempfile import os with tempfile.TemporaryDirectory() as tmpdirname: fa_tmp = os.path.join([tmpdirname, 'in.fa']) with open(fa_tmp, 'wb') as handle: handle.write(in_fa.encode()) proc = subprocess.run( '''bwa samse reference/C57BL_6J.fa &lt;( bwa aln -l 20 reference/C57BL_6J.fa {0}) {0}'''.format(fa_tmp), shell=True, executable="/bin/bash", check=True, stdout=subprocess.PIPE) See also Running Bash commands in Python where I have an answer which outlines some of the problems you are having in more detail.
type: Answer
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/90923605
has comment: http://stackoverflow.com/comment/90923746

http://stackoverflow.com/comment/90988649
type: Comment
type: QuestionComment
has text: Right... so that's expected? I'm not sure where Interface and your `btn` are related here?
comment on: http://stackoverflow.com/q/52019050
score: 0

http://stackoverflow.com/comment/90982960
comment on: http://stackoverflow.com/a/52014504
type: Comment
has text: @blhsing Seems you are selecting elements with odd indices instead of odd values
score: 0
type: AnswerComment

http://stackoverflow.com/comment/91123285
score: 0
type: AnswerComment
type: Comment
has text: Actually DRF's exceptions automatically return the appropriate status code.
comment on: http://stackoverflow.com/a/52076556

http://stackoverflow.com/q/52081803
type: UnansweredQuestion
score: 1
has body: Trying to figure out how to add line breaks to the todo list in Sphinx.
type: Question
has answer: http://stackoverflow.com/a/52092670
has comment: http://stackoverflow.com/comment/91118907
has title: Preserving line breaks in Sphinx and example todolist
answer count: 2
upvote count: 1
downvote count: 0
favorite count: 0
tagged with: python-sphinx
has answer: http://stackoverflow.com/a/52083684
tagged with: python
tagged with: line-breaks

http://stackoverflow.com/a/52096305
type: AcceptedAnswer
downvote count: 0
upvote count: 8
has comment: http://stackoverflow.com/comment/91142746
type: Answer
has comment: http://stackoverflow.com/comment/91142797
accepted answer of: http://stackoverflow.com/q/52096225
has comment: http://stackoverflow.com/comment/91143016
answers question: http://stackoverflow.com/q/52096225
has body: Via iter and zip: &gt;&gt;&gt; it = iter(list1 + list2) &gt;&gt;&gt; dict(zip(it,it)) {1: 'a', 2: 'b', 3: 'c', 5: 'd', 6: 'e', 7: 'f'}
score: 8
has comment: http://stackoverflow.com/comment/91143049
has comment: http://stackoverflow.com/comment/91142700

http://stackoverflow.com/a/51961000
accepted answer of: http://stackoverflow.com/q/51958626
downvote count: 0
answers question: http://stackoverflow.com/q/51958626
has comment: http://stackoverflow.com/comment/90872331
score: 7
upvote count: 7
type: AcceptedAnswer
has body: This is because QFileDialog uses forward slashes regardless of OS. This makes it easier to write path handling code. You can use os.path.normpath to converts forward slashes to backward slashes in a path on Windows.
type: Answer

http://stackoverflow.com/q/51975416
downvote count: 0
favorite count: 0
score: 1
has answer: http://stackoverflow.com/a/51976391
has answer: http://stackoverflow.com/a/52905405
upvote count: 1
tagged with: python
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/52905405
accepted answer: http://stackoverflow.com/a/51976391
type: Question
has body: So far I've been attempting to create a 2 factor authentication script in python. It works very well now and I wanted to create a gui since this will be running nearly 24/7 on a raspberry pi. TLDR; I don't understand what the docs mean by "stretch. Pass a string describing if rows/columns should stretch, to fill the entire GUI. " #!/usr/bin/env python import pyotp import os import sys import math import time from appJar import gui udstart = 1 app = gui("2FA Keys","480x320") def count(n): while n &gt;= 0: time.sleep(1) n -= 1 if n == 0: return 1 #Keygenertor function pass the base32 code def keyGen(secret): secretcalc = pyotp.TOTP(secret) code = secretcalc.now() Lcode = list(code) Lcode.insert(3, " ") Ocode = ''.join(Lcode) return Ocode #INIT CODES GO HERE CoinbaseCode = keyGen("3JCAJVDGIW4KHUHL") SiaCoinCode = keyGen("PFFO3KKKRQL6ACU5") app.stretch(columns) app.setFont(50) app.addLabel("l2", "Sia Coin: " + SiaCoinCode, 0,0,0,0) app.setLabelbg("l2", "blue") app.addLabel("l1", "Coinbase: " + CoinbaseCode, 1,0,0,0) #Coinbase 2FA app.setLabelBg("l1", "red") while True: if udstart == 1: break else: time.sleep(30) break def update(): #UPDATE CODES GO HERE CoinbaseCode = keyGen("3JCAJVDGIW4KHUHL") #Coinbase SiaCoinCode = keyGen("PFFO3KKKRQL6ACU5") app.setLabel("l2", "Sia Coin: " + SiaCoinCode) app.setLabelBg("l2", "blue") app.setLabel("l1", "Coinbase: " + CoinbaseCode) app.setLabelBg("l1", "red") #profit??? udstart = 0 app.registerEvent(update) app.go() I have no idea what to pass it.
answer count: 2
has title: What are valid appJar stretch function arguments

http://stackoverflow.com/comment/91106750
score: 1
type: Comment
comment on: http://stackoverflow.com/q/52078344
type: QuestionComment
has text: the idea is: operators or functions come first, then the arguments. Just rewrite by putting them into the proper order. Ex: `(+ (angle p1 p2) (- (/ pi 2) (* 2 (atan b))))` => `((angle(p1,p2) + ((pi /2) - (2 * (atan (b))))` (I didn't count the parentheses)

http://stackoverflow.com/q/51970105
favorite count: 0
has answer: http://stackoverflow.com/a/51970202
has title: Pandas: Transform Dataframe into list of Dataframes by adjacent rows
possible better answer: http://stackoverflow.com/a/51970734
tagged with: python
has comment: http://stackoverflow.com/comment/90890747
score: 2
type: AnsweredQuestion
downvote count: 0
type: Question
has answer: http://stackoverflow.com/a/51970734
has body: Convert this dataframe: A B C 0 '1' '2' '3' 1 '1' '4' '5' 2 '2' '6' '7' 3 '2' '8' '9' 4 '1' '0' '1' 5 '2' '2' '3' into this list of dataframes: A B C 0 '1' '2' '3' 1 '1' '4' '5' A B C 2 '2' '6' '7' 3 '2' '8' '9' A B C 4 '1' '0' '1' A B C 5 '2' '2' '3' such that all adjacent rows of the same A group are together in their own dataframe. I've tried various combinations of groupby and drop_duplicates, but these are not dealing with the contiguous nature of the rows. And diff doesn't like strings.
upvote count: 2
answer count: 2
tagged with: pandas-groupby
tagged with: pandas
accepted answer: http://stackoverflow.com/a/51970202

http://stackoverflow.com/a/53626862
type: Answer
score: 6
upvote count: 6
has body: cv2.convexHull returns convex hull as a set of points by default (returnPoints argument is responsible for this, defaulted to True, docs here). But the cv2.convexityDefects function, according to docs, expects 2nd argument to be indices of the contour points that make the hull. So just change hull=cv2.convexHull(sorted_cnts[0]) to hull=cv2.convexHull(sorted_cnts[0], returnPoints=False) so hull will contain indices of original sorted_cnts[0] contour that make the convex hull. BTW, in this case you still can obtain the hull as a set of points by doing sorted_cnts[0][hull].
downvote count: 0
answers question: http://stackoverflow.com/q/52099356
has comment: http://stackoverflow.com/comment/105574139

http://stackoverflow.com/q/52062803
has title: Reading the next line of a text file?
possible better answer: http://stackoverflow.com/a/52062861
has answer: http://stackoverflow.com/a/52062861
favorite count: 0
answer count: 3
has answer: http://stackoverflow.com/a/52062935
tagged with: python-3.x
upvote count: 2
has answer: http://stackoverflow.com/a/52062883
tagged with: python
downvote count: 1
tagged with: line
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/52062935
score: 1
has body: Ok, so I've looked at all the other questions but I'm not really sure on how to apply what I've read to my code, and I'm not really to sure if it would work. So the text file I have looks like this: NeQua,High, ImKol,Moderate, YoTri,Moderate, RoDen,High, and my code is able to read the first line and cut out sections but the moment I add a search request for the second line it comes to an error. So how do I get it to read the next line? This is the code I have so far: def main(): global idin,clientid print("===================") print("=Activity Recorder=") print("===================") clientid=input("Please enter the client ID : ") print("") with open ("clientIntensity.txt") as search: for line in search: if clientid in line: idin=line[6:]#to extract high or moderate from the text idin=idin[:-2] print ("Intensity = ",idin) print("-",idin,"-") acti() break elif clientid not in line: search.next() else: print("Error") main() def acti(): global idin,clientid if idin == "High": print("Activites = Running, Swimming, Aerobics, Football, Tennis") elif idin == " Moderate ": print("Activities = Walking, Hiking, Cleaning, Skateboarding, Basketball") else: print("error 2") I'm not really too sure on how to use the next function works.
has comment: http://stackoverflow.com/comment/91075898
type: Question

http://stackoverflow.com/q/51980087
has answer: http://stackoverflow.com/a/51982439
accepted answer: http://stackoverflow.com/a/51982439
tagged with: python
tagged with: cuda
type: AnsweredQuestion
has body: I am new to python and PYCUDA. In many PYCUDA examples I can find codes like this: import pycuda.driver as cuda cuda.mem_alloc(a.nbytes) But when I take a look into pycuda/driver.py, I can't find where mem_alloc is defined. I can only find mem_alloc_like, which calls mem_alloc(): def mem_alloc_like(ary): return mem_alloc(ary.nbytes) which tells me that mem_alloc must be somewhere in the libraries driver.py imports. However, the following are the imports I find in driver.py, and none of six, numpy, or sys has a function named as "mem_alloc()" from __future__ import absolute_import from __future__ import print_function import six try: from pycuda._driver import * # noqa except ImportError as e: if "_v2" in str(e): from warnings import warn warn("Failed to import the CUDA driver interface, with an error " "message indicating that the version of your CUDA header " "does not match the version of your CUDA driver.") raise import numpy as np import sys
type: Question
has comment: http://stackoverflow.com/comment/90924502
tagged with: pycuda
has title: Where is pycuda.driver.mem_alloc() ? In pycuda/driver.py I can only find mem_alloc_like()
score: 0
answer count: 1

http://stackoverflow.com/comment/90982479
type: AnswerComment
score: 0
type: Comment
has text: Show the stacktrace. If is_valid() is true then selected_student must be present in cleaned_data
comment on: http://stackoverflow.com/a/52015750

http://stackoverflow.com/comment/90976055
has text: Yes, `lxml.etree` is a superset of the ElementTree API. And it's been the main API for using `lxml` since the start, and the only one even mentioned in the tutorials.
type: Comment
score: 1
comment on: http://stackoverflow.com/a/52008111
type: AnswerComment

http://stackoverflow.com/q/52002753
has comment: http://stackoverflow.com/comment/90954982
score: -1
duplicate of: http://stackoverflow.com/q/19913659
downvote count: 2
tagged with: pandas
upvote count: 1
answer count: 1
has comment: http://stackoverflow.com/comment/90955599
favorite count: 0
has body: I am new to Python. Please help me solve below problem. I have a data set (sample data) given below and I want to create a new column called salary_range. Please suggest how can I iterate if else statement over a data frame to create a new column "Salary_range" DataFrame: Name Salary Salary_Range A 10 Low B 8 Low C 21 Medium D 22 Medium A 23 Medium R 25 Medium K 31 High A 33 High L 34 High M 41 Very_High N 44 Very_High
has title: How to iterate if else statement over data frame in Python?
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/90954784
has comment: http://stackoverflow.com/comment/90956288
type: Question
has comment: http://stackoverflow.com/comment/90954568
has answer: http://stackoverflow.com/a/52039827
linked to: http://stackoverflow.com/q/19913659

http://stackoverflow.com/comment/90969791
has text: Could even just be a regular terminal on Linux or something. I see a similar performance difference on my Gnome Terminal on Linux.
comment on: http://stackoverflow.com/q/52009415
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/90893103
has text: thanks! How can I add class id to css selector? I tried something like below: print(response.css('#offerPage h3 a [@class = "notranslate]'))
comment on: http://stackoverflow.com/q/51968013
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/a/51999124
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/51996912
downvote count: 0
answers question: http://stackoverflow.com/q/51996912
has comment: http://stackoverflow.com/comment/90975040
type: Answer
score: 3
has body: As KlausD mentions in his comment, the canonical (and language-agnostic) solution is to use a lock file containing the pid of the running process, so the code responsible for the lock acquisition can check if the process is still running. An alternative solution if you use redis in your project is to store the lock in redis with a TTL that's a bit longer than the worst case runtime of the task. This makes sure the lock will be freed whatever, and also allow to easily share the lock between multiple servers if needed. EDIT: is it possible that the process crashes and another process pick up the same pid? Yes, of course, and that's even rather likely (and this is an understatement) on a server running for month or more without reboot, and even more so if the server runs a lot of short-lived processes. You will not only have to check if there's a running process matching this pid but also get the process stats to inspect the process start time, the command line, the parent etc and decides the likelyhood it's the same process or a new one. Note that this is nothing new - most process monitoring tools face the same problem, so you may want to check how they solved it (gunicorn might be a good starting point here).
upvote count: 3

jepp
tag name: jepp
tags question: http://stackoverflow.com/q/51967191
type: Tag

http://stackoverflow.com/a/52014218
type: Answer
score: 0
has body: That never happened to me. Maybe it will be useful for someone, it worked as soon as specified the headers: headers = {'user-agent' : 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36'} page_html = requests.get(my_sub_url, headers = headers).text
answers question: http://stackoverflow.com/q/52013628

http://stackoverflow.com/q/52029864
tagged with: numpy
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52030327
downvote count: 0
score: 6
favorite count: 0
accepted answer: http://stackoverflow.com/a/52030327
type: Question
has comment: http://stackoverflow.com/comment/91010450
has title: How to vectorize this peak finding for loop in Python?
tagged with: python
upvote count: 6
has comment: http://stackoverflow.com/comment/91010437
has body: Basically I'm writing a peak finding function that needs to be able to beat scipy.argrelextrema in benchmarking. Here is a link to the data I'm using, and the code: https://drive.google.com/open?id=1U-_xQRWPoyUXhQUhFgnM3ByGw-1VImKB If this link expires, the data can be found at dukascopy bank's online historical data downloader. import numpy as np import pandas as pd import matplotlib.pyplot as plt data = pd.read_csv('EUR_USD.csv') data.columns = ['Date', 'open', 'high', 'low', 'close','volume'] data.Date = pd.to_datetime(data.Date, format='%d.%m.%Y %H:%M:%S.%f') data = data.set_index(data.Date) data = data'open', 'high', 'low', 'close' data = data.drop_duplicates(keep=False) price = data.close.values def fft_detect(price, p=0.4): trans = np.fft.rfft(price) trans[round(p*len(trans)):] = 0 inv = np.fft.irfft(trans) dy = np.gradient(inv) peaks_idx = np.where(np.diff(np.sign(dy)) == -2)[0] + 1 valleys_idx = np.where(np.diff(np.sign(dy)) == 2)[0] + 1 patt_idx = list(peaks_idx) + list(valleys_idx) patt_idx.sort() label = [x for x in np.diff(np.sign(dy)) if x != 0] # Look for Better Peaks l = 2 new_inds = [] for i in range(0,len(patt_idx[:-1])): search = np.arange(patt_idx[i]-(l+1),patt_idx[i]+(l+1)) if label[i] == -2: idx = price[search].argmax() elif label[i] == 2: idx = price[search].argmin() new_max = search[idx] new_inds.append(new_max) plt.plot(price) plt.plot(inv) plt.scatter(patt_idx,price[patt_idx]) plt.scatter(new_inds,price[new_inds],c='g') plt.show() return peaks_idx, price[peaks_idx] It basically smoothes data using a fast fourier transform (FFT) then takes the derivative to find the minimum and maximum indices of the smoothed data, then finds the corresponding peaks on the unsmoothed data. Sometimes the peaks it finds are not idea due to some smoothing effects, so I run this for loop to search for higher or lower points for each index between the bounds specified by l. I need help vectorizing this for loop! I have no idea how to do it. Without the for lo…
answer count: 2
possible better answer: http://stackoverflow.com/a/52030303
has answer: http://stackoverflow.com/a/52030303
tagged with: vectorization
has comment: http://stackoverflow.com/comment/91010366
tagged with: scipy
tagged with: signal-processing

http://stackoverflow.com/q/52047289
has body: how to get the value of 'x' out of this equation using python ? 5443984100737085739 * x mod 10512797518085747507 = 7873334411288369657 I've tried inverse function x=inverse((7873334411288369657/5443984100737085739),10512797518085747507) but it gives me x = 0
has comment: http://stackoverflow.com/comment/91089742
has answer: http://stackoverflow.com/a/52047684
score: 0
has comment: http://stackoverflow.com/comment/91045774
has title: how to get variable from modulus equation
answer count: 1
has comment: http://stackoverflow.com/comment/91045874
tagged with: python
has comment: http://stackoverflow.com/comment/91046005
type: AnsweredQuestion
tagged with: math
has comment: http://stackoverflow.com/comment/91045897
accepted answer: http://stackoverflow.com/a/52047684
type: Question

http://stackoverflow.com/q/52053980
has comment: http://stackoverflow.com/comment/91066194
type: Question
has comment: http://stackoverflow.com/comment/91095489
score: 5
has title: Airflow schedule interval with ExternalTaskSensor
tagged with: airflow
has comment: http://stackoverflow.com/comment/91064730
downvote count: 0
has comment: http://stackoverflow.com/comment/91090860
has body: I'm trying to set up airflow with two dags on an interval of "every 30 minutes". The first dag (extract) looks like this: extract_table_user_schema >> extract_table_user_data >> finish_extract_table_user The second dag (transform) looks like this: sensor_wait_for_finish_extract_table_user >> transform_table_user >> finish_transform_table_user For both dags I've set up the schedule_interval to "*/30 * * * *" The ExternalTaskSensor is set up with execution_delta=timedelta(minutes=30) My expected flow of the tasks would be: at first the extract dag is run. Then, after the dummy task finish_tranform_table_user is successful the sensor is triggered and the tasks in transform are run. It just runs fine for the first time, but when I wait for the second run the tasks interrupt themself. I've observed the extract dag being interupted by the transform_table_user task which changes some column names. This results in a failed extract_table_user_data since the column names do not match any more. Edit: to be more specific what are the expected &amp; occurring results First, the rundown what each task is supposed to do: (sql)extract_table_user_schema: copies the schema from the user table (sql)extract_table_user_data: copies data from the source table user into the copy of that table (dummy)finish_extract_table_user: dummy task (sensor)sensor_wait_for_finish_extract_table_user: sensor to wait until the extract is finished (sql)transform_table_user: renames a column field from id to user_id (dummy)finish_transform_table_user: dummy task Now, the first time the dags are run the result is a copied schema + data and a renamed field. All tasks as successful The second time the dags are run, one tasks fails and one task is not run. The other are all successful. The task extract_table_user_data fails with the error message; no such field as id. The task finish_extract_table_user was not run The resulting table was a copied schema but no data and a renamed field. So I assume the task tra…
tagged with: directed-acyclic-graphs
favorite count: 0
answer count: 0
type: UnansweredQuestion
tagged with: python
upvote count: 5

http://stackoverflow.com/q/52038226
type: AnsweredQuestion
tagged with: loops
upvote count: 1
downvote count: 1
type: Question
accepted answer: http://stackoverflow.com/a/52038374
score: 0
has comment: http://stackoverflow.com/comment/91028515
answer count: 1
has comment: http://stackoverflow.com/comment/91027555
has body: To make you understand. I have this loop: for i,v in zip(ps,db): print(i,v) C:\Users\user\Desktop\sa\43001\PST\PST.shp C:\Users\user\Desktop\sa\43001\DBOUND\DBOUND.shp C:\Users\user\Desktop\sa\43003\PST\PST.shp C:\Users\user\Desktop\sa\43003\DBOUND\DBOUND.shp For each export in each iteration I want the exported file to be put in a new folder according to the number in the directory of the files used. Example: Create folder named 43001 that has the PST.shp created of the files from the 43001 directory. Then a folder named 43003 that has the corresponding PST.shp. This code is close to the wanted but needs a fix to create those folders. for i, v in zip(ps,db): db1 = gpd.read_file(v) pst1 = gpd.read_file(i) wdp = gpd.sjoin(pst1, db1, how="left", op='within') o = r'C:\Users\user\Desktop\resultss' out = o +'\\'+i.split("\\")[-3] +'PST.shp' wdp.to_file(out) The problem with this: This code creates the files as 43001PST.shp and 43002PST.shp in the resultss folder instead of creating the folders with the numbers as names with PST.shp in them as it should. What should be changed? The wanted is: resultss&gt;&gt;43001&gt;&gt;PST.shp resultss&gt;&gt;43003&gt;&gt;PST.shp
favorite count: 0
has title: export files through a loop each in a new folder?
has answer: http://stackoverflow.com/a/52038374
tagged with: python

http://stackoverflow.com/comment/91074913
comment on: http://stackoverflow.com/a/52059769
type: Comment
has text: @user1889342 add `%matplotlib inline`
type: AnswerComment
score: 0

http://stackoverflow.com/q/52063964
has comment: http://stackoverflow.com/comment/91078389
favorite count: 0
downvote count: 0
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/52068369
type: Question
linked to: http://stackoverflow.com/q/21553353
score: 1
has answer: http://stackoverflow.com/a/52064069
has body: I am trying to run a Flask app using Docker. Normally, to execute the Flask app, I run this inside of my Terminal: python myapp.py images/* I am unsure of how to convert that to Docker CMD syntax (or if I need to edit ENTRYPOINT). Here is my docker file: RUN apt-get update -y RUN apt-get install -y python-pip python-dev build-essential hdf5-tools COPY . ~/myapp/ WORKDIR ~/myapp/ RUN pip install -r requirements.txt ENTRYPOINT ["python"] CMD ["myapp.py"] Inside of requirements.txt: flask numpy h5py tensorflow keras When I run the docker image: person@person:~/Projects/$ docker run -d -p 5001:5000 myapp 19645b69b68284255940467ffe81adf0e32a8027f3a8d882b7c024a10e60de46 docker ps: Up 24 seconds 0.0.0.0:5001-&gt;5000/tcp hardcore_edison When I got to localhost:5001 I get no response. Is it an issue with my CMD parameter? EDIT: New Dockerfile: RUN apt-get update -y RUN apt-get install -y python-pip python-dev build-essential hdf5-tools COPY . ~/myapp/ WORKDIR ~/myapp/ EXPOSE 5000 RUN pip install -r requirements.txt CMD ["python myapp.py images/*.jpg "] With this new configuration, when I run: docker run -d -p 5001:5000 myapp I get: docker: Error response from daemon: OCI runtime create failed: container_linux.go:348: starting container process caused "exec: \"python myapp.py images/*.jpg \": stat python myapp.py images/*.jpg : no such file or directory": unknown. When I run: docker run -d -p 5001:5000 myapp python myapp.py images/*.jpg I get the Docker image to run, but now when I go to localhost:5001, it complains that the connection was reset.
upvote count: 1
tagged with: flask
linked to: http://stackoverflow.com/q/30323224
tagged with: docker
answer count: 3
has title: What should I put for Docker CMD and ENTRYPOINT for Flask app running "python myapp.py images/*"
tagged with: python
has answer: http://stackoverflow.com/a/52068921

http://stackoverflow.com/comment/91145629
score: 0
type: AnswerComment
type: Comment
has text: Yes. The downside is that you must have an object that [supports weak references](https://docs.python.org/3/extending/newtypes.html#weakref-support).
comment on: http://stackoverflow.com/a/52096694

http://stackoverflow.com/a/52048500
type: AcceptedAnswer
downvote count: 0
type: Answer
score: 2
upvote count: 2
has body: The first only creates another name for the list. It is still the same list. This means mutating newlist also mutates mylist. &gt;&gt;&gt; mylist = [1, 2, 3] &gt;&gt;&gt; newlist = mylist &gt;&gt;&gt; newlist.append(4) &gt;&gt;&gt; mylist [1, 2, 3, 4] The second example actually creates a copy of the list, an actual new list. &gt;&gt;&gt; mylist = [1, 2, 3] &gt;&gt;&gt; newlist = mylist[:] &gt;&gt;&gt; newlist.append(4) &gt;&gt;&gt; newlist [1, 2, 3, 4] &gt;&gt;&gt; mylist [1, 2, 3] You have little reason to have two names for the same object as this can be both confusing and lead to mutation bugs. A mutation bug is when some object is needed in some part of your code, say a function func1, but mutated beforehand by some other part of your code, say a function func2. If the object in its initial state was expected by func1, it can be very tedious to track down where the mutation happened. Example: obj = [list of data] same_obj = obj func2(same_obj) # mutates the object # hundreds of lines of code func1(obj) # needs the initial state of the object In the above example, it would have been better to pass func2 a copy of obj. Since a lot happen between the first and last lines, it can be very tedious to track down the mutation bug.
accepted answer of: http://stackoverflow.com/q/52048454
answers question: http://stackoverflow.com/q/52048454

http://stackoverflow.com/a/51963696
downvote count: 0
has body: These files are generated by Cython. Try upgrading Cython to the version that supports your Python and regenerate files. (Cython >= 0.27.3 for Python 3.7) EDIT: This thread recommends installing pyproj by pointing to the git repo of pyproj. pipenv install cython pipenv install git+https://github.com/jswhit/pyproj.git#egg=pyproj By installing from Git, Cython will recompile necessary c files.
answers question: http://stackoverflow.com/q/51963619
type: Answer
upvote count: 6
has comment: http://stackoverflow.com/comment/90912594
score: 6

http://stackoverflow.com/q/52058886
has title: Visual Studio code with PyLint and autoPep8: How can I avoid PyLint to complain about my line length?
tagged with: visual-studio-code
tagged with: linter
has answer: http://stackoverflow.com/a/64817582
has comment: http://stackoverflow.com/comment/110460762
downvote count: 0
answer count: 7
has answer: http://stackoverflow.com/a/75825695
has answer: http://stackoverflow.com/a/52062434
has body: I recently switched to Visual Studio Code and I have to say I love it so far. I'm working on a Python project, which includes the pip packages pylint and autopep8 and I configured VSCode to format the code according to these packages. Only problem is: In the Python project I'm working on the line length is 100. So all my code looks like this: The error says: E501:line too long (97 &gt; 79 characters). Here are my VSCode settings: { "python.pythonPath": "~/.envs/myProject/bin/python", "python.linting.pep8Enabled": true, "python.linting.pylintPath": "~/.envs/myProject/bin/pylint", "python.linting.pylintArgs": ["--load-plugins", "pylint_django", "--max-line-length=100"], "python.formatting.autopep8Args": ["--max-line-length=100"], "python.linting.pylintEnabled": true, "files.exclude": { "**/.git": true, "**/.svn": true, "**/.hg": true, "**/CVS": true, "**/.DS_Store": true, ".vscode": true, "**/*.pyc": true } } These settings at least now ensure that format on save keeps the lines at 100 max and does not wrap all my files lines to 79. Still it would be awesome without the warnings. How do I disable these linter warnings?
tagged with: autopep8
favorite count: 0
has answer: http://stackoverflow.com/a/62994200
has answer: http://stackoverflow.com/a/69257772
accepted answer: http://stackoverflow.com/a/52062434
tagged with: pylint
tagged with: python
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/69682412
has answer: http://stackoverflow.com/a/69682412
score: 44
upvote count: 44
has answer: http://stackoverflow.com/a/77580661
type: Question

http://stackoverflow.com/a/51988487
type: Answer
answers question: http://stackoverflow.com/q/51987997
upvote count: 2
score: 2
has comment: http://stackoverflow.com/comment/90926701
has comment: http://stackoverflow.com/comment/90926593
downvote count: 0
has body: Another possible solution would be to use seaborn import seaborn as sns ax = sns.lineplot(x="Week", y="Visits", hue="Campaign", estimator=None, lw=1, data=df) The documentation is here

http://stackoverflow.com/comment/90970625
score: 0
has text: Fair on `\b`. You can drop the `$` to match `foobar` followed by a period, but given the lack of detail in OPs question, it's out of scope whether that case is matched or not.
comment on: http://stackoverflow.com/a/52009518
type: AnswerComment
type: Comment

http://stackoverflow.com/a/52018807
answers question: http://stackoverflow.com/q/52018724
has body: Because it checks if the string is empty: Empty return False Not Empty return True
score: 1
upvote count: 1
type: Answer
downvote count: 0

http://stackoverflow.com/a/52052729
upvote count: 6
has comment: http://stackoverflow.com/comment/98762840
has body: Use OUTPUT for this: I would not use triggers for this, to much activity in the trigger would result in undesired things happening when other changes occur. Instead I am using a stored procedure I rewrote my answer after the question was changed: -- create test tables and test data CREATE table item (ID int identity, Col varchar(99), ColOther varchar(99), Latest bit default 1, Time datetime default getdate()) INSERT item(col, colother) values('old','oldother') CREATE table product (ID int identity, ItemID int, [Value] varchar(20), ValueOther varchar(20), Latest bit default 1, Time datetime default getdate()) INSERT product(itemid, [value], valueother) values(1, 'foo', 'bar') go -- create procedure CREATE procedure p_insert ( @id int, @col varchar(99), @colOther varchar(99) ) as BEGIN tran t DECLARE @out table(IDold int, IDnew int) INSERT item(col, colother, Latest) OUTPUT @id, inserted.id INTO @out SELECT @col, @colother, 1 FROM item WHERE id = @id and latest = 1 UPDATE i SET Latest=0 FROM item i JOIN @out o ON o.IDold = i.id and i.Latest=1 DECLARE @p table (itemid int, [value] varchar(20), valueother varchar(20)) UPDATE p SET Latest=0 OUTPUT o.IDnew, deleted.[value],deleted.[valueother] INTO @p FROM product p JOIN @out o ON p.ItemID = o.IDold WHERE p.Latest=1 INSERT product(itemid, [value], valueother, Latest) SELECT itemid, value, valueother, 1 FROM @p commit tran t To test this: exec p_insert 1, 'a','b' Note this will only work if you try to update the existing row where Latest=1.
answers question: http://stackoverflow.com/q/52052296
has comment: http://stackoverflow.com/comment/98762736
has comment: http://stackoverflow.com/comment/98762967
downvote count: 0
has comment: http://stackoverflow.com/comment/98762084
has comment: http://stackoverflow.com/comment/98762107
type: Answer
score: 6
has comment: http://stackoverflow.com/comment/98677764

http://stackoverflow.com/a/51980918
score: 8
has body: In pytorch you can always implement your own layers, by making them subclasses of nn.Module. You can also have trainable parameters in your layer, by using nn.Parameter. Possible implementation of such layer might look like import torch from torch import nn class TrainableEltwiseLayer(nn.Module): def __init__(self, n, h, w): super(TrainableEltwiseLayer, self).__init__() self.weights = nn.Parameter(torch.Tensor(1, n, h, w)) # define the trainable parameter def forward(self, x): # assuming x is of size b-n-h-w return x * self.weights # element-wise multiplication You still need to worry about initializing the weights. look into nn.init on ways to init weights. Usually, one init the weights of all the net prior to training and prior to loading any stored model (so partially trained models can override random init). Something like model = mymodel(*args, **kwargs) # instantiate a model for m in model.modules(): if isinstance(m, nn.Conv2d): nn.init.normal_(m.weights.data) # init for conv layers if isinstance(m, TrainableEltwiseLayer): nn.init.constant_(m.weights.data, 1) # init your weights here...
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51980654
upvote count: 8
answers question: http://stackoverflow.com/q/51980654
type: AcceptedAnswer
type: Answer

http://stackoverflow.com/q/52013465
downvote count: 0
tagged with: instagram-api
tagged with: instagram
has answer: http://stackoverflow.com/a/53445099
favorite count: 0
tagged with: python-3.x
upvote count: 2
tagged with: python
accepted answer: http://stackoverflow.com/a/53445099
type: AnsweredQuestion
has title: What is the purpose of the header element 'x-instagram-ajax' in API calls via Python to Instagram?
has body: On the instagram login page, if one inspects the element of the POST call for the url 'https://www.instagram.com/accounts/web_create_ajax/', it lists the following as headers: Host: www.instagram.com User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.13; rv:61.0) Gecko/20100101 Firefox/61.0 Accept: */* Accept-Language: en-US,en;q=0.5 Accept-Encoding: gzip, deflate, br Referer: https://www.instagram.com/ X-CSRFToken: 7dmO9F3JuVGvSXumd79yByPxnHoWHz1A X-Instagram-AJAX: c2d8f4380025 Content-Type: application/x-www-form-urlencoded X-Requested-With: XMLHttpRequest Content-Length: 102 Cookie: csrftoken=7dmO9F3JuVGvSXumd79yByPxnHoWHz1A; mid=W30zsQAEAAErXHJ3iUojfTceCd53; mcd=3; csrftoken=7dmO9F3JuVGvSXumd79yByPxnHoWHz1A; rur=FTW Connection: keep-alive I am wondering if anyone would have any idea what X-Instagram-AJAX is and how I can generate it each time. Is it connected as a pair with X-CSRFToken? Thanks.
type: Question
score: 2
answer count: 1

keras-layer
tags question: http://stackoverflow.com/q/52089601
tags question: http://stackoverflow.com/q/52042199
tags question: http://stackoverflow.com/q/52012252
type: Tag
tag name: keras-layer
tags question: http://stackoverflow.com/q/52009468

http://stackoverflow.com/a/52007358
type: Answer
has body: So, the solution I have found is as follows (for autocorrect package); import autocorrect as ac.word.LOWERCASE.update({'zumba'}) ac.word.MIXED_CASE.update({'Zumba'}) I got to this simply by iterating through the module attributes; dir(ac.word.LOWERCASE) Sorted!
downvote count: 0
score: 1
accepted answer of: http://stackoverflow.com/q/52006711
answers question: http://stackoverflow.com/q/52006711
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/121327807
upvote count: 1

http://stackoverflow.com/a/52068681
type: Answer
answers question: http://stackoverflow.com/q/52068630
score: 2
downvote count: 0
has body: This exception SystemExit(1) means that the code executed fine until it reached a sys.exit(1). Now, there are multiple sys.exit(1) in your code. To know which one the code reached you have to examine the output or maybe run the code in a debugger like winpdb
upvote count: 2

http://stackoverflow.com/q/52077984
tagged with: rabbitmq
tagged with: celery
has body: Basically, I have flask app which is hosted on Azure instance. when I post some data at API endpoint celery start a process in background and API send a response immediately to the client. here is tasks.py basic sample: from celery import Celery app = Celery('tasks', broker ='amqp://localhost//') @app.task def reverse(main): return main[::-1] Error: Basic flask Example: from flask import Flask from flask import request from tasks import * app = Flask(__name__) @app.route('/params',methods =['POST']) def get_url(): main = request.args.get('main') reverse.delay(main) return main if __name__ == "__main__": app.run() again, flask app is running on azure instance. do I have change localhost to a IP in tasks.py
type: Question
has comment: http://stackoverflow.com/comment/91136875
score: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/91110369
tagged with: flask
linked to: http://stackoverflow.com/q/9769496
has comment: http://stackoverflow.com/comment/91126356
has title: Error in celery while requesting API endpoint(flask app)
tagged with: python
favorite count: 0
has comment: http://stackoverflow.com/comment/91107654
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91111164
upvote count: 1

http://stackoverflow.com/q/52093388
has comment: http://stackoverflow.com/comment/91140061
has comment: http://stackoverflow.com/comment/91137332
has answer: http://stackoverflow.com/a/60258525
type: AnsweredQuestion
has title: How to choose optimal threshold for class probabilities?
tagged with: machine-learning
has comment: http://stackoverflow.com/comment/91138285
type: Question
score: 5
tagged with: neural-network
upvote count: 6
has comment: http://stackoverflow.com/comment/91139613
has comment: http://stackoverflow.com/comment/91139699
possible better answer: http://stackoverflow.com/a/60258525
has comment: http://stackoverflow.com/comment/91138909
answer count: 3
downvote count: 1
has answer: http://stackoverflow.com/a/52093565
tagged with: scikit-learn
has body: My output of neural network is table of predicted class probabilities for multi-label classification: print(probabilities) | | 1 | 3 | ... | 8354 | 8356 | 8357 | |---|--------------|--------------|-----|--------------|--------------|--------------| | 0 | 2.442745e-05 | 5.952136e-06 | ... | 4.254002e-06 | 1.894523e-05 | 1.033957e-05 | | 1 | 7.685694e-05 | 3.252202e-06 | ... | 3.617730e-06 | 1.613792e-05 | 7.356643e-06 | | 2 | 2.296657e-06 | 4.859554e-06 | ... | 9.934525e-06 | 9.244772e-06 | 1.377618e-05 | | 3 | 5.163169e-04 | 1.044035e-04 | ... | 1.435158e-04 | 2.807420e-04 | 2.346930e-04 | | 4 | 2.484626e-06 | 2.074290e-06 | ... | 9.958628e-06 | 6.002510e-06 | 8.434519e-06 | | 5 | 1.297477e-03 | 2.211737e-04 | ... | 1.881772e-04 | 3.171079e-04 | 3.228884e-04 | I converted it to class labels using a threshold (0.2) for measuring accuraccy of my prediction: predictions = (probabilities &gt; 0.2).astype(np.int) print(predictions) | | 1 | 3 | ... | 8354 | 8356 | 8357 | |---|---|---|-----|------|------|------| | 0 | 0 | 0 | ... | 0 | 0 | 0 | | 1 | 0 | 0 | ... | 0 | 0 | 0 | | 2 | 0 | 0 | ... | 0 | 0 | 0 | | 3 | 0 | 0 | ... | 0 | 0 | 0 | | 4 | 0 | 0 | ... | 0 | 0 | 0 | | 5 | 0 | 0 | ... | 0 | 0 | 0 | Also I have a test set: print(Y_test) | | 1 | 3 | ... | 8354 | 8356 | 8357 | |---|---|---|-----|------|------|------| | 0 | 0 | 0 | ... | 0 | 0 | 0 | | 1 | 0 | 0 | ... | 0 | 0 | 0 | | 2 | 0 | 0 | ... | 0 | 0 | 0 | | 3 | 0 | 0 | ... | 0 | 0 | 0 | | 4 | 0 | 0 | ... | 0 | 0 | 0 | | 5 | 0 | 0 | ... | 0 | 0 | 0 | Question: How to build an algorithm in Python that will choose the optimal threshold that maximize roc_auc_score(average = 'micro') or another metrics? Maybe it is possible to build manual function in Python that optimize threshold, depending on the accuracy metric.
favorite count: 0
has comment: http://stackoverflow.com/comment/91137230
has comment: http://stackoverflow.com/comment/91138160
tagged with: python
has answer: http://stackoverflow.com/a/52094705
accepted answer: http://stackoverflow.com/a/52094705

http://stackoverflow.com/comment/91056887
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52053204
score: 1
has text: Assignment statements always make a variable *local* unless you use `global` or `nonlocal`, it doesn't matter if the assignment is inaccesible at rutime. This happens at *compile time*.

http://stackoverflow.com/comment/91031623
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52040483
has text: No need to put a comma after after print() and this line with "..., end=' ' " works properly. The problem is in the second line where input() needs you to press enter, which will add the new line and I need a way to go cursor to the previous line and then printing.

http://stackoverflow.com/q/52034477
type: Question
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52034548
score: 0
tagged with: pandas
answer count: 1
has body: There is a dataframe with a list of bus stop ids and the hub is 'none'. I need to update the dataframe such that - if the bus stop id is in the list a_ids then its corresponding hub should be a, if in b_ids then hub=b and so on. a = pd.DataFrame(({'stop' : ['10388','10382','10383','10387','10389','25568'],'hub' : ['none', 'none', 'none', 'none', 'none', 'none']})) a_ids = ['10388','10382','10383'] b_ids = ['10387','10389','25568','10381'] a I have tried: a[(a.stop.isin(a_ids)),'hub'] = 'a' I understand my approach is flawed; Any help appreciated.
tagged with: python
accepted answer: http://stackoverflow.com/a/52034548
has title: Python: Update column X value if the value of column Y is in a list L of possible values

http://stackoverflow.com/a/52104907
has comment: http://stackoverflow.com/comment/91160894
accepted answer of: http://stackoverflow.com/q/52104841
type: AcceptedAnswer
type: Answer
has body: This question isn't related to Python. I think you need to read an intro to bootstrapping. "An Introduciton to Statistical Learning" provides a good one. The idea is not to sample 100 -- you must sample with replacement and taking the same sample size (500). Yes, then you reestimate your parameter many times. And then there's several ways of taking all of these estimates and turning them into a confidence interval. For example, you can use them to estimate the standard error (the standard deviation of the sampling distribution), and then use +/- 2*se.
upvote count: 4
downvote count: 0
answers question: http://stackoverflow.com/q/52104841
score: 4

http://stackoverflow.com/comment/90986550
type: QuestionComment
has text: I suggest you post a minimal informative example of input and output, and remove any code which people don't need to know about.
comment on: http://stackoverflow.com/q/52018014
score: 0
type: Comment

http://stackoverflow.com/comment/90999113
comment on: http://stackoverflow.com/a/52023882
score: 0
type: AnswerComment
type: Comment
has text: Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/178783/discussion-between-argo-and-dev-patel).

http://stackoverflow.com/comment/91039867
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52044522
has text: Just put this as an edit to my answer (will delete). But clearly this is the way to go!

http://stackoverflow.com/a/53091322
has comment: http://stackoverflow.com/comment/104553077
score: 0
type: Answer
upvote count: 3
downvote count: 3
has body: Use conda search python to select the version of python you want to downgrade to then use something like conda install python=3.6.0 if you want to downgrade to 3.6.0
answers question: http://stackoverflow.com/q/52072588

http://stackoverflow.com/comment/90957762
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52002648
score: 1
has text: I have tried the PIL approach but it gives me "OSError: cannot find loader for this WMF file". Is it working for you?

http://stackoverflow.com/q/52094821
has body: I'm following the Wagtail documentation to customize the user model. I want to add an image to the user model. Django version: 2.0.8, Wagtail version: 2.1 Problem After choosing an image with the image chooser field and clicking 'Save', this error shows up: 'No file was submitted. Check the encoding type on the form.' Code models.py from django.db import models from django.contrib.auth.models import AbstractUser class User(AbstractUser): display_image = models.ForeignKey('wagtailimages.Image', null=True, blank=True, on_delete=models.SET_NULL, related_name='+') forms.py from django import forms from django.utils.translation import ugettext_lazy as _ from wagtail.users.forms import UserEditForm, UserCreationForm from wagtail.images.widgets import AdminImageChooser class CustomUserEditForm(UserEditForm): display_image = forms.ImageField( widget=AdminImageChooser(), label=_('Autorenbild')) class CustomUserCreationForm(UserCreationForm): display_image = forms.ImageField( widget=AdminImageChooser(), label=_('Autorenbild'))} edit.html {% extends "wagtailusers/users/edit.html" %} {% block extra_fields %} {% include "wagtailadmin/shared/field_as_li.html" with field=form.display_image %} {% endblock extra_fields %} {% block extra_js %} {{ block.super }} {% include 'wagtailadmin/pages/_editor_js.html' %} {% endblock extra_js %} create.html similar What I've tried so far The idea to use the AdminImageChooser widget I found here. I had to adjust the forms by adding an forms.ImageField so that the User page displays without error. Questions Anyone know why the error occurs and how to fix it? As stated in the above Google group thread, it seems as adding an image to the user model is 'a bit awkward'. What is a better approach to have an image connected to an user for repetitive usage in a site? A requirement is that the image can be easily changed in Wagtail admin. Other problem with Wagtail version 2.2 In Settings > User in the admin interface, the window of the AdminImageChooser…
score: 6
tagged with: django
has comment: http://stackoverflow.com/comment/91258990
has comment: http://stackoverflow.com/comment/91221616
has answer: http://stackoverflow.com/a/62775355
has answer: http://stackoverflow.com/a/52578186
type: Question
tagged with: wagtail
tagged with: django-custom-user
downvote count: 0
has answer: http://stackoverflow.com/a/69208091
has answer: http://stackoverflow.com/a/57221457
has comment: http://stackoverflow.com/comment/91246673
favorite count: 0
tagged with: python
upvote count: 6
answer count: 4
has title: Wagtail: Add image to custom user model
has comment: http://stackoverflow.com/comment/91259135
type: UnansweredQuestion

http://stackoverflow.com/a/52004625
upvote count: 6
has comment: http://stackoverflow.com/comment/90960875
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/90959326
type: Answer
has comment: http://stackoverflow.com/comment/90959374
downvote count: 0
score: 6
has body: Maybe: label_sums = df.Value.groupby(df.Label).transform(sum) df["new_sum"] = label_sums.where(np.sign(label_sums) == np.sign(df.Value), 0) which gives me In [42]: df Out[42]: Label Offset Value new_sum 0 L1 False 100 100 1 L2 False 100 100 2 L3 False 50 0 3 L3 True -100 -50 4 L4 False 100 100 5 L5 False 100 100 6 L6 False 100 50 7 L6 True -50 0
answers question: http://stackoverflow.com/q/52003960
accepted answer of: http://stackoverflow.com/q/52003960

http://stackoverflow.com/a/52039875
has body: You need to put the variable cells inside the brackets of the len() method. Since you have cells==9 inside the brackets the if statement is trying to find the length of a variable named 'cells==9' with no arguments. It should look like this if len(cells) == 9:
type: Answer
answers question: http://stackoverflow.com/q/52039637
score: 0

http://stackoverflow.com/a/52057731
score: 3
upvote count: 3
has body: You can try to merge all images together by copying them into one black frame. Here is an example with the same image in all 4 places: import cv2 import numpy as np #loads images and gets data img = cv2.imread("img.png") h,w,_ = img.shape # creates the resulting image with double the size and 3 channels output = np.zeros((h * 2, w * 2, 3), dtype="uint8") # copies the image to the top left output[0:h, 0:w] = img # copies the image to the top right output[0:h, w:w * 2] = img # copies the image to the bottom left output[h:h * 2, w:w * 2] = img # copies the image to the bottom right output[h:h * 2, 0:w] = img You can always change the img to something different. Also you can concatenate them like this: top = np.hstack((img, img)) bottom = np.hstack((img, img)) result = np.vstack((top, bottom)) And the result will be the same. Here as sample of the resulting img with this code: However your image is a little bit different, you will need a rotation and is not exactly concatenation, but the copying one. An example of this follows: # creates the resulting image with double the size and 3 channels output = np.zeros((w+h+h , w + h + h, 3), dtype="uint8") # top img output[0:h, h:h+w] = img # left img (rotated 90°) output[h:h+w, 0:h] = np.rot90(img,1) # right img (rotated 270°) output[h:h + w, h + w:h +w +h] = np.rot90(img,3) # bottom img (rotated 180°) output[h+w:h+w+h, h:h+w] = np.rot90(img,2) and the result is like this: If you use your image with the black background you will get more or less what you have there. You would need to play maybe with the copying parameters, but basically you do something like: imgToCopyTo[y1:y2, x1:x2] = imgToCopyFrom Where y1 and x1 is your top left coordinates where you want to start the copy and y2 and x2 are your bottom right coordinates of where you want to copy to. Also y2-y1 should have the height of the imgToCopyFrom x2-x1 the width (it can be bigger than the width or height but not smaller).
has comment: http://stackoverflow.com/comment/91558488
has comment: http://stackoverflow.com/comment/91102733
has comment: http://stackoverflow.com/comment/91103146
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/52052480
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52052480
type: Answer

http://stackoverflow.com/comment/90866499
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51957955
score: 0
has text: @eyllanesc: Thank you for your answer. Now I got the name of the object but whatever the button clicked, it only returns the name of the last button added.

django
tags question: http://stackoverflow.com/q/52067828
tags question: http://stackoverflow.com/q/52031799
tags question: http://stackoverflow.com/q/52101451
tags question: http://stackoverflow.com/q/52028943
tags question: http://stackoverflow.com/q/52014962
tags question: http://stackoverflow.com/q/52104746
tags question: http://stackoverflow.com/q/52082682
tags question: http://stackoverflow.com/q/52047986
tags question: http://stackoverflow.com/q/51958739
tags question: http://stackoverflow.com/q/51983749
tags question: http://stackoverflow.com/q/52063027
tags question: http://stackoverflow.com/q/52107184
tags question: http://stackoverflow.com/q/52054905
tags question: http://stackoverflow.com/q/51987936
tags question: http://stackoverflow.com/q/52083931
tags question: http://stackoverflow.com/q/51966356
tags question: http://stackoverflow.com/q/52094075
tags question: http://stackoverflow.com/q/51972291
tags question: http://stackoverflow.com/q/52050191
tags question: http://stackoverflow.com/q/52041430
tags question: http://stackoverflow.com/q/52081776
tags question: http://stackoverflow.com/q/52101700
tags question: http://stackoverflow.com/q/52094644
tags question: http://stackoverflow.com/q/52062691
tags question: http://stackoverflow.com/q/52001533
tags question: http://stackoverflow.com/q/52034075
tags question: http://stackoverflow.com/q/51984225
tags question: http://stackoverflow.com/q/52048778
tags question: http://stackoverflow.com/q/52073874
tags question: http://stackoverflow.com/q/52073187
tags question: http://stackoverflow.com/q/52034214
tags question: http://stackoverflow.com/q/51958718
tags question: http://stackoverflow.com/q/52101240
tags question: http://stackoverflow.com/q/51989415
tags question: http://stackoverflow.com/q/52064821
tags question: http://stackoverflow.com/q/52054686
tags question: http://stackoverflow.com/q/52075131
tags question: http://stackoverflow.com/q/52004910
tags question: http://stackoverflow.com/q/52087698
tags question: http://stackoverflow.com/q/52005877
tags question: http://stackoverflow.com/q/52055169
tags question: http://stackoverflow.com/q/52020929
tags question: http://stackoverflow.com/q/52064512
tags question: http://stackoverflow.com/q/52085600
tags question: http://stackoverflow.com/q/52063491
tags question: http://stackoverflow.com/q/52037564
tags question: http://stackoverflow.com/q/52109861
tags question: http://stackoverflow.com/q/52104679
tags question: http://stackoverflow.com/q/52065520
tags question: http://stackoverflow.com/q/52020713
type: Tag
tags question: http://stackoverflow.com/q/52006122
tags question: http://stackoverflow.com/q/52101331
tags question: http://stackoverflow.com/q/52027225
tags question: http://stackoverflow.com/q/51997403
tags question: http://stackoverflow.com/q/52065046
tags question: http://stackoverflow.com/q/52081773
tags question: http://stackoverflow.com/q/52106750
tags question: http://stackoverflow.com/q/51986060
tags question: http://stackoverflow.com/q/52108846
tags question: http://stackoverflow.com/q/52056526
tags question: http://stackoverflow.com/q/51961999
tags question: http://stackoverflow.com/q/51959738
tags question: http://stackoverflow.com/q/52009318
tags question: http://stackoverflow.com/q/52029805
tags question: http://stackoverflow.com/q/52026815
tags question: http://stackoverflow.com/q/52071040
tags question: http://stackoverflow.com/q/51979586
tags question: http://stackoverflow.com/q/52035050
tags question: http://stackoverflow.com/q/52073538
tags question: http://stackoverflow.com/q/52107264
tags question: http://stackoverflow.com/q/52100914
tags question: http://stackoverflow.com/q/51992061
tags question: http://stackoverflow.com/q/51989857
tags question: http://stackoverflow.com/q/52022436
tags question: http://stackoverflow.com/q/51962003
tags question: http://stackoverflow.com/q/52026330
tags question: http://stackoverflow.com/q/51976579
tags question: http://stackoverflow.com/q/52100035
tags question: http://stackoverflow.com/q/52097001

http://stackoverflow.com/comment/90966415
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52007314
has text: I'm doing the same. This should be linear by length of `vals`. My initial approach is the fastest when I apply Numba's `njit`. I'll show it. I wanted an O(n) Numpy approach. This does come close.
score: 0

http://stackoverflow.com/q/52007396
tagged with: scikit-learn
tagged with: xgboost
answer count: 1
has body: Although I have been using Python for a while, I am relatively new to Anaconda, and package handling in general seems to cause a lot of problems for me. I am trying to get xgboost up and running with Anaconda. I eventually managed to install it by using the command: conda install -c anaconda py-xgboost in the Anaconda prompt. When I now try import xgboost in the PyCharm Python Console, I am given the following error: Python 2.7.15 |Anaconda 2.5.0 (64-bit)| (default, May 1 2018, 18:37:09) [MSC v.1500 64 bit (AMD64)] on win32 Backend Qt5Agg is interactive backend. Turning interactive mode on. Traceback (most recent call last): File "&lt;input&gt;", line 1, in &lt;module&gt; File "C:\Program Files (x86)\JetBrains\PyCharm Community Edition 5.0.4\helpers\pydev\pydev_import_hook.py", line 21, in do_import module = self._system_import(name, *args, **kwargs) File "C:\Users\Richard\Anaconda2\lib\site-packages\xgboost\__init__.py", line 11, in &lt;module&gt; from .core import DMatrix, Booster File "C:\Program Files (x86)\JetBrains\PyCharm Community Edition 5.0.4\helpers\pydev\pydev_import_hook.py", line 21, in do_import module = self._system_import(name, *args, **kwargs) File "C:\Users\Richard\Anaconda2\lib\site-packages\xgboost\core.py", line 115, in &lt;module&gt; _LIB = _load_lib() File "C:\Users\Richard\Anaconda2\lib\site-packages\xgboost\core.py", line 109, in _load_lib lib = ctypes.cdll.LoadLibrary(lib_path[0]) File "C:\Users\Richard\Anaconda2\lib\ctypes\__init__.py", line 444, in LoadLibrary return self._dlltype(name) File "C:\Users\Richard\Anaconda2\lib\ctypes\__init__.py", line 366, in __init__ self._handle = _dlopen(self._name, mode) WindowsError: [Error 126] The specified module could not be found I have searched for similar questions on StackOverflow, but I've had no luck, besides finding complicated answers which I did not feel comfortable implementing without fully understanding, and which I am not sure are applicable to my scenario anyway. Some further things t…
has answer: http://stackoverflow.com/a/52008291
tagged with: python
has title: Windows Error 126 when importing xgboost into Anaconda
type: AnsweredQuestion
tagged with: anaconda
score: 0
type: Question
tagged with: python-import
accepted answer: http://stackoverflow.com/a/52008291

http://stackoverflow.com/q/52110236
answer count: 1
tagged with: c#
tagged with: uipath
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91171315
has comment: http://stackoverflow.com/comment/91171420
type: Question
tagged with: python
has answer: http://stackoverflow.com/a/52112067
has title: Run Python function (64-bit) from C# in 32-bit program
score: 0
has comment: http://stackoverflow.com/comment/91174614
tagged with: ironpython
has body: after quite long inspection of this issue, I'm a little bit lost and I need community help. Let me explain the issue firstly: I'm using the software (32-bit, let's call it UiPath) in Windows 7 (x64). From UiPath, I want to run python method by using Python 3.6 (64-bit) Interpreter. In UiPath, you can write your own activity programmed in C#. My goal is to write the activity (C# class), which will be able to run some python function with parameters and return me output (return) of this function. I think, that cmd is not the good approach, maybe IronPython would help me, but can you give me any advice, please? Thank you so much.
has comment: http://stackoverflow.com/comment/91172843

countvectorizer
type: Tag
tags question: http://stackoverflow.com/q/52005164
tag name: countvectorizer

http://stackoverflow.com/a/52030654
score: 0
answers question: http://stackoverflow.com/q/52027761
has body: The best solution I have reached so far, is this: if mycollection.find_one({'area': 'zone 45', 'Report_stats.date_hour': '2018-08-26 13'}): mycollection.update_one({'area': 'zone 45', 'Report_stats.date_hour': '2018-08-26 13'}, { '$inc': { 'Report_stats.$.count': 1 }, '$set': { 'last_state': 'Clear' }, '$push': { 'recent_indices': 33, } }, ) else: mycollection.update_one({'area': 'zone 45'}, { '$set': { 'last_state': 'Clear' }, '$push': { 'recent_indices': 33, 'Report_stats':{'date_hour':'2018-08-26 13', 'count':1} } }, upsert = True ) However, it still is performing one query twice to update one document based on one request, which is not quite satisfactory. Any better suggestions?
type: Answer

http://stackoverflow.com/comment/90925790
comment on: http://stackoverflow.com/a/51986006
type: Comment
score: 1
has text: @JRCX - Added solution for you, check edited answer.
type: AnswerComment

http://stackoverflow.com/comment/90889503
score: 0
type: QuestionComment
type: Comment
has text: Also look into `functools.wraps`
comment on: http://stackoverflow.com/q/51969462

http://stackoverflow.com/a/52100113
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52099985
type: Answer
has body: Try it like this: import re patt = r'100\.(6|7|8|9|10|11|12)' data = '100.13.1' if re.match(patt, data): print('[Quit], Matches') else: print('[info], Not match') Alternatively, this pattern will match numbers from 6 through 12: r'100\.([6-9]|1[0-2])'
has comment: http://stackoverflow.com/comment/91151450
upvote count: 3
score: 3
answers question: http://stackoverflow.com/q/52099985

http://stackoverflow.com/comment/91124350
comment on: http://stackoverflow.com/q/52087029
has text: @JonClements What version are you on? It creates a single row Series on 0.23.4.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/51964911
score: 0
has body: When you do a = test(), you have called the test() function, and got the nested function. This function needs an argument, so you can't call it by a() alone (it's like calling it by nested()). You would need to modify this to def nested() for your code to work, and, more importantly, to see that the function "remembers" the x defined outside. A more typical example would be def test(x): def nested(y): print(f'x is {x}, y is {y}') return nested a = test(5) a(12)
has comment: http://stackoverflow.com/comment/90944551
type: Answer
answers question: http://stackoverflow.com/q/51964872
has comment: http://stackoverflow.com/comment/90967267

http://stackoverflow.com/comment/91145796
comment on: http://stackoverflow.com/q/52097680
score: 0
type: Comment
has text: Is this just for one record, or are you going to be iterating through a list within a page? The problem with your first BeautifulSoup (BS) code is that only some of the data is contained within `span` tags. I think you need to write a discreen piece of extraction logic for each field (perhaps as a separate method / function) and then apply each one to the code.
type: QuestionComment

http://stackoverflow.com/comment/90932981
comment on: http://stackoverflow.com/a/51987693
has text: If I do a filter, I can get 1 of 2 results. I can get true/false values or I can get the actual value back. The solution you gave me earlier, gave me exactly what I needed, but what dictates whether I get true/false back or the actual value back on true records returned? does that make sense?
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/a/52111872
upvote count: 3
answers question: http://stackoverflow.com/q/52111601
score: 3
has comment: http://stackoverflow.com/comment/91176613
has body: You can use itertools.product for this &gt;&gt;&gt; from itertools import product &gt;&gt;&gt; sentence = "The weather is cool" &gt;&gt;&gt; dico = {'weather': ['sun', 'rain'],'cool': ['fabulous', 'great']} &gt;&gt;&gt; &gt;&gt;&gt; lst = [[word] + list(dico[word]) if word in dico else [word] for word in sentence.split()] &gt;&gt;&gt; lst [['The'], ['weather', 'sun', 'rain'], ['is'], ['cool', 'fabulous', 'great']] &gt;&gt;&gt; &gt;&gt;&gt; res = [' '.join(line) for line in product(*lst)] &gt;&gt;&gt; &gt;&gt;&gt; pprint(res) ['The weather is cool', 'The weather is fabulous', 'The weather is great', 'The sun is cool', 'The sun is fabulous', 'The sun is great', 'The rain is cool', 'The rain is fabulous', 'The rain is great']
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52111601
type: Answer

http://stackoverflow.com/comment/91066218
comment on: http://stackoverflow.com/a/52057333
score: 0
type: Comment
has text: I mean, by searching for h2 then h3, then h4, the order of those in the html page is lost :/
type: AnswerComment

http://stackoverflow.com/a/73576818
answers question: http://stackoverflow.com/q/52053491
has body: An end-to-end practical example: $ test_click add -a 1 -b 2 --- add: 3 ------------------ $ test_click sub -a 5 -b 1 --- sub: 4 ------------------ $ test_click enter a operation (add or sub): add enter a number 1: 1 enter a number 2: 2 --- add: 3 ------------------ $ test_click enter a operation (add or sub): sub enter a number 1: 5 enter a number 2: 1 --- sub: 4 the code: import click @click.group(invoke_without_command=True) @click.pass_context def mycommands(ctx): if ctx.invoked_subcommand is None: manual_mode() pass def manual_mode(): tipo = input('enter a operation (add or sub): ') arg1 = input('enter a number 1: ') arg2 = input('enter a number 2: ') if tipo == 'add': add_f(int(arg1), int(arg2)) elif tipo == 'sub': sub_f(int(arg1), int(arg2)) else: print('type not know') def add_f(arg1, arg2): print('add:', arg1 + arg2) def sub_f(arg1, arg2): print('sub:', arg1 - arg2) @click.option('-a', 'arg1', type=click.INT) @click.option('-b', 'arg2', type=click.INT) @mycommands.command() def add(arg1, arg2): add_f(arg1, arg2) @click.option('-a', 'arg1', type=click.INT) @click.option('-b', 'arg2', type=click.INT) @mycommands.command() def sub(arg1, arg2): sub_f(arg1, arg2) if __name__ == '__main__': mycommands()
type: Answer
score: 0

http://stackoverflow.com/q/52102744
has comment: http://stackoverflow.com/comment/91156474
downvote count: 2
type: Question
tagged with: discord.py
score: -2
upvote count: 0
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/52102850
has title: Listing roles alphabetically
has body: Hi I'm trying to list roles alphabetically so far I'm able to list roles on my discord server bit I'm unsure how to list them in alphabetical order in .py I've searched everywhere without any success. Here is what I'm working with. import re import discord from .utils import checks from discord.ext import commands from __main__ import send_cmd_help class Roles: def __init__(self, bot): self.bot = bot @commands.command(pass_context=True, no_pm=True, name='add', aliases=['iam','iplay']) async def add(self, context, *role_name): """Add a role""" server = context.message.server author = context.message.author name = ' '.join(role_name) roles = [role.name.lower() for role in server.roles] if name.lower() in roles: for role in server.roles: if role.name.lower() == name.lower(): if role.permissions.value &lt; 1: try: await self.bot.add_roles(author, role) message = '{} added the role **{}**.'.format(author.display_name, role.name) embed = discord.Embed(description=message.format(author.display_name, role.name), colour=0x00ff00) embed.set_footer(text="Tip: type the command !roles or !list to list all roles.") break except discord.Forbidden: message = 'I have no permissions to do that. Please give me role managing permissions.' embed = discord.Embed(description=message) else: message = 'You cannot use this role' embed = discord.Embed(description=message) else: message = 'No such role' embed = discord.Embed(description=message) else: message = 'I cannot find that role :frowning2:' embed = discord.Embed(description=message) embed.set_footer(text="Tip: type the command !list to list all roles.") await self.bot.say(embed=embed) @commands.command(pass_context=True, no_pm=True, name='remove') async def remove(self, context, *role_name): """Remove a role""" server = context.message.server author = context.message.author name = ' '.join(role_name) roles = [role.name.lower() for role in server.roles] if name.lower() in roles: for role in server.roles: if role.name.lower() == name.low…
tagged with: python
accepted answer: http://stackoverflow.com/a/52102850
tagged with: discord
type: AnsweredQuestion
tagged with: python-3.x

http://stackoverflow.com/comment/90896973
type: QuestionComment
comment on: http://stackoverflow.com/q/51973253
has text: have you tried locating with other locators like css selector,xpath? Also, are you getting any exception?
score: 0
type: Comment

http://stackoverflow.com/comment/90928059
type: Comment
has text: I assumed that the best way of increasing speed would be to get rid of the double loop, or by somehow vectorising the approach. In terms of the first comment suggestion for a pattern, I struggle to understand what each of these characters implies given that I am relatively new to Regex
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/51968184

http://stackoverflow.com/comment/90994400
has text: That is for modules, not for loading file-like objects from disk.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52022001
type: AnswerComment

http://stackoverflow.com/q/52103370
type: Question
upvote count: 4
accepted answer: http://stackoverflow.com/a/52103706
score: 4
has answer: http://stackoverflow.com/a/52103547
has answer: http://stackoverflow.com/a/52103706
has answer: http://stackoverflow.com/a/52103514
possible better answer: http://stackoverflow.com/a/52103520
downvote count: 0
has body: I want to get all 'xlsx' files that somewhere have 'feedback report' in them. I want to make this filter very strong. So any partial matches like 'feedback_report', 'feedback report', 'Feedback Report' should all return true. Example file names : ZSS Project_JKIAL-SA_FEEDBACK_REPORT_Jan 29th 2015.xlsx ZL-SA_feedback report_012844.xlsx ASARanem-SA_Feedback Report_012844.xlsx A futile attempt below. regex = re.compile(r"[a-zA-Z0-0]*[fF][eE][eE][dD][bB][aA][cC][kK]\s[rR][eE][pP][oO][rR][tT][a-zA-Z0-0]*.xlsx")
has comment: http://stackoverflow.com/comment/91158314
favorite count: 0
answer count: 5
tagged with: python
tagged with: regex
has title: How to partial search for words using regex python
has answer: http://stackoverflow.com/a/52103721
type: AnsweredQuestion
tagged with: cpu-word
has answer: http://stackoverflow.com/a/52103520
has comment: http://stackoverflow.com/comment/91157968

http://stackoverflow.com/comment/90937120
has text: That is the entire error log it does not print import or runtime issue.
score: 0
comment on: http://stackoverflow.com/q/51993659
type: Comment
type: QuestionComment

http://stackoverflow.com/a/52113396
upvote count: 6
accepted answer of: http://stackoverflow.com/q/52107584
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/91303452
type: Answer
score: 6
has comment: http://stackoverflow.com/comment/102257295
downvote count: 0
has body: R-solution the tidyxl-package can help you... example temp.xlsx, with data on A1:A4 of the first sheet. Below is an excel-screenshot: library(tidyxl) formats <- xlsx_formats( "temp.xlsx" ) cells <- xlsx_cells( "temp.xlsx" ) strike <- which( formats$local$font$strike ) cells[ cells$local_format_id %in% strike, 2 ] # A tibble: 2 x 1 # address # <chr> # 1 A2 # 2 A4
answers question: http://stackoverflow.com/q/52107584

http://stackoverflow.com/comment/90982268
score: 0
has text: Tried it, still no luck :/ But you were totally right about the __FILE__ not working so thanks for that!
type: Comment
comment on: http://stackoverflow.com/a/52012510
type: AnswerComment

http://stackoverflow.com/comment/91143019
comment on: http://stackoverflow.com/a/52091740
score: 0
type: AnswerComment
type: Comment
has text: I'm not use to conditional formatting, so my way of doing it might not be pythonic, but it's a starter. Please tell me if it worked on your dataframe.

http://stackoverflow.com/q/52060033
has answer: http://stackoverflow.com/a/52072096
has title: Python Pandas to plot bar - adjust width using column value
has comment: http://stackoverflow.com/comment/91070785
has body: I am using python/pandas dataframe to plot a bar graph but I have no success to adjust the bar width using an array or a df columns, like this: df.plot.bar(ax=axes[i], width=df.width, stacked=True, color=colors[i], logy=logy) where df.width is a column in my dataframe. Stacktrace: File "/usr/local/lib/python2.7/dist-packages/pandas/plotting/_core.py", line 3090, in bar return self(kind='bar', x=x, y=y, **kwds) File "/usr/local/lib/python2.7/dist-packages/pandas/plotting/_core.py", line 2941, in __call__ sort_columns=sort_columns, **kwds) File "/usr/local/lib/python2.7/dist-packages/pandas/plotting/_core.py", line 1977, in plot_frame **kwds) File "/usr/local/lib/python2.7/dist-packages/pandas/plotting/_core.py", line 1804, in _plot plot_obj.generate() File "/usr/local/lib/python2.7/dist-packages/pandas/plotting/_core.py", line 267, in generate self._post_plot_logic(ax, self.data) File "/usr/local/lib/python2.7/dist-packages/pandas/plotting/_core.py", line 1276, in _post_plot_logic e_edge = self.ax_pos[-1] + 0.25 + self.bar_width + self.lim_offset File "/usr/local/lib/python2.7/dist-packages/pandas/core/series.py", line 767, in __getitem__ result = self.index.get_value(self, key) File "/usr/local/lib/python2.7/dist-packages/pandas/core/indexes/numeric.py", line 358, in get_value loc = self.get_loc(k) File "/usr/local/lib/python2.7/dist-packages/pandas/core/indexes/numeric.py", line 419, in get_loc tolerance=tolerance) File "/usr/local/lib/python2.7/dist-packages/pandas/core/indexes/base.py", line 3080, in get_loc return self._engine.get_loc(self._maybe_cast_indexer(key)) File "pandas/_libs/index.pyx", line 140, in pandas._libs.index.IndexEngine.get_loc File "pandas/_libs/index.pyx", line 162, in pandas._libs.index.IndexEngine.get_loc File "pandas/_libs/hashtable_class_helper.pxi", line 379, in pandas._libs.hashtable.Float64HashTable.get_item File "pandas/_libs/hashtable_class_helper.pxi", line 385, in pandas._libs.hashtable.Float64HashTable.get_item KeyError: -1.0 Ins…
tagged with: pandas
answer count: 1
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/91077788
type: UnansweredQuestion
tagged with: python
score: 1
upvote count: 1
type: Question

http://stackoverflow.com/comment/91160768
has text: Infura doesn't support event filters via HTTP(s). You'll need to use websockets (or connect to a node other than Infura).
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52104686
score: 1

http://stackoverflow.com/comment/90867091
has text: Please reformat the post so the code is in code format.
comment on: http://stackoverflow.com/q/51958350
score: 4
type: Comment
type: QuestionComment

http://stackoverflow.com/a/51968113
type: AcceptedAnswer
downvote count: 0
has body: Type Command + . (on Mac), or Ctrl + . (on Windows) to restart your Spyder kernel.
upvote count: 8
type: Answer
has comment: http://stackoverflow.com/comment/90887459
score: 8
accepted answer of: http://stackoverflow.com/q/51967975
answers question: http://stackoverflow.com/q/51967975

http://stackoverflow.com/a/52042421
score: 1
has comment: http://stackoverflow.com/comment/91036293
has comment: http://stackoverflow.com/comment/91036184
upvote count: 1
has comment: http://stackoverflow.com/comment/91036392
has comment: http://stackoverflow.com/comment/91036074
has body: There is a problem with your file structure. Your celery app should be on the same folder as settings.py website/website --> init.py, settings.py, urls.py, wsgi.py, celery_app.py website/index --> init.py, tasks.py and also in the init.py in the website folder should be having from __future__ import absolute_import, unicode_literals # This will make sure the app is always imported when # Django starts so that shared_task will use this app. from .celery_app import app as celery_app __all__ = ['celery_app']
has comment: http://stackoverflow.com/comment/91036513
answers question: http://stackoverflow.com/q/52041921
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/91036452
has comment: http://stackoverflow.com/comment/91036578

regex
tags question: http://stackoverflow.com/q/52014482
tags question: http://stackoverflow.com/q/51957721
tags question: http://stackoverflow.com/q/51965650
tags question: http://stackoverflow.com/q/52052189
tags question: http://stackoverflow.com/q/52093555
tags question: http://stackoverflow.com/q/52006806
tags question: http://stackoverflow.com/q/52034775
tags question: http://stackoverflow.com/q/51982073
tags question: http://stackoverflow.com/q/52014159
tags question: http://stackoverflow.com/q/51973240
tags question: http://stackoverflow.com/q/51976517
tags question: http://stackoverflow.com/q/51978160
tags question: http://stackoverflow.com/q/52096260
tag name: regex
tags question: http://stackoverflow.com/q/51982826
tags question: http://stackoverflow.com/q/52032785
tags question: http://stackoverflow.com/q/52071899
tags question: http://stackoverflow.com/q/52024612
tags question: http://stackoverflow.com/q/52069098
tags question: http://stackoverflow.com/q/51980572
tags question: http://stackoverflow.com/q/52004719
tags question: http://stackoverflow.com/q/52041238
tags question: http://stackoverflow.com/q/52066023
tags question: http://stackoverflow.com/q/52082823
tags question: http://stackoverflow.com/q/52081659
tags question: http://stackoverflow.com/q/52013854
tags question: http://stackoverflow.com/q/51960151
tags question: http://stackoverflow.com/q/51963008
tags question: http://stackoverflow.com/q/52003530
tags question: http://stackoverflow.com/q/51973231
tags question: http://stackoverflow.com/q/52009482
tags question: http://stackoverflow.com/q/52100291
tags question: http://stackoverflow.com/q/51974506
tags question: http://stackoverflow.com/q/51999096
tags question: http://stackoverflow.com/q/52095109
tags question: http://stackoverflow.com/q/51970066
tags question: http://stackoverflow.com/q/51968526
tags question: http://stackoverflow.com/q/51979193
tags question: http://stackoverflow.com/q/52077771
tags question: http://stackoverflow.com/q/52085907
tags question: http://stackoverflow.com/q/52050018
tags question: http://stackoverflow.com/q/52025152
tags question: http://stackoverflow.com/q/52016751
tags question: http://stackoverflow.com/q/51992874
tags question: http://stackoverflow.com/q/52063425
tags question: http://stackoverflow.com/q/51963270
tags question: http://stackoverflow.com/q/51973529
tags question: http://stackoverflow.com/q/52059515
tags question: http://stackoverflow.com/q/52050527
tags question: http://stackoverflow.com/q/51970640
tags question: http://stackoverflow.com/q/52048849
tags question: http://stackoverflow.com/q/52099964
tags question: http://stackoverflow.com/q/52086166
tags question: http://stackoverflow.com/q/52049714
tags question: http://stackoverflow.com/q/51973598
tags question: http://stackoverflow.com/q/52006648
tags question: http://stackoverflow.com/q/52047532
tags question: http://stackoverflow.com/q/52102921
tags question: http://stackoverflow.com/q/51979358
tags question: http://stackoverflow.com/q/52103370
tags question: http://stackoverflow.com/q/52048617
tags question: http://stackoverflow.com/q/51988738
tags question: http://stackoverflow.com/q/52007431
tags question: http://stackoverflow.com/q/51989179
tags question: http://stackoverflow.com/q/52103666
tags question: http://stackoverflow.com/q/52089036
tags question: http://stackoverflow.com/q/52065083
tags question: http://stackoverflow.com/q/51973450
tags question: http://stackoverflow.com/q/52104576
tags question: http://stackoverflow.com/q/52102208
tags question: http://stackoverflow.com/q/51961326
tags question: http://stackoverflow.com/q/51973338
tags question: http://stackoverflow.com/q/51958483
tags question: http://stackoverflow.com/q/51968184
tags question: http://stackoverflow.com/q/52016577
tags question: http://stackoverflow.com/q/52004101
tags question: http://stackoverflow.com/q/52045064
tags question: http://stackoverflow.com/q/51967507
tags question: http://stackoverflow.com/q/51967212
tags question: http://stackoverflow.com/q/51998555

http://stackoverflow.com/a/52086952
has comment: http://stackoverflow.com/comment/95660133
downvote count: 0
score: 4
has body: Jest can mock an entire module using jest.mock() or mock an individual module export using jest.spyOn() in combination with functions like mockImplementation(). This makes it easy to mock a function imported from a library: // ---- lib.js ---- export function myFunctionA() { return 'a'; } // ---- myModule.js ---- import { myFunctionA } from './lib'; export function myFunctionB() { return myFunctionA() + 'b'; // call lib.myFunctionA() } // ---- myModule.test.js ---- import { myFunctionB } from './myModule'; import * as lib from './lib'; describe('myModule tests', () =&gt; { test('myFunctionB works', () =&gt; { const mock = jest.spyOn(lib, 'myFunctionA'); // create a spy on lib.myFunctionA() mock.mockImplementation(() =&gt; 'c'); // replace the implementation expect(myFunctionB()).toBe('cb'); mock.mockRestore(); // remove the spy and mock implementation }); }); In the code sample from the question myModule contains two functions and one calls the other directly. Because a mock works on either an entire module or a module export, mocking the direct call to myFunctionA() from within myFunctionB() would be very difficult the way the code is written. The easiest way I have found to work around situations like this is to import the module into itself and use the module when calling the function. That way it is the module export that is being called and it can be mocked in the test: // ---- myModule.js ---- import * as myModule from './myModule'; export function myFunctionA() { return 'a'; } export function myFunctionB() { return myModule.myFunctionA() + 'b'; // call myModule.myFunctionA() } // ---- myModule.test.js ---- import * as myModule from './myModule'; describe('myModule tests', () =&gt; { test('myFunctionB works', () =&gt; { const mock = jest.spyOn(myModule, 'myFunctionA'); // create a spy on myModule.myFunctionA() mock.mockImplementation(() =&gt; 'c'); // replace the implementation expect(myModule.myFunctionB()).toBe('cb'); mock.mockRestore(); // remove the spy an…
has comment: http://stackoverflow.com/comment/95728115
type: Answer
has comment: http://stackoverflow.com/comment/112663709
answers question: http://stackoverflow.com/q/52080459
upvote count: 4

http://stackoverflow.com/comment/91172320
score: 0
type: AnswerComment
has text: unfortunately, it does not work when I use virtual enviroment too
comment on: http://stackoverflow.com/a/52110562
type: Comment

http://stackoverflow.com/comment/91027839
has text: According to Qt docs. "The grabWindow() function grabs pixels from the screen, not from the window", so this function is't able to grab invisible parts of your widget.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52038724
score: 1

http://stackoverflow.com/comment/90937709
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51992497
has text: I installed "conda" package manager for sublime and im using that as the build, im not getting issues or anything, but how do I tell if it is using the anaconda version?
type: AnswerComment

http://stackoverflow.com/comment/90922104
type: Comment
type: QuestionComment
has text: Check out decorators, I think that might be what you're going for
comment on: http://stackoverflow.com/q/51986378
score: 0

http://stackoverflow.com/comment/91148179
type: QuestionComment
score: 3
has text: The data structure for which method 1 works, is a `dict`, not a `list`. When you iterate a `dict`, you iterate its keys. Try it with: `l = {0: 'tiger', 1: 'lion'}`
comment on: http://stackoverflow.com/q/52098874
type: Comment

http://stackoverflow.com/comment/90884657
type: Comment
has text: `L[0:1] == L[0] == L[:1]`
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51966912

http://stackoverflow.com/comment/90961130
score: 0
has text: Generally you want to let errors like this bubble up to the caller. It usually means that they made a mistake, and the best way of giving them all the information about that mistake is to raise an exception. You could even do something like `except AttributeError as e: raise ValueError("I need a Foo") from e` to give context.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52005640

http://stackoverflow.com/a/59478307
has comment: http://stackoverflow.com/comment/105141312
answers question: http://stackoverflow.com/q/52111663
score: 0
type: Answer
has body: you can use from this command for write a rtp header packet. but whet you trying to write this packet in a pcap. you will see this error: TypeError: clone_with() got multiple values for keyword argument 'payload' therefor you before write packet must change scapy/packet.py lib. this link explain better: https://github.com/CJTozer/scapy/commit/d0367f2efa86e65fa2b0a82a864b7fe89222f153

http://stackoverflow.com/a/52169316
upvote count: 1
accepted answer of: http://stackoverflow.com/q/52094338
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/52094338
has body: I found out my problem. It caused that I had two environments on server and uwsgi settings was set on another environment that not installing rest framework on it. thanks everybody
has comment: http://stackoverflow.com/comment/111001316
type: Answer
downvote count: 0
score: 1

http://stackoverflow.com/q/51980938
answer count: 1
has body: I use jupyder notebook: from IPython import display graph = net_drawer.GetPydotGraph(train_model.net.Proto().op, 'mnist', rankdir='LR') #graph.write_png("lenet.png") display.Image(graph.create_png(), width=800) and I encounter this error: --------------------------------------------------------------------------- OSError Traceback (most recent call last) &lt;ipython-input-11-95f1d8e2feb8&gt; in &lt;module&gt;() 2 graph = net_drawer.GetPydotGraph(train_model.net.Proto().op, 'mnist', rankdir='LR') 3 #graph.write_png("lenet.png") ----&gt; 4 display.Image(graph.create_png(), width=800) /home/user/.local/lib/python2.7/site-packages/pydot.pyc in new_method(f, prog, encoding) 1660 """Refer to docstring of method `create`.""" 1661 return self.create( -&gt; 1662 format=f, prog=prog, encoding=encoding) 1663 name = 'create_{fmt}'.format(fmt=frmt) 1664 self.__setattr__(name, new_method) /home/user/.local/lib/python2.7/site-packages/pydot.pyc in create(self, prog, format, encoding) 1865 args[1] = '"{prog}" not found in path.'.format( 1866 prog=prog) -&gt; 1867 raise OSError(*args) 1868 else: 1869 raise OSError: [Errno 2] "dot" not found in path. I can run the codes in terminal and pycharm successfully, but fail in jupyder notebook. could you please help me? thanks! Besides,I have installed dot successfully such as: sudo apt-get insall graphviz pip install pydot
tagged with: caffe
type: UnansweredQuestion
tagged with: caffe2
has title: jupyder notebook: OSError: [Errno 2] "dot" not found in path
has comment: http://stackoverflow.com/comment/90911968
tagged with: deep-learning
has comment: http://stackoverflow.com/comment/90950946
downvote count: 0
score: 1
favorite count: 0
type: Question
tagged with: python
upvote count: 1
has answer: http://stackoverflow.com/a/59461056

http://stackoverflow.com/a/51976252
type: AcceptedAnswer
score: 0
type: Answer
answers question: http://stackoverflow.com/q/51966816
accepted answer of: http://stackoverflow.com/q/51966816
has body: the issue was resolved after below steps - go to pyral location edit config.py file to include your rally log in credentials for fields USER_NAME and PASSWORD open command prompt in admin mode and run command set HTTPS_PROXY==http://user:password@proxy.domain.com:port for user id/psw, use your SSO credentials and not Rally credentials (if they are different). Then run the file sample.py and it worked

http://stackoverflow.com/comment/101232261
type: Comment
has text: I had a look to your code, but there is no usage info (I left an "Issue"); how is it supposed to be used?
type: AnswerComment
comment on: http://stackoverflow.com/a/51982749
score: 0

http://stackoverflow.com/q/52038311
has answer: http://stackoverflow.com/a/52038619
has answer: http://stackoverflow.com/a/52038495
accepted answer: http://stackoverflow.com/a/52038353
has title: How to create lists in list where every future list is separate by spaces in list
possible better answer: http://stackoverflow.com/a/52038436
tagged with: string
has answer: http://stackoverflow.com/a/52038436
favorite count: 0
tagged with: python-3.x
downvote count: 2
tagged with: input
tagged with: python
has comment: http://stackoverflow.com/comment/91026972
has body: User provides input with spaces: row = list(input()) print(row) ['1','2','3',' ','4','5','6',' ','7','8','9',' '] So I need to create 'row' list into the below. The list is divided into sub-lists based on whitespace: [['1','2','3'],['4','5','6'],['7','8','9']]
answer count: 4
type: AnsweredQuestion
score: 3
tagged with: list
has answer: http://stackoverflow.com/a/52038353
type: Question
upvote count: 5

http://stackoverflow.com/q/52029939
has answer: http://stackoverflow.com/a/52030006
type: Question
has body: I'm working on a project that uses Google Cloud Platform's App Engine in the Python 3 Flexible Environment using Django, and I'm trying to permanently redirect all requests over http to https for all routes, but so far have not been successful. I can access the site over https, but only if explicitly written in the address bar. I've looked at this post: How to permanently redirect `http://` and `www.` URLs to `https://`? but did not find the answer useful. The app works properly in every sense except for the redirecting. Here is my app.yaml file: # [START runtime] runtime: python env: flex entrypoint: gunicorn -b :$PORT myproject.wsgi runtime_config: python_version: 3 # [END runtime] In myproject/settings.py I have these variables defined: SECURE_SSL_REDIRECT = True SESSION_COOKIE_SECURE = True CSRF_COOKIE_SECURE = True SECURE_PROXY_SSL_HEADER = ('HTTP-X-FORWARDED-PROTO', 'https') On my local machine, when I set SECURE_SSL_REDIRECT to True, I was redirected to https properly, even though SSL is not supported on localhost. In production, I am still able to access the site using just http. Is there something I'm missing or doing wrong to cause the redirect not to happen?
tagged with: ssl
linked to: http://stackoverflow.com/q/44890448
score: 4
linked to: http://stackoverflow.com/q/33878825
upvote count: 4
has answer: http://stackoverflow.com/a/56370798
tagged with: google-cloud-platform
accepted answer: http://stackoverflow.com/a/52030006
downvote count: 0
has answer: http://stackoverflow.com/a/68202970
has answer: http://stackoverflow.com/a/52047272
favorite count: 0
answer count: 5
tagged with: google-app-engine
has title: Permanently Redirect http to https on Google App Engine Flexible with Django
tagged with: django
tagged with: python
has answer: http://stackoverflow.com/a/52032707
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/52032707

http://stackoverflow.com/a/52106094
type: Answer
has comment: http://stackoverflow.com/comment/91194951
has comment: http://stackoverflow.com/comment/91193088
has comment: http://stackoverflow.com/comment/91195258
score: 1
upvote count: 1
has body: According to this question, you can send keystrokes to a screen session like so: screen -dmS new_screen sh screen -S new_screen -X stuff "cd /dir " screen -S new_screen -X stuff "java -version " You could write a small shell script (let's call it run-exp.sh) to set your experiment running: #!/bin/sh source activate myenv python process_experiment $1 And then use a loop to start screen sessions running that script: #!/bin/sh for i in $(seq -w 1 20); do screen -dmS exp$i screen -S exp$i -X stuff "./run-exp.sh $i " # (The new line is necessary, not a mistake.) done
has comment: http://stackoverflow.com/comment/91197376
has comment: http://stackoverflow.com/comment/91187535
has comment: http://stackoverflow.com/comment/91193014
answers question: http://stackoverflow.com/q/52105173
has comment: http://stackoverflow.com/comment/91187341
downvote count: 0

http://stackoverflow.com/q/52014798
tagged with: graph
has title: Find number of breathe in and out in graph generated by breathe audio(wav) using jupyter/matplotlib
has comment: http://stackoverflow.com/comment/90979953
tagged with: matplotlib
upvote count: 2
has comment: http://stackoverflow.com/comment/90981452
has body: Now I have plot of audio of breathing man (plot) Then I put it through FFT(Fourier Fast Transform) (plot) Now I have to find number of breathe in and out per minute import matplotlib.pyplot as plt import wavio import numpy as np from scipy.fftpack import fft, fftfreq from IPython.display import display, HTML import math %matplotlib inline rate, sampwidth, array = wavio.readwav('breath.wav') data = array[:,0] samples = data.shape[0] plt.plot(data) # here i have plot of audio fft_out = fft(array) fft_out = fft_out[:,0] fftabs = np.abs(fft_out) freqs = fftfreq(samples, 1 / rate) plt.plot(freqs, fftabs) # here i have fft plot
favorite count: 0
tagged with: python
tagged with: jupyter
score: 2
answer count: 0
downvote count: 0
has comment: http://stackoverflow.com/comment/90980375
type: UnansweredQuestion
type: Question

http://stackoverflow.com/comment/91082843
type: QuestionComment
has text: Hi андрэ, I don't quite understand. What does this code currently do and what would you like it to do? Also, the two lines after "#output" make me think this won't compile if I try to run it; should those be non-code blocks?
comment on: http://stackoverflow.com/q/52066135
score: 1
type: Comment

http://stackoverflow.com/comment/91108675
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52079177
has text: @roganjosh I know to get variable as total posts I can use - json.dumps(data['total']) , but not sure how to create a loop which will pass through API pages.
score: 0

scipy
tags question: http://stackoverflow.com/q/52047639
tags question: http://stackoverflow.com/q/51956695
tags question: http://stackoverflow.com/q/52108417
tags question: http://stackoverflow.com/q/52017297
tags question: http://stackoverflow.com/q/52048904
tags question: http://stackoverflow.com/q/52043638
tags question: http://stackoverflow.com/q/52098146
tags question: http://stackoverflow.com/q/52014197
tags question: http://stackoverflow.com/q/52025636
tags question: http://stackoverflow.com/q/51996701
type: Tag
tags question: http://stackoverflow.com/q/52105165
tags question: http://stackoverflow.com/q/51973039
tag name: scipy
tags question: http://stackoverflow.com/q/51966169
tags question: http://stackoverflow.com/q/52105389
tags question: http://stackoverflow.com/q/52041542
tags question: http://stackoverflow.com/q/52088709
tags question: http://stackoverflow.com/q/51985853
tags question: http://stackoverflow.com/q/51988141
tags question: http://stackoverflow.com/q/52030866
tags question: http://stackoverflow.com/q/51980910
tags question: http://stackoverflow.com/q/52107471
tags question: http://stackoverflow.com/q/52088980
tags question: http://stackoverflow.com/q/51958811
tags question: http://stackoverflow.com/q/51956951
tags question: http://stackoverflow.com/q/52047851
tags question: http://stackoverflow.com/q/52073685
tags question: http://stackoverflow.com/q/52105247
tags question: http://stackoverflow.com/q/51968640
tags question: http://stackoverflow.com/q/52009153
tags question: http://stackoverflow.com/q/51983058
tags question: http://stackoverflow.com/q/51972134
tags question: http://stackoverflow.com/q/52022362
tags question: http://stackoverflow.com/q/51993431
tags question: http://stackoverflow.com/q/52020984
tags question: http://stackoverflow.com/q/51962506
tags question: http://stackoverflow.com/q/51987744
tags question: http://stackoverflow.com/q/52010861
tags question: http://stackoverflow.com/q/52041224
tags question: http://stackoverflow.com/q/52031190
tags question: http://stackoverflow.com/q/52015689
tags question: http://stackoverflow.com/q/51989966
tags question: http://stackoverflow.com/q/52030458
tags question: http://stackoverflow.com/q/51957207
tags question: http://stackoverflow.com/q/52094020
tags question: http://stackoverflow.com/q/52007861
tags question: http://stackoverflow.com/q/51967195
tags question: http://stackoverflow.com/q/51991626
tags question: http://stackoverflow.com/q/52075557
tags question: http://stackoverflow.com/q/51972620
tags question: http://stackoverflow.com/q/52001922
tags question: http://stackoverflow.com/q/52014550
tags question: http://stackoverflow.com/q/52099787
tags question: http://stackoverflow.com/q/51992154
tags question: http://stackoverflow.com/q/52029864
tags question: http://stackoverflow.com/q/52045608
tags question: http://stackoverflow.com/q/52013574
tags question: http://stackoverflow.com/q/52068810
tags question: http://stackoverflow.com/q/52064978
tags question: http://stackoverflow.com/q/51972569
tags question: http://stackoverflow.com/q/51961233
tags question: http://stackoverflow.com/q/52002080

http://stackoverflow.com/comment/91157037
type: AnswerComment
comment on: http://stackoverflow.com/a/52102409
score: 0
type: Comment
has text: @astute Does the new output makes sense to you?

http://stackoverflow.com/q/52039093
tagged with: django
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52053059
has comment: http://stackoverflow.com/comment/91028866
has body: I want the text inside button to toggle between like and dislike .Im trying to accomplish this using custom template tags . The like and dislike is working and model is getting updated. Just want the button to toggle between like and dislike! I have created the template tags folder .Just want help in creating the template tag function inside post_extras.py and how to call the function inside the template post_extras.py from django import template register = template.Library() @register.simple_tag(takes_context=True) def isliked(context,entry): if entry.filter(id=context['request'].post.id).exists(): return "Unlike" else: return "Like" like_section.html {% load post_extras %} {{ entry.total_likes }} Like &lt;form action="{% url 'like_post' %}" method="POST"&gt; {% csrf_token %} &lt;input type="submit" name="{{ entry.id }}" value="like" class="btn btn-primary like"/&gt; &lt;/form&gt; models.py class Post(models.Model): user= models.ForeignKey(User, on_delete=models.CASCADE) heading = models.CharField(max_length=200, null=False) text = models.TextField(null=False) created_date=models.DateTimeField(default=timezone.now) pic = models.ImageField(upload_to='image', blank='True') def __str__(self): return self.heading def getuser(self): return self.user.username def total_likes(self): return Like.objects.filter(post=self).count() class Like(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE) post = models.ForeignKey(Post,on_delete=models.CASCADE) def __str__(self): return self.post.heading ajax code: $(document).on('click','.like',function(e) { e.preventDefault(); var pks=$(this).attr('name'); console.log('primarys : '+ pks); $.ajax({ type:'POST', url:'like/', data:{ 'ids': pks, csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val() }, success:function (response) { $(e.target).parents('.like-section').html(response); console.log(response) console.log("liked"); }, error: function(rs,e){ console.log(rs, e.response…
type: Question
accepted answer: http://stackoverflow.com/a/52053059
has comment: http://stackoverflow.com/comment/91028887
score: 0
answer count: 2
has comment: http://stackoverflow.com/comment/91028823
has answer: http://stackoverflow.com/a/52039733
has title: Like Dislike Toggle using custom template tags
has comment: http://stackoverflow.com/comment/91028684
possible better answer: http://stackoverflow.com/a/52039733
has comment: http://stackoverflow.com/comment/91029178

http://stackoverflow.com/comment/91166810
type: AnswerComment
comment on: http://stackoverflow.com/a/52107882
has text: This works now! there was a bug in my previous code! Thank you.
type: Comment
score: 1

http://stackoverflow.com/q/52022571
type: Question
answer count: 1
has comment: http://stackoverflow.com/comment/90996209
score: 0
has title: Passing data/request to multiple html files
tagged with: http://stackoverflow.com/tag/html
has answer: http://stackoverflow.com/a/52022654
tagged with: view
tagged with: django
tagged with: python
type: AnsweredQuestion
has body: Is there a way to pass data to multiple html files? def topic(request, topic_id): topic = Topic.objects.get(id = topic_id) entries = topic.entry_set.order_by('-date_added') videos = topic.document_set.order_by('-upload_at') images = topic.image_set.order_by('-upload_at') context1 = {'topic': topic} context2 = {'entries': entries} return render(request, 'learning_logs/entry.html', context1) return render(request, 'learning_logs/text.html', context2) I want the data to passed onto both html files, but only one is actually rendered/displayed. The html file that is displayed will have an extends linking to the other one.
accepted answer: http://stackoverflow.com/a/52022654
tagged with: forms

http://stackoverflow.com/q/51957005
score: -2
tagged with: javascript
upvote count: 0
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/90864907
tagged with: http://stackoverflow.com/tag/html
has answer: http://stackoverflow.com/a/51957243
tagged with: python
type: AnsweredQuestion
downvote count: 2
has body: I am working on a project where I have inherited some code that logs into a website using python's 'requests' library and scrapes the site for content. The 'login' code utilizes a backend URL to POST credentials to an endpoint. (Works fine) There is another part of the site, however that does not have a backend URL. It just has a form where a pin number need to be entered to access data. Below is the div code Verify PIN Does anyone know of a good way to use the requests library to input the data and press the button ? My inclination is to use the xpath and go from there (I'm pretty familiar with writing scapers - https://github.com/1jkunz1/MLB-Sabermetrics-Scraper/blob/master/src/scraper.py) I really don't want to use selenium for this task because I don't want the project to be dependent upon it, but most of the solutions I've been able to find seem to prefer selenium.
tagged with: python-requests
type: Question
has title: Programmatically enter a pin number and press button
tagged with: scraper
accepted answer: http://stackoverflow.com/a/51957243

http://stackoverflow.com/comment/90926253
type: QuestionComment
has text: Although, if you are willing to change your DB Schema, then you can replace fields `mother` and `father` with `parents` as a `ManyToManyField` and add a `type` field in `Parent` model with choices as `M` or `F`, corresponding to `Mother` and `Father`. Then, you can have the `related_name` of `parents` as `children`.
type: Comment
score: 2
comment on: http://stackoverflow.com/q/51988218

http://stackoverflow.com/comment/90900671
type: Comment
type: QuestionComment
has text: Is `something` a string?
score: 0
comment on: http://stackoverflow.com/q/51975047

http://stackoverflow.com/q/51969653
tagged with: python
has comment: http://stackoverflow.com/comment/90896818
has title: How to pass data from java to python script as parameter
has body: I wanted to run a script from java class. I was able to do it with ProcessBuilder. Now I am struggling to pass data as an argument to the script. I can pass a string, but I am having trouble passing list of data (data read from a CSV file). One that I tried was using StringBuffer and passing the data as Bytes StringBuffer sb = new StringBuffer(); ArrayList argsList = new ArrayList(); // append the sb from record. //convert it to bytes //sb.toString() contains my data with a delimiter ';' // sb.toString().getBytes("UTF-8").toString() argsList.add(0,"Continuum/anaconda3/envs/sth/python"); argsList.add(1,"python/test.py"); argsList.add(2,"python/test.py"); argsList.add(3,sb.toString().getBytes("UTF-8").toString()) ProcessBuilder builder = new ProcessBuilder(argsList); Process p = builder.start(); I can not pass sb.toString().getBytes("UTF-8") to the process builder. I get java.lang.ArrayStoreException On the other hand, if I pass sb.toString(), I get java.io.IOException: Cannot run program Continuum/anaconda3/envs/sth/python, CreateProcess error=206, The filename or extension is too long add it to list of commands to process builder. How can I read what I passed in python? Is this even the right way to pass data ( row X column)? Thanks
upvote count: 3
type: UnansweredQuestion
tagged with: parameter-passing
linked to: http://stackoverflow.com/q/27267391
has comment: http://stackoverflow.com/comment/90890268
score: 3
tagged with: java
type: Question
has answer: http://stackoverflow.com/a/51971978
answer count: 2
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/90911009
has comment: http://stackoverflow.com/comment/90890130
has answer: http://stackoverflow.com/a/70091350

http://stackoverflow.com/q/52000635
answer count: 1
has comment: http://stackoverflow.com/comment/90950313
has comment: http://stackoverflow.com/comment/90950538
score: 0
has title: TypeError: 'NoneType' object is not callable but object is not nonetype
tagged with: python
has comment: http://stackoverflow.com/comment/90950835
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/90950786
type: Question
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90950644
has answer: http://stackoverflow.com/a/52001015
has comment: http://stackoverflow.com/comment/90950473
accepted answer: http://stackoverflow.com/a/52001015
has comment: http://stackoverflow.com/comment/90950803
has body: def winner(board): WAYS_TOWIN = ((0, 1, 2), (3, 4, 5), (6, 7, 8), (0, 4, 8), (2, 4, 6), (0, 3, 6), (1, 4, 7), (2, 5, 8)) for row in WAYS_TOWIN: if board[row[0]] == board[row[1]] == board[row[2]] != " ": winner = board[row[0]] return winner if " " not in board: return TIE else: return None #Main instructions() human = input("Enter your name: "); print("\n") pieces = who_first(human, computer); print("\n")#pieces becomes a list with human piece first and computer piece second board = new_board(); print("\n") winner = winner(board) while winner == None and winner != TIE: if turn == pieces[0]:#if human is first winner = winner(board) When I run the winner function the first time, it returns none to the winner variable and there are no errors. But when I run it for the second time it gives me TypeError: 'NoneType' object is not callable. The board is a list with [" "]*9 and i dont get why calling the board the second time is a nonetype object.
has comment: http://stackoverflow.com/comment/90950952

http://stackoverflow.com/a/52038940
accepted answer of: http://stackoverflow.com/q/52037519
answers question: http://stackoverflow.com/q/52037519
type: Answer
has body: gevent.Greenlet.name is not a common property, but a gevent.util.readproperty obj, which is a special non-data descriptor works like @property, and for a non-data descriptor: ... In contrast, non-data descriptors can be overridden by instances. you could override it simply: &gt;&gt;&gt; gr = gevent.spawn(gevent.sleep, (1,)) &gt;&gt;&gt; gr.name = "a_cool_name" &gt;&gt;&gt; print(gr) &lt;Greenlet "a_cool_name" at 0x1082a47b8: sleep((1,))&gt; read more on the gevent source and the descriptor doc.
score: 3
upvote count: 3
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/a/52147233
has comment: http://stackoverflow.com/comment/91878232
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/52032441
has body: Just copy-pasting your code and running it with VTK 6.3 on Ubuntu 16.04 seems to work correctly. The window closes as expected using the closing button or "q". So this seems to be a bug related to the VTK release you are using on your system. Kind regards.
downvote count: 0
type: Answer
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/52032441

google-cloud-functions
tag name: google-cloud-functions
type: Tag
tags question: http://stackoverflow.com/q/51995682

http://stackoverflow.com/comment/91041950
type: QuestionComment
score: 0
has text: Do the arrays all look the same? Can you just find the starting column header and run it to the end?
comment on: http://stackoverflow.com/q/52045433
type: Comment

http://stackoverflow.com/comment/91121470
type: Comment
type: QuestionComment
score: 2
comment on: http://stackoverflow.com/q/52085506
has text: That is not possible, as exceptions are just regular classes in Python, with the main difference being that the built-in ones are, well, in the `builtins` module. However, it is not possible nor desirable to add custom classes to that module.

http://stackoverflow.com/q/51987761
has comment: http://stackoverflow.com/comment/90925226
has body: I'm scraping this website using Python and Selenium. But it currently only scrapes the first 10 page for the month of July, it turns the page number of the previous sibling of the next button into int and clicks next number_of_pages - 1 however after it gets to page 10 it stops. URL - https://planning.adur-worthing.gov.uk/online-applications/search.do?action=monthlyList Can anyone help me to get it to scrape all the pages? def pagination( driver ): data = [] last_element = driver.find_element_by_xpath('//a[ contains( concat( " ", normalize-space( @class ), " "), " next ") ]/preceding-sibling::a[1]') if last_element is None: number_of_pages = 1 else: number_of_pages = int( last_element.text ) # data = [ getData( driver ) ] data.extend(getData(driver)) for i in range(number_of_pages - 1): driver.find_element_by_xpath('//a[ contains( concat( " ", normalize-space( @class ), " "), " next ") ]').click() data.extend( getData( driver ) ) time.sleep(1) return data
has title: Navigation using selenium in python
tagged with: selenium-webdriver
has comment: http://stackoverflow.com/comment/90925635
accepted answer: http://stackoverflow.com/a/51990165
linked to: http://stackoverflow.com/q/2356501
linked to: http://stackoverflow.com/q/51743859
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51987953
has answer: http://stackoverflow.com/a/51988540
possible better answer: http://stackoverflow.com/a/51987953
type: Question
has comment: http://stackoverflow.com/comment/90925418
has answer: http://stackoverflow.com/a/51990165
has comment: http://stackoverflow.com/comment/90925144
score: 0
answer count: 3
tagged with: selenium
tagged with: python

http://stackoverflow.com/comment/90868503
has text: The processor code imports only the class Instructions. If the user functions are an inherited class from Instructions, I would still need to load this new class into the instructions file.
comment on: http://stackoverflow.com/q/51959029
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52046552
type: Question
has title: Simulation using a Queue
downvote count: 0
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/91044555
answer count: 1
score: 1
tagged with: simulation
has comment: http://stackoverflow.com/comment/91068938
favorite count: 0
tagged with: exponential-distribution
type: UnansweredQuestion
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/91045132
has answer: http://stackoverflow.com/a/52046950
has body: I am trying to simulate the following simple scenario using a queue: "Students come to a professor's office to receive help on a homework assignment every 10 minutes exponentially distributed. The time to help a student is exponentially distributed with a mean of 7 minutes. What are the expected number of students waiting to be helped and the average waiting time before being helped? For what percentage of time is it expected there will be more than two students at the professor's office?" I started by making the following queue but I'm struggling how to create a global time clock and how to integrate students leaving the queue. import random as rd class Queue(object): def __init__(self): self.officeHasStudent = False self.totalTime = 0 self.numStudentsInLine = 0 def studentArrives(self, time): self.totalTime += time if self.officeHasStudent == False: self.officeHasStudent = True else: self.numStudentsInLine += 1 def __str__(self): temp = '' temp += 'Time Elapsed: ' + str(self.totalTime) + ' min\n' temp += 'number of students in line: ' + str(self.numStudentsInLine) return temp Q = Queue() for i in range(5): Q.studentArrives(rd.expovariate(1/10.0)) print(Q)
tagged with: queue

http://stackoverflow.com/comment/91103163
has text: Thank you for the explanation @EliKorvigo :) Also the down vote question wasn’t directed at you, just wanted to know why i was down voted by whoever did it. I feel like the question was following all guidelines set by Stackoverflow.
score: 0
comment on: http://stackoverflow.com/q/52054532
type: QuestionComment
type: Comment

http://stackoverflow.com/q/52076577
answer count: 3
tagged with: hadoop-streaming
has answer: http://stackoverflow.com/a/61624913
has comment: http://stackoverflow.com/comment/91102888
favorite count: 0
type: UnansweredQuestion
tagged with: python
downvote count: 1
has title: Error: java.lang.RuntimeException: PipeMapRed.waitOutputThreads(): subprocess failed with code 1, worked perfectly on local
has answer: http://stackoverflow.com/a/75776134
score: -1
type: Question
has body: I have googled this error on each and every forum but no luck. I have got the error written below: 18/08/29 00:24:53 INFO mapreduce.Job: map 0% reduce 0% 18/08/29 00:24:59 INFO mapreduce.Job: Task Id : attempt_1535105716146_0226_m_000000_0, Status : FAILED Error: java.lang.RuntimeException: PipeMapRed.waitOutputThreads(): subprocess failed with code 1 at org.apache.hadoop.streaming.PipeMapRed.waitOutputThreads(PipeMapRed.java:325) at org.apache.hadoop.streaming.PipeMapRed.mapRedFinished(PipeMapRed.java:538) at org.apache.hadoop.streaming.PipeMapper.close(PipeMapper.java:130) at org.apache.hadoop.mapred.MapRunner.run(MapRunner.java:61) at org.apache.hadoop.streaming.PipeMapRunner.run(PipeMapRunner.java:34) at org.apache.hadoop.mapred.MapTask.runOldMapper(MapTask.java:465) at org.apache.hadoop.mapred.MapTask.run(MapTask.java:349) at org.apache.hadoop.mapred.YarnChild$2.run(YarnChild.java:174) at java.security.AccessController.doPrivileged(Native Method) at javax.security.auth.Subject.doAs(Subject.java:422) at org.apache.hadoop.security.UserGroupInformation.doAs(UserGroupInformation.java:1688) at org.apache.hadoop.mapred.YarnChild.main(YarnChild.java:168) 18/08/29 00:25:45 INFO mapreduce.Job: Task Id : attempt_1535105716146_0226_r_000000_2, Status : FAILED Error: java.lang.RuntimeException: PipeMapRed.waitOutputThreads(): subprocess failed with code 1 at org.apache.hadoop.streaming.PipeMapRed.waitOutputThreads(PipeMapRed.java:325) at org.apache.hadoop.streaming.PipeMapRed.mapRedFinished(PipeMapRed.java:538) at org.apache.hadoop.streaming.PipeReducer.close(PipeReducer.java:134) at org.apache.hadoop.mapred.ReduceTask.runOldReducer(ReduceTask.java:454) at org.apache.hadoop.mapred.ReduceTask.run(ReduceTask.java:393) at org.apache.hadoop.mapred.YarnChild$2.run(YarnChild.java:174) at java.security.AccessController.doPrivileged(Native Method) at javax.security.auth.Subject.doAs(Subject.java:422) at org.apache.hadoop.security.UserGroupInformation.doAs(UserGroupInformation.java…
upvote count: 0
has comment: http://stackoverflow.com/comment/91107929
has answer: http://stackoverflow.com/a/52108698

http://stackoverflow.com/q/52052184
has answer: http://stackoverflow.com/a/76868886
type: Question
score: 3
tagged with: xlsxwriter
tagged with: dataframe
answer count: 3
has body: my data is dataframe ' how can i do it ? import xlsxwriter workbook = xlsxwriter.Workbook("test1.xlsx") worksheet = workbook.add_worksheet("sheli22") worksheet.add_table('B3:F7', {'data': data,'style': 'Table Style Light 17','header_row': False}) workbook.close()
downvote count: 0
favorite count: 0
has title: How to use xlsxwriter .add_table() method with a dataframe?
has answer: http://stackoverflow.com/a/52063000
tagged with: python
has answer: http://stackoverflow.com/a/72740411
upvote count: 3
type: UnansweredQuestion

http://stackoverflow.com/a/52073726
answers question: http://stackoverflow.com/q/52073396
type: Answer
has comment: http://stackoverflow.com/comment/91112032
has comment: http://stackoverflow.com/comment/91116394
has body: You can use os.path.join(), which joins a list of directories according to the rules of the platform it's run on. &gt;&gt;&gt; # windows &gt;&gt;&gt; os.path.join('projects', 'file.txt') projects\file.txt &gt;&gt;&gt; # mac osx &gt;&gt;&gt; os.path.join('projects', 'file.txt') projects/file.txt You can also use os.name to get the operating system the program is currently on so you can edit the start of your path accordingly.
score: 0

http://stackoverflow.com/comment/91140181
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52095093
has text: @AKX: in that case, he can just replace it. `old_dict = {...}`

http://stackoverflow.com/q/51964116
has comment: http://stackoverflow.com/comment/92691679
tagged with: uwsgi
type: Question
has title: uWSGI build flask application error how to solve
has body: Wrong when starting the flask application with uwsgi ModuleNotFoundError: No module named '_ssl' Directly in python3 Import ssl No error will be reported. Error message *** Operational MODE: preforking+threaded *** Traceback (most recent call last): File "text.py", line 2, in &lt;module&gt; From flask_restful import Api,Resource,reqparse File "/usr/local/python3/lib/python3.6/site-packages/flask_restful/__init__.py", line 5, in &lt;module&gt; From flask import request, url_for, current_app File "/usr/local/python3/lib/python3.6/site-packages/flask/__init__.py", line 21, in &lt;module&gt; From .app import Flask, Request, Response File "/usr/local/python3/lib/python3.6/site-packages/flask/app.py", line 25, in &lt;module&gt; From . import cli, json File "/usr/local/python3/lib/python3.6/site-packages/flask/cli.py", line 18, in &lt;module&gt; Import ssl File "/usr/local/python3/lib/python3.6/ssl.py", line 101, in &lt;module&gt; Import _ssl # if we can't import it, let the error propagate ModuleNotFoundError: No module named '_ssl' Unable to load app 0 (mountpoint='') (callable not found or import error) *** no app loaded. going in full dynamic mode *** Uwsgi configuration information [uwsgi] # uwsgi Address and port used at startup Socket = 127.0.0.1:8001 # pointing to the website directory Chdir = /root/wx_xiaochengxu/ # python Launcher file Wsgi-file = wx_api1.py # python application variable name to be started in the program Callable = app #processor number Processes = 4 # Threads Threads = 2 #Status detection address Stats = 127.0.0.1:9191
favorite count: 0
linked to: http://stackoverflow.com/q/12030809
has comment: http://stackoverflow.com/comment/90896394
score: 0
tagged with: python-3.x
answer count: 0
type: UnansweredQuestion
upvote count: 1
tagged with: python
downvote count: 1

http://stackoverflow.com/comment/91017432
has text: @bakas it happens to the best of us ;) don't forget to tick if it's ok!
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/52033631
type: Comment

http://stackoverflow.com/a/52004006
type: Answer
has body: Run again with admin priviledges
score: 1
upvote count: 1
accepted answer of: http://stackoverflow.com/q/52003889
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/52003889
downvote count: 0

http://stackoverflow.com/a/51964494
has body: flag is a tkinter IntVar, so flag == 3 will never be true. Instead, use flag.get() == 3. Also, when a correct answer is given, you increment flag twice, once in the clear function and once in the correct function. Also also, you run flagset (from clear) before you run totalset, so with the last answer total will not be updated before you show the score.
has comment: http://stackoverflow.com/comment/90881515
accepted answer of: http://stackoverflow.com/q/51964325
answers question: http://stackoverflow.com/q/51964325
type: AcceptedAnswer
score: 0
has comment: http://stackoverflow.com/comment/90879297
type: Answer

http://stackoverflow.com/q/52064478
has comment: http://stackoverflow.com/comment/91080276
score: 0
has comment: http://stackoverflow.com/comment/91081318
has comment: http://stackoverflow.com/comment/91080297
answer count: 1
has title: (Django) Limited ForeignKey choices by Current User
has comment: http://stackoverflow.com/comment/91079958
has comment: http://stackoverflow.com/comment/91081835
has comment: http://stackoverflow.com/comment/91079717
has comment: http://stackoverflow.com/comment/91080029
has body: Update Thanks to Michael I was able to get this to work perfectly in my CreateView, but not in the UpdateView. When I try to set a form_class it spits out an improperly configured error. How can I go about filtering the ForeignKey in the updateview? End Update I have a feeling I'm missing something small here but I've been working on it for a while and can't figure it out. I have an app called story universe where the user creates one with a name and description. I then have a character creator class where the user can create a character within that universe. This all works fine, except when the user goes to create their character they see a list of all universes created by all users. Then there are other apps that will also mimic what I'm trying to do with the character creator. I need to limit the Story Universes to only those created by the currently logged in user. I've tried a few different ways and had the most success with the following, but with this code, no Universe appears when trying to create a new character. models.py: class Universe(models.Model): user = models.ForeignKey(User,related_name='universe',on_delete=models.CASCADE) name = models.CharField(max_length=100, unique=True) description = models.TextField(max_length=2000,blank=True,default="") def __str__(self): return self.name def get_absolute_url(self): return reverse('universe:singleuniverse',kwargs={'pk': self.pk}) class Meta: ordering = ['name'] unique_together = ['user','name'] class Character(models.Model): user = models.ForeignKey(User,related_name='characters',on_delete=models.CASCADE) universe = models.ForeignKey("story_universe.Universe", on_delete=models.CASCADE) name = models.CharField(max_length=255,unique=True) def __str__(self): return self.name def get_absolute_url(self): return reverse('character_developer:singlecharacter',kwargs={'pk': self.pk}) class Meta(): ordering = ['name'] unique_together=['user','name'] views.py: class CreateCharacter(LoginRequiredMixin,generic.CreateView…
tagged with: django
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52064785
accepted answer: http://stackoverflow.com/a/52064785
has comment: http://stackoverflow.com/comment/91080134
has comment: http://stackoverflow.com/comment/91080120
type: Question
linked to: http://stackoverflow.com/q/52065617
has comment: http://stackoverflow.com/comment/91081332

http://stackoverflow.com/q/52073870
has comment: http://stackoverflow.com/comment/91097447
has comment: http://stackoverflow.com/comment/91097655
score: -4
upvote count: 1
has comment: http://stackoverflow.com/comment/91097789
has comment: http://stackoverflow.com/comment/91097883
has title: The unequal width between axes causes non-diagonal lines
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/52074044
tagged with: matplotlib
downvote count: 5
type: Question
has comment: http://stackoverflow.com/comment/91097827
answer count: 1
has body: import numpy as np import matplotlib.pyplot as plt x=np.arange(-2,4,0.1) y1=x y2=-x fig=plt.figure(figsize=(8,8)) plt.plot(x,y1) plt.plot(x,y2) Now I have drawn a graph of y=x and y=-x. It's known to all that y=x and y=-x should be diagonal lines. However, because of the inequality of width between x axis and y axis with the same 1 unit distance, the lines are not diagonal. That's a wrong graph. I have also set the canvas to be a square to avoid such problem. It doesn't work. How to draw a correct y=x and y=-x? Thanks for your help!
has comment: http://stackoverflow.com/comment/91097683
favorite count: 0
has answer: http://stackoverflow.com/a/52074044
has comment: http://stackoverflow.com/comment/91097519
tagged with: python
has comment: http://stackoverflow.com/comment/91097813

http://stackoverflow.com/comment/91001584
score: 1
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52024844
has text: Thank you for answering my question and adding precise information about `create_task`

http://stackoverflow.com/q/52005830
has comment: http://stackoverflow.com/comment/90961636
type: Question
has comment: http://stackoverflow.com/comment/90961657
has title: To unpack a zip file from url request
upvote count: 3
tagged with: http://stackoverflow.com/tag/csv
answer count: 1
downvote count: 1
tagged with: url
has body: I want to get this XML file from a danish website with the URL https://www.foedevarestyrelsen.dk/_layouts/15/sdata/smileystatus.zip, but the data comes in a zip file. This is problematic because I want to get the data sheet directly into Python for a school project, and not to save it local and convert it into csv. So far I have tried following codes inspired from answers to previous questions about this subject.... from zipfile import ZipFile from io import BytesIO import requests import pandas as pd def get_zip(file_url): url = requests.get(file_url) zipfile = ZipFile(BytesIO(url.content)) zip_names = zipfile.namelist() if len(zip_names) == 1: SmileyStatus = zip_names.pop() extracted_file = zipfile.open("SmileyStatus.xls") return extracted_file xls = get_zip("https://www.foedevarestyrelsen.dk/_layouts/15/sdata/smileystatus.zip") data = pd.read_excel(xls) and I have also tried: from zipfile import ZipFile import requests import pandas as pd url = 'https://www.foedevarestyrelsen.dk/_layouts/15/sdata/smileystatus.zip' df = pd.read_csv(url, compression = "zip")
favorite count: 0
tagged with: http://stackoverflow.com/tag/xml
tagged with: http://stackoverflow.com/tag/zip
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90962814
tagged with: python
score: 2
has answer: http://stackoverflow.com/a/71061929

http://stackoverflow.com/comment/91025501
has text: @JoseRuiz Sorry, missed the fact you are calling `fetchall`. See the updated answer
type: AnswerComment
comment on: http://stackoverflow.com/a/52037624
type: Comment
score: 1

http://stackoverflow.com/comment/112521578
score: 0
comment on: http://stackoverflow.com/q/52068664
has text: If you're using G-suite, you can delegate domain wide access to your service account and have it upload the file as the owner [Reference](https://stackoverflow.com/questions/24560314/quota-orphaned-files-and-uploads-using-service-account-with-google-drive-api?rq=1)
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/91035922
type: Comment
has text: This looks like a certificate error... there is a version of 2.7 that gives the same error try 3.6 or 3.5.6 or something... you can also sudo apt-get uninstall python-pip. And try reinstalling with easy_install
comment on: http://stackoverflow.com/q/52042226
score: 0
type: QuestionComment

http://stackoverflow.com/q/52067058
has answer: http://stackoverflow.com/a/52067412
answer count: 4
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/66247489
tagged with: uuid
possible better answer: http://stackoverflow.com/a/52067412
score: 17
tagged with: sqlalchemy
upvote count: 17
type: Question
accepted answer: http://stackoverflow.com/a/52071275
linked to: http://stackoverflow.com/q/30340380
has comment: http://stackoverflow.com/comment/91085038
has answer: http://stackoverflow.com/a/59883971
downvote count: 0
has body: I'm trying to create objects in Postgres db. I'm using this approach https://websauna.org/docs/narrative/modelling/models.html#uuid-primary-keys class Role(Base): __tablename__ = 'role' # Pass `binary=False` to fallback to CHAR instead of BINARY id = sa.Column(UUIDType(binary=False), primary_key=True) But when I create object user_role = Role(name='User') db.session.add(user_role) db.session.commit() I have the following error: sqlalchemy.exc.IntegrityError: (psycopg2.IntegrityError) null value in column "id" violates not-null constraint Looks like I didn't provide any ID. So, how I can make the database auto-generate it or generate on my own?
favorite count: 0
tagged with: postgresql
has answer: http://stackoverflow.com/a/52071275
has title: How to autogenerate UUID for Postgres in Python?
tagged with: python

http://stackoverflow.com/q/52049128
type: Question
has title: Can't put print statement in generator
downvote count: 0
has body: What's going on here? Why doesn't the latter work? def foo(arg): print(arg) for _ in (foo(x) for x in range(10)): pass # Works for _ in (print(x) for x in range(10)): pass # Doesn't work
has comment: http://stackoverflow.com/comment/91048989
accepted answer: http://stackoverflow.com/a/52049149
answer count: 1
tagged with: python
favorite count: 0
upvote count: 2
tagged with: generator
type: AnsweredQuestion
score: 2
has answer: http://stackoverflow.com/a/52049149
has comment: http://stackoverflow.com/comment/91048991
has comment: http://stackoverflow.com/comment/91048996

http://stackoverflow.com/comment/91086583
has text: Hey, Thank you a ton. You were the only one willing to help. Cheers.
type: Comment
score: 0
comment on: http://stackoverflow.com/a/52067209
type: AnswerComment

http://stackoverflow.com/a/75776134
type: Answer
answers question: http://stackoverflow.com/q/52076577
score: 0
has body: For me it was changing #!/usr/bin/env python to #!/usr/bin/env python3

http://stackoverflow.com/q/51991675
accepted answer: http://stackoverflow.com/a/51992369
tagged with: python
has comment: http://stackoverflow.com/comment/90933347
type: AnsweredQuestion
type: Question
score: 0
has comment: http://stackoverflow.com/comment/90933088
answer count: 1
has answer: http://stackoverflow.com/a/51992369
has title: Recursion not happening in a Class unless I use a helper method
has comment: http://stackoverflow.com/comment/90933038
has comment: http://stackoverflow.com/comment/90933116
linked to: http://stackoverflow.com/q/8991840
tagged with: python-3.x
has body: I was coding the dfs solution for a problem. When I write the code as below, on debugging, I find that whenever the code reaches at self.dfs_solution_rework, instead of recursing, it just continues execution, leading to wrong results.: def dfs_solution_rework(self, end, start= 1, sorted=False, num= None): if not num: for i in range(1, 10): self.dfs_solution_rework(end, start, num=i) elif num &lt;= end: if num &gt;= start: yield num last_digit = num % 10 if not (last_digit == 0 or last_digit == 9): self.dfs_solution_rework(end, start, num=num * 10 + (last_digit - 1)) self.dfs_solution_rework(end, start, num=num * 10 + (last_digit + 1)) elif last_digit == 0: self.dfs_solution_rework(end, start, num=num * 10 + 1) else: self.dfs_solution_rework(end, start, num=num * 10 + 8) On the other hand, if I write the dfs with a util (helper) method, as follows, it works without any issues. def dfs_solution(self, end, start= 1, sorted=False, num= None): def dfs_util(end, start, num): if num &lt;= end: if num &gt;= start: print(num) last_digit = num % 10 if not (last_digit == 0 or last_digit == 9): dfs_util(end, start, num=num * 10 + (last_digit - 1)) dfs_util(end, start, num=num * 10 + (last_digit + 1)) elif last_digit == 0: dfs_util(end, start, num=num * 10 + 1) else: dfs_util(end, start, num=num * 10 + 8) for i in range(1, 10): dfs_util(end, start, num=i) Any help as to why this behaviour might be happening ? I have debugged it in VS Code to understand but couldn't get any idea. PS: Not a homework problem. :) Thanks

customization
tags question: http://stackoverflow.com/q/52041545
type: Tag
tag name: customization

http://stackoverflow.com/q/52057307
tagged with: python-3.6
has comment: http://stackoverflow.com/comment/91086242
has comment: http://stackoverflow.com/comment/91069431
answer count: 2
accepted answer: http://stackoverflow.com/a/52179522
upvote count: 0
has comment: http://stackoverflow.com/comment/91064757
has comment: http://stackoverflow.com/comment/91308817
has comment: http://stackoverflow.com/comment/91090679
has title: PyImport_Import return null when import pyodbc
favorite count: 0
tagged with: python
type: AnsweredQuestion
tagged with: windows-7
has comment: http://stackoverflow.com/comment/91086340
has body: I use the python example from https://docs.python.org/3/extending/embedding.html. every thing is right until I added one line import pyodbc in the 'multiply.py' file. PyImport_Import will return null if i add this line,and PyErr_Print() show that no module named pyodbc. but actually, i have install pyodbc with pip,and i run 'multiply.py' with no problem on command line. Is something wrong?
downvote count: 2
possible better answer: http://stackoverflow.com/a/55947896
has answer: http://stackoverflow.com/a/55947896
has comment: http://stackoverflow.com/comment/91085885
type: Question
has comment: http://stackoverflow.com/comment/91309077
has comment: http://stackoverflow.com/comment/91303296
score: -2
has answer: http://stackoverflow.com/a/52179522

http://stackoverflow.com/q/52077150
type: UnansweredQuestion
upvote count: 0
has body: When I'm trying to make an external connection via socket(LIKE CHAT APPLICATION) python I get [Errno 111] Connection refused Image : Client Code : while True: try: self.connection = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.connection.connect((ip, port)) break except socket.error as e: print(str(e)) time.sleep(5) continue self.reliable_send(platform.platform()) Server image: Server Code: def __init__(self, ip="0.0.0.0", port=55000): self.listener = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.listener.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) self.listener.bind((ip, port)) self.listener.listen(1) print("[+] Waiting for incoming connections") (self.connection, address) = self.listener.accept() print("[+] Got a connection from :" + address[0]) print("[+] Victim operating system :" + self.reliable_receive()) What is the error? I already open this port on my server and the application running on it but it does not get any connection on it! Thanks
answer count: 1
has comment: http://stackoverflow.com/comment/91105743
favorite count: 0
type: Question
tagged with: sockets
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/91106043
has answer: http://stackoverflow.com/a/52077221
tagged with: tcp
has comment: http://stackoverflow.com/comment/91105160
downvote count: 1
has comment: http://stackoverflow.com/comment/91106437
tagged with: network-programming
has title: [Python]Socket external connection error
tagged with: server

http://stackoverflow.com/q/52050346
has comment: http://stackoverflow.com/comment/91051042
has body: infile = open('abc.csv', "r") infile1 = open('xyz.csv', "r") infile2 = open('pqr.csv', "r") I am trying to read 3 csv files into infile, infile1, infile2. After that i have to pass them to a function. The problem is when i am trying to pass directly in, in1, in2 as arguments its showing ValueError: invalid literal for int() with base 10: convert_to(infile, infile1, infile2) def convert_to(..,..,..) How can i pass in, in1, in2 as arguments to the function definition and call? Is this the right way then why it is showing this error. Is there any other better and efficient way to do this?
score: 0
tagged with: file
has title: Passing csv files as arguments to a function
has comment: http://stackoverflow.com/comment/91051057
type: Question
has answer: http://stackoverflow.com/a/52050676
has answer: http://stackoverflow.com/a/52050407
possible better answer: http://stackoverflow.com/a/52050472
accepted answer: http://stackoverflow.com/a/52050676
has answer: http://stackoverflow.com/a/52050472
has answer: http://stackoverflow.com/a/52050463
tagged with: function
has comment: http://stackoverflow.com/comment/91052707
has comment: http://stackoverflow.com/comment/91050948
has comment: http://stackoverflow.com/comment/91051787
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
answer count: 4
type: AnsweredQuestion

http://stackoverflow.com/comment/91031716
type: Comment
has text: The issue appears to be that the [`event` Python module](https://pypi.org/project/event/) won't build, likely due to its [documented dependency on `libevent` 1.4.x](https://github.com/jaraco/pyevent#pyevent). For comparison, my OS-provided `libevent` is at version 2.1.8. I haven't been able to get this to build yet, but Ubuntu has a [`libevent-1.4-2` package](https://packages.ubuntu.com/bionic/libevent-1.4-2). Maybe installing that will work? I'll try it myself in a VM when I get a moment.
comment on: http://stackoverflow.com/a/52028183
score: 0
type: AnswerComment

http://stackoverflow.com/comment/91039711
has text: you want to know only if there are missing or what the missing dates are?
type: Comment
type: QuestionComment
score: 2
comment on: http://stackoverflow.com/q/52044348

http://stackoverflow.com/a/51960740
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/90872901
score: 0
has comment: http://stackoverflow.com/comment/90872845
type: Answer
accepted answer of: http://stackoverflow.com/q/51960471
has comment: http://stackoverflow.com/comment/90872364
has body: Keras deals with sessions implicitly, which means you mostly don't need to worry about it. If you want to fetch the current session, you can use: from keras import backend as K K.get_session(). If you want to define a tensorflow session and make Keras use it to initialize all variables: import tensorflow as tf sess = tf.Session() from keras import backend as K K.set_session(sess)
answers question: http://stackoverflow.com/q/51960471
has comment: http://stackoverflow.com/comment/90873605

http://stackoverflow.com/comment/91074303
type: Comment
comment on: http://stackoverflow.com/a/52047814
has text: hello, when I load my server and run the site it runs fine its when I test my code on the terminal is where I'm having these problems =/ would that still be a problem?
type: AnswerComment
score: 0

http://stackoverflow.com/a/52083532
answers question: http://stackoverflow.com/q/52048655
type: Answer
downvote count: 0
score: 2
has body: Every program is represented through one process. A process is the execution context one or multiple threads operate in. All threads in one process share the same tranche of virtual memory assigned to the process. Python (refering to CPython, e.g. Jython and IronPython have no GIL) is special because it has the global interpreter lock (GIL), which prevents threaded python code from being run on multiple cores in parallel. Only code releasing the GIL can operate truely parallel (I/O operations and some C-extensions like numpy). That's why you will have to use the multiprocessing module for cpu-bound python-code you need to run in parallel. Processes startet with the multiprocessing module then will run it's own python interpreter instance so you can process code truely parallel. Note that even a single threaded python-application can run on different cores, not in parallel but sequentially, in case the OS re-schedules execution to another core after a context switch took place. Back to your question: if I create multiple processes inside a child thread will they be limited to that single core too? You don't create processes inside a thread, you spawn new independent python-processes with the same limitations of the original python process and on which cores threads of the new processes will execute is up to the OS (...as long you don't manipulate the core-affinity of a process, but let's not go there).
upvote count: 2

http://stackoverflow.com/q/51983632
has comment: http://stackoverflow.com/comment/90916722
tagged with: python
has comment: http://stackoverflow.com/comment/90920742
has comment: http://stackoverflow.com/comment/90916854
type: AnsweredQuestion
type: Question
has answer: http://stackoverflow.com/a/51993644
has comment: http://stackoverflow.com/comment/90919699
has body: I am trying to read the following format (Intel -&gt; Little-Endian): X: 0 -&gt; 31, size 32 bits Offset: 32 -&gt; 43, size 12 bits Index: 44 -&gt; 47, size 4 bits Time: 48 -&gt; 55, size 8 bits Radius: 56 -&gt; 63, size 8 bits For this parser I defined: from construct import Bitwise, BitStruct, BitsInteger from construct import Int32sl, Int8ul BitStruct( "X" / Bytewise(Int32sl), "Offset" / BitsInteger(12), "Index" / BitsInteger(4), "Time" / Bytewise(Int8ul), "Radius" / Bytewise(Int8ul), ) from the folloing bytes: bytearray(b'\xca\x11\x01\x00\x00\x07\xffu') What I get is: Container: X = 70090 Offset= 0 Index = 7 Time = 255 Radius = 117 What I should have gotten is: Container: X = 70090 Offset = 1792 Index = 0 Time = 255 Radius= 117 As you can see, the values of Offset and Index that I get do not match with the expected values, the rest is correct. From what I saw, i need to swap the two byes, which contains the Offset and Index values. How could I define a struct inside a struct and swap the two bytes as well?
possible better answer: http://stackoverflow.com/a/51985847
has title: Define a BitStruct inside a BitStruct in python using construct package
has comment: http://stackoverflow.com/comment/90916879
has answer: http://stackoverflow.com/a/51985847
score: 0
answer count: 2
has comment: http://stackoverflow.com/comment/90916806
accepted answer: http://stackoverflow.com/a/51993644
has comment: http://stackoverflow.com/comment/90920949

http://stackoverflow.com/a/51959669
has comment: http://stackoverflow.com/comment/90870002
upvote count: 1
downvote count: 0
has body: I assume that each day (0 through 4) is mentioned somewhere in your dataframe at least once. Make the id and the day a MultiIndex (set_index) and convert the dataframe into a table (unstack). There will be missing values (missing days for some id's), set them to zeros (fillna). Then convert the table back to a vector (stack) and convert the index back to the columns (reset_index). df1 = df.set_index(['id', 'day']).unstack().fillna(0)\ .stack().reset_index().astype(object) The dataframe must be converted to the type object, otherwise the assignment of lists to a column won't work. Now, replace the 0s with the lists of your choice: df1.loc[df1['value'] == 0, 'value'] = [[0, 0, 0]] Note that you should assign a one-element list that contains your desired list.
type: Answer
answers question: http://stackoverflow.com/q/51959497
score: 1
has comment: http://stackoverflow.com/comment/90869945

http://stackoverflow.com/comment/91171291
score: 0
type: Comment
type: QuestionComment
has text: Then you not only want the leaves of the Tree object but the leaves of Tree or str? It's unclear what's the purpose. Could you give several more inputs / outputs?
comment on: http://stackoverflow.com/q/52107825

http://stackoverflow.com/comment/91219489
type: Comment
type: QuestionComment
has text: Maybe it is just your slimmed down example, but you never add your subprocess `p` to `procs`. Thus, the current program will not wait for your subprocesses to finish. I guess that could lead to odd problems down the road.
comment on: http://stackoverflow.com/q/52064036
score: 0

http://stackoverflow.com/a/52047375
has comment: http://stackoverflow.com/comment/108308628
type: Answer
downvote count: 0
score: 3
has body: I prefer storing my .txt as a json file. My filename looking like : { "foo": "bar" } From here, you can have import json #Read JSON data into the datastore variable if filename: with open(filename, 'r') as f: datastore = json.load(f) #Use the new datastore datastructure print datastore["foo"]
has comment: http://stackoverflow.com/comment/91045766
upvote count: 3
answers question: http://stackoverflow.com/q/52047314

http://stackoverflow.com/q/52012279
has comment: http://stackoverflow.com/comment/90976627
has title: Most efficient way to break up a dataframe using multiple DateTimeIndexes
tagged with: pandas
downvote count: 0
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/90977995
has answer: http://stackoverflow.com/a/52012422
type: UnansweredQuestion
tagged with: python
has body: I have a dataframe which contains prices for a security each minute over a long period of time. I would like to extract a subset of the prices, 1 per day between certain hours. Here is an example of brute-forcing it (using hourly for brevity): dates = pandas.date_range('20180101', '20180103', freq='H') prices = pandas.DataFrame(index=dates, data=numpy.random.rand(len(dates)), columns=['price']) I now have a DateTimeIndex for the hours within each day I want to extract: start = datetime.datetime(2018,1,1,8) end = datetime.datetime(2018,1,1,17) day1 = pandas.date_range(start, end, freq='H') start = datetime.datetime(2018,1,2,9) end = datetime.datetime(2018,1,2,13) day2 = pandas.date_range(start, end, freq='H') days = [ day1, day2 ] I can then use prices.index.isin with each of my DateTimeIndexes to extract the relevant day's prices: daily_prices = [ prices[prices.index.isin(d)] for d in days] This works as expected: daily_prices[0] daily_prices[1] The problem is that as the length of each selection DateTimeIndex increases, and the number of days I want to extract increases, my list-comprehension slows down to a crawl. Since I know each selection DateTimeIndex is fully inclusive of the hours it encompasses, I tried using loc and the first and last element of each index in my list comprehension: daily_prices = [ prices.loc[d[0]:d[-1]] for d in days] Whilst a bit faster, it is still exceptionally slow when the number of days is very large Is there a more efficient way to divide up a dataframe into begin and end time ranges like above?
upvote count: 3
type: Question
score: 3

http://stackoverflow.com/a/52020240
answers question: http://stackoverflow.com/q/52017470
has comment: http://stackoverflow.com/comment/109234397
score: 4
upvote count: 4
has body: Let's add two binary variables y_0 and y_1: y = m.addVars(2, vtype=GRB.BINARY, name="y") Now you can add two indicator constraints: # If y[0] == 1, then quicksum(x.select(8, '*')) == 2 m.addConstr((y[0] == 1) &gt;&gt; (quicksum(x.select(8, '*')) == 2)) # If y[1] == 1, then quicksum(x.select(8, '*')) == 3 m.addConstr((y[1] == 1) &gt;&gt; (quicksum(x.select(8, '*')) == 3)) Next you add the constraint m.addConstr(y[0] + y[1] == 1) This ensures that only one of these two variables can be 1 and thus the sum is either 2 or 3.
accepted answer of: http://stackoverflow.com/q/52017470
type: AcceptedAnswer
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/109228895

http://stackoverflow.com/q/52052566
has answer: http://stackoverflow.com/a/52052858
score: -1
has comment: http://stackoverflow.com/comment/91055615
answer count: 3
downvote count: 1
has comment: http://stackoverflow.com/comment/91055510
has title: File handling using Python - Print daily value sums
favorite count: 0
has comment: http://stackoverflow.com/comment/91055453
tagged with: file-handling
tagged with: python-3.x
has answer: http://stackoverflow.com/a/52052660
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/91055358
upvote count: 0
has body: I need to write a function print_daily_totals(filename) that takes the name of such a file as a parameter and reads the data from the file, printing the total of the readings for each day in the format given below. Days should be printed out in the same order as in the input file. For each line in the input file I should print an output line in the format date = total, with the total given to 2 decimal places. For example, with the simple 2-line input file above, the output would be: 2010-01-01 = 30.00 2010-01-02 = 115.30 The file contains: 2006-04-10,836.2,563.263 2006-04-11,462.06,1694.3,666.0 2006-04-12,1318.19,1485.62 The call statement will be print_daily_totals('data.txt') The expected output must be: 2006-04-10 = 1399.46 2006-04-11 = 2822.36 2006-04-12 = 2803.81 I am still beginning file handling in Python. So, any help would be appreciated.
type: Question
has answer: http://stackoverflow.com/a/52053076

http://stackoverflow.com/comment/91144490
has text: @FHTMitchell You are probably right, that the reader does not need to care about the singleton nature of `t`. However, I thought we would be nice to make it obvious, that we are not discarding any returned values. Is there a particular reason for avoiding `*_`?
type: QuestionComment
comment on: http://stackoverflow.com/q/52096923
score: 0
type: Comment

http://stackoverflow.com/comment/115687283
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52047847
has text: You can try https://johannesbuchner.github.io/UltraNest/ instead, with MPI.
score: 0

http://stackoverflow.com/a/52046116
upvote count: 3
has body: Use df.at for single cell assignment. df.at[('ds1', 'cl1', 're1'), (1, 1)] = somevalue You can also use loc but is not as quick for use on single cells. df.loc[('ds1', 'cl1', 're1'), (1, 1)] = somevalue
accepted answer of: http://stackoverflow.com/q/52046094
answers question: http://stackoverflow.com/q/52046094
type: AcceptedAnswer
downvote count: 0
type: Answer
score: 3

http://stackoverflow.com/comment/133272008
has text: @user2399432 They now have a "Current File" option that will run the active file.
comment on: http://stackoverflow.com/a/52030559
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/a/52028289
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/52025970
type: Answer
score: 2
upvote count: 2
has body: it's just a simple query as Daniel mentioned above notice that you have a foreign key: documents = Document.objects.all().filter(course_name__courses__iexact=file_name) context["documents"] = documents
accepted answer of: http://stackoverflow.com/q/52025970

http://stackoverflow.com/comment/91645122
comment on: http://stackoverflow.com/a/52095244
score: 0
type: AnswerComment
type: Comment
has text: It gives the error: Period('1961-01', 'M') is not a string for the command: ax.plot(df-all)

http://stackoverflow.com/a/52097429
has body: This line: corr=df.rolling(20).corr(df[df.columns[i]],df[df.columns[j]]) will produce an error because the second argument of corr expects a Bool but you passed a DataFrame which has an ambiguous truth value. You can view the docs here. Does applying the rolling method to the first DataFrame in the second line of code that you provided achieve what you are trying to do? corr = df[df.columns[i]].rolling(20).corr(df[df.columns[j]])
type: Answer
answers question: http://stackoverflow.com/q/52094901
has comment: http://stackoverflow.com/comment/91145672
score: 1
upvote count: 1
accepted answer of: http://stackoverflow.com/q/52094901
downvote count: 0
type: AcceptedAnswer

http://stackoverflow.com/comment/91009987
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/52018681
type: Comment
has text: So I'm sorry, I give up. I'm not able to help you while you will not help me (and probably others, too) understand what you want. E. g.: **I have a workbook with 3 sheets with names People, Things, Animals and I want to assign the string "People" to the variable ws1, string "Things" to variable ws2, and so on**. BTW, it is as how I understood your question. You motivation will be probably helpful, too.

http://stackoverflow.com/a/52051226
accepted answer of: http://stackoverflow.com/q/52050755
answers question: http://stackoverflow.com/q/52050755
has comment: http://stackoverflow.com/comment/91053428
has comment: http://stackoverflow.com/comment/91053185
has comment: http://stackoverflow.com/comment/91053594
score: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/91053619
has comment: http://stackoverflow.com/comment/91053499
has body: EDIT: As there are several unwanted lines in the logfile, not only "Not found...", I assume all valid lines begin with a square bracket like the date rows above. At first, I'd read all lines which are valid into a list: log = [] with open ('/wherever/file/may/roam/logfile.log', 'r') as logfile: for row in logfile.readlines(): if row[0] == '[': log.append(row) With StringIO from the io-module you can feed this into the dataframe-creation of pandas: from io import StringIO df = pd.read_fwf(StringIO(''.join(log)), colspecs=[(1, 21), (23, None)], header=None) You can read this log file with pandasin a dataframe like this import pandas as pd df = pd.read_fwf('/wherever/file/may/roam/logfile.log', colspecs=[(1, 21), (23, None)], comment='o', header=None) Here I used 'read fixed width file', because of the equal-length date at the beginning. I already cut off the brackets by reading from the second character on (colspecs), so the signal character for lines to be skipped via the comment keyword is the 'o' of 'Not'. Call it misuse, but it works here well. Then header=None is because your file has no column descriptors as a first line. Result is this dataframe: df 0 1 0 22/Aug/2018 10:07:14 "GET /api HTTP/1.1" 404 2318 1 22/Aug/2018 10:30:30 "GET /api HTTP/1.1" 404 2318 2 22/Aug/2018 10:30:33 "GET /api HTTP/1.1" 404 2318 3 22/Aug/2018 10:37:08 "POST /api/entity/ HTTP/1.1" 201 83 4 22/Aug/2018 10:37:40 "GET /api/entity/ HTTP/1.1" 200 412 5 22/Aug/2018 10:37:41 "POST /api/datasets/ HTTP/1.1" 201 115 With df[0] = pd.to_datetime(df[0]) we turn the date of type string into a datetime format we can calculate with. Then we need a function to calculate n seconds back from the last entry: thrshld = lambda n: df[0].values[-1] - n*10**9 The datetime values in df[0] are of type numpy.datetime64, which has a nanosecond resolution, therefore the factor 10**9. Now you can index your dataframe like df[df[0]&gt;thrshld(5)] Out: 0 1 4 2018-08-22 10:37:40 "GET /api/entity/ HTTP/1.1" 200 412 5 2…
has comment: http://stackoverflow.com/comment/91053328
type: Answer

http://stackoverflow.com/comment/91078438
type: Comment
comment on: http://stackoverflow.com/q/52063759
score: 1
has text: @Aran-Fey did you try to write the code? As I said it doesn't work with the an instance, see my edit
type: QuestionComment

http://stackoverflow.com/comment/92572632
score: 0
comment on: http://stackoverflow.com/q/51961712
type: Comment
type: QuestionComment
has text: Btw... did you mean to misspell "Municipality" in `city`?

http://stackoverflow.com/q/52079640
type: AnsweredQuestion
upvote count: 3
accepted answer: http://stackoverflow.com/a/52080525
downvote count: 3
has answer: http://stackoverflow.com/a/52080807
type: Question
has comment: http://stackoverflow.com/comment/91110185
tagged with: algorithm
possible better answer: http://stackoverflow.com/a/52080807
has comment: http://stackoverflow.com/comment/91109777
tagged with: python-2.7
score: 0
answer count: 3
tagged with: python-2.x
has answer: http://stackoverflow.com/a/52080525
favorite count: 0
has title: Build hierarchized strings
has body: Suppose I have the following method: def _build_hierarchy(*keys): # ... If I call _build_hierarchy('a', 'b', 'c', 'd'), I expect to get the following sequence of str: [ 'a', 'a:b', 'a:c', 'a:d', 'a:b:c', 'a:b:d', 'a:b:c:d' ] Notice that hierarchy is based on the order on which I provided the arguments. To be honest, I have no idea how to approach this. Ideally, I would like a really simple and pythonic solution if there is such thing. Note: Solution needs to be compatible Python 2.7
has answer: http://stackoverflow.com/a/52079928
tagged with: python

http://stackoverflow.com/comment/90910035
type: Comment
score: 1
has text: You need to put `Open` in quotes.
type: AnswerComment
comment on: http://stackoverflow.com/a/51980127

http://stackoverflow.com/comment/91061535
has text: please post a proper MVC if you hope to get a serious answer. This being said, I can only second Daniel Roseman and Marcos Schroh: if you're using Django with a relational database, not using the ORM is a complete WTF.
type: Comment
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/52054905

http://stackoverflow.com/comment/90938932
has text: Which Python version are you using ? Because f-strings are available only in Python 3.6+...
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51994202

http://stackoverflow.com/comment/91035822
type: Comment
type: QuestionComment
has text: `a == b` *will* disregard order so I think normal dict comparison does exactly what you want already??
score: 1
comment on: http://stackoverflow.com/q/52042430

http://stackoverflow.com/comment/106178173
has text: I had to modify this Line of assigning to self.id as below: self.id = "{}{:05d}".format('A', int(max[1:]) if max is not None else 1) Observer the slicing done and conversion to int in max variable. Now to solve the problem of getting the correct id_max, I followed the this: custom=Custom.objects.last() (new line) max=custom.id if custom is not None else None
comment on: http://stackoverflow.com/a/52070665
score: 1
type: AnswerComment
type: Comment

http://stackoverflow.com/a/55909785
answers question: http://stackoverflow.com/q/52091033
downvote count: 0
score: 1
type: Answer
upvote count: 1
has body: This should do what you're looking for. You can return the underlying Plotly figure from Cufflinks with asFigure=True and access the legend position with my_fig.layout.legend=dict(x=-.1, y=.1). You can adjust the x and y values as needed to move the legend. df = pd.DataFrame(np.random.randn(1000, 2), columns=['A', 'B']).cumsum() my_fig = df.iplot(asFigure=True) my_fig.layout.legend=dict(x=-.1, y=.1) my_fig.iplot(filename='line-example.html') You can also see the values for the Plotly figure you create in a Jupyter Notebook with my_fig.

http://stackoverflow.com/comment/91070752
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52060093
has text: @FHTMitchell I gived you an example of the structure of the dataframe, sometime the col_3 is empty between too ||
score: 0

http://stackoverflow.com/q/52022575
downvote count: 0
accepted answer: http://stackoverflow.com/a/52027930
favorite count: 0
has body: I'm working on a scheduling optimization problem where we have a set of tasks that need to be completed within a certain timeframe. Each task has a schedule that specifies a list of time slots when it can be performed. The schedule for each task can be different depending on the weekday. Here is small sample (reduced number of tasks and time slots): task_availability_map = { "T1" : [0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0], "T2" : [0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "T3" : [0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0], "T4" : [0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0], "T5" : [0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0], "T6" : [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0], "T7" : [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0], "T8" : [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0], "T9" : [0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0], "T10": [0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0] } The constraint is that only up to N tasks can be performed in parallel within the same time slot (if they overlap). The group of parallel tasks always takes the same amount of time regardless of whether 1 or N are being done. The objective is to minimize the number of time slots. I've tried a brute force approach that generates all time slot index permutations. For each index in a given permutation, get all tasks that can be scheduled and add them to a list of tasks to be excluded in the next iteration. Once all iterations for a given permutation are completed, add the number of time slots and the combination of indices to a list. def get_tasks_by_timeslot(timeslot, tasks_to_exclude): for task in task_availability_map.keys(): if task in tasks_to_exclude: continue if task_availability_map[task][timeslot] == 1: yield task total_timeslot_count = len(task_availability_map.values()[0]) # 17 timeslot_indices = range(total_timeslot_count) timeslot_index_permutations = list(itertools.permutations(timeslot_indices)…
score: 6
tagged with: python
tagged with: linear-programming
upvote count: 6
has comment: http://stackoverflow.com/comment/91004334
type: AnsweredQuestion
tagged with: job-scheduling
has answer: http://stackoverflow.com/a/52027930
type: Question
tagged with: or-tools
has comment: http://stackoverflow.com/comment/90995717
tagged with: algorithm
has comment: http://stackoverflow.com/comment/90999603
has title: Scheduling optimization to minimize the number of timeslots (with constraints)
answer count: 1

http://stackoverflow.com/a/51997184
score: 5
type: AcceptedAnswer
type: Answer
upvote count: 5
accepted answer of: http://stackoverflow.com/q/51992154
answers question: http://stackoverflow.com/q/51992154
has body: The good news is that your computation of the FFT is fine. The data you show in the time domain has a fairly strong low frequency component. Correspondingly, your frequency-domain graph you get shows a significant spike near 0Hz. The main problem lies in how you plot the results. To better see what you might expect to see in the frequency-domain based on an intuitive perception of the time-domain waveform you would need to readjust the scale of each axis. In particular, on the time scale shown you might expect to notice patterns with a duration of around 0.25 seconds up to maybe a few seconds. That would correspond to a frequency range of roughly 0-5Hz. It would then make sense to focus on that range instead of showing the entire 0-125Hz spectrum. This can be achieved by setting the x-axis limits as such: plt.xlim(0,5) # set x-axis limits from 0 to 5Hz Similarly for the y-axis, you need to consider that frequency components with small amplitudes (to the point of becoming harder to notice on a linear scale) can still have a very perceptible contribution on the time-domain signal. As such it is often desirable to show the frequency-domain amplitudes on a logarithmic decibel scale. This can be done as follows: plt.plot(xf, 20*np.log10(2.0/nSamples * np.abs(yf[0:nSamples//2]))) Finally, if you want to better see the contribution of some specific frequency components without the interference from spectral leakage from other frequency component, you may want to consider pre-filtering your time-domain signal before computing the FFT. For example, if you want to eliminate the effect of the constant signal bias, the slow ~0.1Hz variation and the noises with frequency greater than 10Hz you might use something like the following: import scipy.signal b,a = signal.butter(4, [0.25/sRate, 10/sRate], btype='bandpass') y = signal.filtfilt(b,a,signal.detrend(IR, type='constant'))
has comment: http://stackoverflow.com/comment/112413130
downvote count: 0
has comment: http://stackoverflow.com/comment/90994139
has comment: http://stackoverflow.com/comment/112295108

http://stackoverflow.com/comment/90899396
comment on: http://stackoverflow.com/q/51974398
has text: As @ManuelGutierrez indicated, it all depends on what PDF reader you're using to open your document.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91011679
score: 0
has text: `tkinter.Image` needs an `imgtype` argument and does not understand `filename` and `resolution`. I do not thing that is what you want to use.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52029870

http://stackoverflow.com/a/62976857
type: Answer
has body: I believe you can use a pretrained resnet with 1 channel gray scale images without repeating 3 times the image. What I have done is to replace the first layer (this is pythorch not keras, but the idea might be similar): (conv1): Conv2d(3, 64, kernel_size=(7, 7), stride=(2, 2), padding=(3, 3), bias=False) With the following layer: (conv1): Conv2d(1, 64, kernel_size=(7, 7), stride=(2, 2), padding=(3, 3), bias=False) And then copy the sum (in the channel axis) of the weights to the new layer, for example, the shape of the original weights was: torch.Size([64, 3, 7, 7]) So I did: resnet18.conv1.weight.data = resnet18.conv1.weight.data.sum(axis=1).reshape(64, 1, 7, 7) And then check that the output of the new model is the same than the output with the gray scale image: y_1 = model_resnet_1(input_image_1) y_3 = model_resnet_3(input_image_3) print(torch.abs(y_1).sum(), torch.abs(y_3).sum()) (tensor(710.8860, grad_fn=&lt;SumBackward0&gt;), tensor(710.8861, grad_fn=&lt;SumBackward0&gt;)) input_image_1: one channel image input_image_3: 3 channel image (gray scale - all channels equal) model_resnet_1: modified model model_resnet_3: Original resnet model
score: 0
answers question: http://stackoverflow.com/q/51995977

http://stackoverflow.com/q/51970066
linked to: http://stackoverflow.com/q/24037982
linked to: http://stackoverflow.com/q/5071601
type: Question
has comment: http://stackoverflow.com/comment/90899205
score: 0
tagged with: sqlite
duplicate of: http://stackoverflow.com/q/24037982
has title: SQLite3 Full text search using regular expression
has comment: http://stackoverflow.com/comment/90926479
tagged with: python
tagged with: regex
has comment: http://stackoverflow.com/comment/90890673
has comment: http://stackoverflow.com/comment/90891070
answer count: 0
type: UnansweredQuestion
has body: I am using SQLite3 to track daily tests of my system , I logged all failure test ID lists/P4 Change List/Error info , etc in my SQLite3 DB below : Here is what I am trying to do with SQLite3 module in Python I want to use regular expression to search for any test parameter "combo" in "Failure Tests List" column. Let's say , I want to filter all failure tests contains "-algo5" and "-P2" If I use SQLite command : "select * from Table where Failure_Test_List have "algo5" and Failure_Test_List have "-P2";" it will treat Failure Tests List as a "WHOLE" rather than several different Test items. So I am thinking of using Python "regex" module to handle it , is it possible ? Or any other SQLite embedded command / module I didn't realized ? [Modified to point out difference between my problem and the "dup" question] One more thing I'd like to point out is , the test items in "Failure Tests List" are actually combination of multiple tests, when dealing with them using REGEXP (at least this is the tool I think of for now, maybe there is another tool fit more) , sqlite command will treat them as a WHOLE any tools in sqlite can split them into separate tests items and use regex to filter each one of them , and then list out those matches ?

http://stackoverflow.com/a/52021515
answers question: http://stackoverflow.com/q/52021372
downvote count: 0
type: Answer
has body: This is the best I can come up with, and it's #1 on the list of the things I didn't want to do. from IPython.core.magic import register_cell_magic from IPython import get_ipython import functools class MyClass(object): def decorate(self, f): @functools.wraps(f) def wrapped(*args, **kwargs): r = f(*args, **kwargs) print('Send a message here!') return r return wrapped def register_magic(self): @register_cell_magic def magic(line, cell): ip = get_ipython() @self.decorate def f(): return ip.run_cell(cell) return f() Then obj = MyClass() obj.register_magic() # ------ %%magic ...
score: 1
upvote count: 1

gmail
type: Tag
tags question: http://stackoverflow.com/q/52097956
tags question: http://stackoverflow.com/q/52088057
tag name: gmail
tags question: http://stackoverflow.com/q/52079297

http://stackoverflow.com/comment/90879417
comment on: http://stackoverflow.com/q/51964624
type: Comment
has text: So both Python and Javascript are running on the same machine, but are giving you different "local" timezones? The browser will use system settings unless explicitly overridden, but Python can be run any number of different ways and it may get its information from other sources and/or you can override it in a number of ways. How exactly are you running your Python?
score: 0
type: QuestionComment

http://stackoverflow.com/q/52012564
possible better answer: http://stackoverflow.com/a/52012628
has comment: http://stackoverflow.com/comment/90976053
downvote count: 0
has comment: http://stackoverflow.com/comment/90976565
tagged with: string
linked to: http://stackoverflow.com/q/43123408
favorite count: 0
accepted answer: http://stackoverflow.com/a/52012660
has comment: http://stackoverflow.com/comment/90976497
has title: Lazy evaluation of strings in python logging: comparing `%` with `.format`
has comment: http://stackoverflow.com/comment/90976023
has comment: http://stackoverflow.com/comment/90976109
tagged with: python
tagged with: logging
score: 14
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90976655
upvote count: 14
linked to: http://stackoverflow.com/q/40714555
type: Question
answer count: 2
has body: Is there any difference between these two calls: import logging logging.getLogger().debug('test: %i' % 42) and logging.getLogger().debug('test: {}'.format(42)) Where we assume 42 is replaced by some long computation (say 7.5 million years of computation) when it is cast to a string that produces a final answer of 42. Is the first approach lazily evaluated in case logging is set to debug?
linked to: http://stackoverflow.com/q/4148790
has answer: http://stackoverflow.com/a/52012628
linked to: http://stackoverflow.com/q/29147442
has answer: http://stackoverflow.com/a/52012660

http://stackoverflow.com/comment/91293095
type: AnswerComment
comment on: http://stackoverflow.com/a/51994671
type: Comment
has text: I figured it out. Your method worked, but I needed to use toks.replace instead of strip and lstrip. Thank you very much for the help.
score: 0

http://stackoverflow.com/q/52005271
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90960368
tagged with: python
linked to: http://stackoverflow.com/q/485789
has comment: http://stackoverflow.com/comment/90960228
has title: TypeError: can't multiply sequence by non-int of type 'float' numpy
has comment: http://stackoverflow.com/comment/90960192
has comment: http://stackoverflow.com/comment/90960293
has comment: http://stackoverflow.com/comment/90960123
type: Question
tagged with: numpy
has body: When I pass to numpy arrays of correct dimensions to the function below I get an error: TypeError: can't multiply sequence by non-int of type 'float'. see picture Please help. def linear_forward(A, W, b): print('W.type:', type(W), 'W.shape:', W.shape) print('A.type:', type(A), 'A.shape:', A.shape) Z = np.dot(W, A) + b assert (Z.shape == (W.shape[0], A.shape[1])) cache = (A, W, b) return Z, cache A data: sample dataset W is generated by code here(its equal to parameters['W1']): @staticmethod def initialize_parameters(layer_dimensions): """ Arguments: layer_dims -- python array (list) containing the dimensions of each layer in our network Returns: parameters -- python dictionary containing your parameters "W1", "b1", ..., "WL", "bL": Wl -- weight matrix of shape (layer_dims[l], layer_dims[l-1]) bl -- bias vector of shape (layer_dims[l], 1) """ parameters = {} L = len(layer_dimensions) # number of layers in the network for l in range(1, L): parameters['W' + str(l)] = np.random.randn(layer_dimensions[l], layer_dimensions[l - 1]) * 0.01 parameters['b' + str(l)] = np.zeros((layer_dimensions[l], 1)) assert (parameters['W' + str(l)].shape == (layer_dimensions[l], layer_dimensions[l - 1])) assert (parameters['b' + str(l)].shape == (layer_dimensions[l], 1)) return parameters [1]: https://i.sstatic.net/rXXT3.png [2]: https://drive.google.com/file/d/18teb1vrVbCnPzG_eFClTiLRm6VTjCNrv/view?usp=sharing
score: 0
answer count: 1
has comment: http://stackoverflow.com/comment/90960378
has answer: http://stackoverflow.com/a/52006841

http://stackoverflow.com/q/52060533
tagged with: pip
tagged with: python
type: AnsweredQuestion
upvote count: 5
type: Question
score: 5
has answer: http://stackoverflow.com/a/52060587
downvote count: 0
answer count: 1
favorite count: 0
has title: Does `pip install` add current directory to PYTHONPATH?
has body: If I have a python project that contains a setup.py file I can run pip install --user -e .. This will install all of the requirements listed in the setup file and add the current project to my pip list: $ pip show project-name Name: project-name Version: 1.0.0 Summary: None Location: /path-to-project/ Requires: matplotlib, numpy, scipy, ... Required-by: Will this by default add the \path-to-project\ to the users PYTHONPATH, or do you have to do that manually, so you can import the code via import project-name from any location on the system?
accepted answer: http://stackoverflow.com/a/52060587

http://stackoverflow.com/comment/90913134
comment on: http://stackoverflow.com/a/51970123
score: 0
type: AnswerComment
has text: @AracKnight If that is your use case I believe you should do what I describe in the end: provide the env variable by the `env` parameter instead of hacking using the shell.
type: Comment

http://stackoverflow.com/comment/113858964
score: 0
type: Comment
comment on: http://stackoverflow.com/a/64381905
has text: yes thanks for the update in V5 they improved a lot :-)
type: AnswerComment

http://stackoverflow.com/a/52063304
upvote count: 3
has comment: http://stackoverflow.com/comment/91102333
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/52062951
accepted answer of: http://stackoverflow.com/q/52062951
type: Answer
has body: IIUC, using pd.cut with value_counts get the range count , then we using append newdf=df.iloc[:,1:-1].apply(lambda x : pd.cut(x,[0,9,100],labels=['0-9','10-100']).value_counts()) df.append(newdf.rename_axis('startposition',axis=0).reset_index()) Out[216]: A b rnd startposition 0 4 99 88.0 149449305 1 6 50 10.0 47630133 2 12 7 600.0 128200594 3 100 10 8.0 49423101 0 2 3 NaN 10-100 1 2 1 NaN 0-9 df=df.append(newdf.rename_axis('startposition',axis=0).reset_index()).reindex(df.columns,axis=1) df Out[217]: startposition A b rnd 0 149449305 4 99 88.0 1 47630133 6 50 10.0 2 128200594 12 7 600.0 3 49423101 100 10 8.0 0 10-100 2 3 NaN 1 0-9 2 1 NaN
score: 3

http://stackoverflow.com/a/53111069
upvote count: 1
downvote count: 0
answers question: http://stackoverflow.com/q/51974513
type: Answer
has body: I see that the import from base_sensor_operator was added in the version 1.10 of Airflow. This was not present in versions 1.8 and 1.9. Instead, the import was done as follows: from airflow.operators.sensors import BaseSensorOperator So, checking the sensors, the related sensor for Airflow 1.10 is under sensors but for Airflow 1.9 and 1.8, the sensor is under operators. So, this issue seems to be related to the versioning of Composer and Airflow, but Airflow 1.10 wasn't available for Composer on August. In fact, this issue was reported on Google's Issue Tracker and the response is to solve this by using Apache Airflow version 1.10, which can be included on the version 1.3 of Composer.
score: 1

http://stackoverflow.com/comment/91006234
comment on: http://stackoverflow.com/a/52027790
score: 0
type: AnswerComment
has text: Thanks it's work. The parameter must be changed manually. Because we have different data for all supplier
type: Comment

http://stackoverflow.com/a/52056519
has comment: http://stackoverflow.com/comment/91100771
has comment: http://stackoverflow.com/comment/91097281
has comment: http://stackoverflow.com/comment/91131223
has comment: http://stackoverflow.com/comment/91110555
upvote count: 1
answers question: http://stackoverflow.com/q/52055984
has comment: http://stackoverflow.com/comment/91109309
type: Answer
has comment: http://stackoverflow.com/comment/91131133
downvote count: 0
score: 1
has body: There is nothing wrong with nginx. Basically you are using ImmutableMultiDict and the order is not maintained for such datatypes. If you want a particular order of data then you should use ImmutableOrderedMultiDict to store your data and send it in response. UPDATE: Disclaimer: I'm not well versed with flask and my solution would be a hack, which I don't recommend to use in production without getting it verified from someone who knows flask very well. As per the code you have written to change the ImmutableMultiDict format to ImmutableOrderedMultiDict. First you need to convert it into normal dictionary, use this answer to follow. imd = ImmutableMultiDict([('default', u''), ('required', u'on'), ('name', u'short_text'), ('name', u'another')]) x = imd.to_dict(flat=False) Now as per the order you need the data, you should add it. new_imd = ImmutableOrderedMultiDict([('default', x['default'][0]), ('required', x['required'][0]), ('name', x['name'][0]), ('name', x['name'][1])])
has comment: http://stackoverflow.com/comment/91131260

http://stackoverflow.com/comment/90916571
type: QuestionComment
has text: @VivekKumar I used "error_score = 0" in my RandomizedSearchCV. However, the search does not continue after an "AssertionError" occured. Is there any trick to tell it to just continue the search afterwards with a new parameter combination
score: 0
comment on: http://stackoverflow.com/q/51963174
type: Comment

http://stackoverflow.com/a/52095777
has body: You need append another newline character at the end of the loop and use join method to print your result r=[] x='hi' y='there' z='how are you?' for i in range(4): r.append(x) r.append(y) r.append('\n') r.append(z) r.append('\n') print(r) print(" ".join(r)) Output hi there how are you? hi there how are you? hi there how are you? hi there how are you?
downvote count: 1
has comment: http://stackoverflow.com/comment/91141690
upvote count: 1
has comment: http://stackoverflow.com/comment/91141590
has comment: http://stackoverflow.com/comment/91141909
score: 0
has comment: http://stackoverflow.com/comment/91141653
answers question: http://stackoverflow.com/q/52095705
type: Answer

http://stackoverflow.com/q/52078657
has title: Check that a key from json output exists
type: AnsweredQuestion
has body: I keep getting the following error when trying to parse some json: Traceback (most recent call last): File "/Users/batch/projects/kl-api/api/helpers.py", line 37, in collect_youtube_data keywords = channel_info_response_data['items'][0]['brandingSettings']['channel']['keywords'] KeyError: 'brandingSettings' How do I make sure that I check my JSON output for a key before assigning it to a variable? If a key isn’t found, then I just want to assign a default value. Code below: try: channel_id = channel_id_response_data['items'][0]['id'] channel_info_url = YOUTUBE_URL + '/channels/?key=' + YOUTUBE_API_KEY + '&amp;id=' + channel_id + '&amp;part=snippet,contentDetails,statistics,brandingSettings' print('Querying:', channel_info_url) channel_info_response = requests.get(channel_info_url) channel_info_response_data = json.loads(channel_info_response.content) no_of_videos = int(channel_info_response_data['items'][0]['statistics']['videoCount']) no_of_subscribers = int(channel_info_response_data['items'][0]['statistics']['subscriberCount']) no_of_views = int(channel_info_response_data['items'][0]['statistics']['viewCount']) avg_views = round(no_of_views / no_of_videos, 0) photo = channel_info_response_data['items'][0]['snippet']['thumbnails']['high']['url'] description = channel_info_response_data['items'][0]['snippet']['description'] start_date = channel_info_response_data['items'][0]['snippet']['publishedAt'] title = channel_info_response_data['items'][0]['snippet']['title'] keywords = channel_info_response_data['items'][0]['brandingSettings']['channel']['keywords'] except Exception as e: raise Exception(e)
possible better answer: http://stackoverflow.com/a/52078763
has answer: http://stackoverflow.com/a/52079419
accepted answer: http://stackoverflow.com/a/52079419
type: Question
score: 0
has comment: http://stackoverflow.com/comment/91107374
has comment: http://stackoverflow.com/comment/91107356
has comment: http://stackoverflow.com/comment/91107315
answer count: 3
has comment: http://stackoverflow.com/comment/91107348
has answer: http://stackoverflow.com/a/52078800
has comment: http://stackoverflow.com/comment/91107726
tagged with: python
has answer: http://stackoverflow.com/a/52078763

http://stackoverflow.com/a/51992338
has comment: http://stackoverflow.com/comment/90935271
type: Answer
has comment: http://stackoverflow.com/comment/90935209
upvote count: 1
accepted answer of: http://stackoverflow.com/q/51991800
answers question: http://stackoverflow.com/q/51991800
has body: This is another alternative. It adds spaces to the dots but removes also the number after ip address. This is not done in other solutions because of the dot after the number. import re mystr= "hey I want to delete all the digits ex 600 502 700 m 8745 given in this string. And getting request from the ip address 122521587502. This string tells about deleting digits 502 600 765 from this." myDict={'600','700'} print(" ".join("" if (i.isdigit() and i not in myDict) \ else i for i in re.findall(r'(?:\w+|\d+|\S)', mystr))) Output: hey I want to delete all the digits ex 600 700 m given in this string . And getting request from the ip address . This string tells about deleting digits 600 from this . PS: There is a terrible alternative to fix the spaces of the dots: print("".join("" if (i.isdigit() and i not in myDict) \ else i if i == '.' or i == ',' \ else ''.join([' ', i]) for i in re.findall(r'(?:\w+|\d+|\S)', mystr)) .strip()) Which produces the output: hey I want to delete all the digits ex 600 700 m given in this string. And getting request from the ip address. This string tells about deleting digits 600 from this.
has comment: http://stackoverflow.com/comment/90935117
type: AcceptedAnswer
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/90934701
has comment: http://stackoverflow.com/comment/90935357

http://stackoverflow.com/comment/90999553
comment on: http://stackoverflow.com/q/52024612
score: 2
type: Comment
has text: its hard to know what regular expression you want when you only give one example of input and output, depending on how consistent your data is you can do this sort of splitting with some simple string operations or you might need complex regexes , its hard to know without all of your data (or at least representative examples)
type: QuestionComment

http://stackoverflow.com/a/51966690
type: Answer
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/90896825
answers question: http://stackoverflow.com/q/51966541
downvote count: 0
has comment: http://stackoverflow.com/comment/90911963
has body: Using lxml for parsing: from lxml import html doc = html.fromstring(raw_html) doc.xpath('//span[contains(@class,"offer-price")]')[0].text this returns: '$13.00' the xpath portion is simply looking for all the spans: //span and filter those for a certain class marker [contains(@class,"offer-price")]

http://stackoverflow.com/q/52049511
tagged with: word2vec
tagged with: python
has comment: http://stackoverflow.com/comment/91055310
tagged with: nlp
has body: I have a semi-structured dataset, each row pertains to a single user: id, skills 0,"java, python, sql" 1,"java, python, spark, html" 2, "business management, communication" Why semi-structured is because the followings skills can only be selected from a list of 580 unique values. My goal is to cluster users, or find similar users based on similar skillsets. I have tried using a Word2Vec model, which gives me very good results to identify similar skillsets - For eg. model.most_similar(["Data Science"]) gives me - [('Data Mining', 0.9249375462532043), ('Data Visualization', 0.9111810922622681), ('Big Data', 0.8253220319747925),... This gives me a very good model for identifying individual skills and not group of skills. how do I make use of the vector provided from the Word2Vec model to successfully cluster groups of similar users?
upvote count: 10
answer count: 1
has title: How to perform clustering on Word2Vec
tagged with: cluster-analysis
type: UnansweredQuestion
downvote count: 0
tagged with: data-mining
score: 10
has answer: http://stackoverflow.com/a/52060474
favorite count: 0
type: Question

http://stackoverflow.com/q/51968385
type: UnansweredQuestion
has title: Plotly subplot produces two graphs with same data, although traces contain different data
downvote count: 1
has comment: http://stackoverflow.com/comment/90887094
upvote count: 3
tagged with: plotly
has body: When plotting 2 heatmaps, it gives me both heatmaps, each with different settings, but with the data of the first one. from plotly import tools import plotly.graph_objs as go import numpy as np from plotly.offline import plot Data: a = np.array([[1, 2, 3],[1, 2, 3],[1, 2, 3]]) b = np.array([[2, 3, 4],[4, 5, 6],[5, 6, 7]]) fig = tools.make_subplots(rows=1, cols=2) trace1 = go.Heatmapgl( z=a, showscale=False, colorscale='Viridis', name='aa' ) trace2 = go.Heatmapgl( z=b, showscale=False, name='bb' ) fig.append_trace(trace1, 1, 1) fig.append_trace(trace2, 1, 2) plot(fig, filename='simple-subplot') This gives me 2 heatmaps, but the second one also contains z values of 1, 2 or 3. Anyone knows what the issue is here?
has comment: http://stackoverflow.com/comment/108838916
has answer: http://stackoverflow.com/a/59683056
type: Question
score: 2
answer count: 1
has comment: http://stackoverflow.com/comment/90887663
tagged with: python
favorite count: 0

beautifulsoup
tags question: http://stackoverflow.com/q/52101446
tags question: http://stackoverflow.com/q/52002758
tags question: http://stackoverflow.com/q/52020060
tags question: http://stackoverflow.com/q/52074916
tags question: http://stackoverflow.com/q/51992879
tags question: http://stackoverflow.com/q/51978428
tags question: http://stackoverflow.com/q/52064686
tags question: http://stackoverflow.com/q/52040260
tags question: http://stackoverflow.com/q/52049257
tags question: http://stackoverflow.com/q/52084739
tags question: http://stackoverflow.com/q/52026274
tags question: http://stackoverflow.com/q/52007897
tags question: http://stackoverflow.com/q/52099923
tags question: http://stackoverflow.com/q/52084162
tags question: http://stackoverflow.com/q/51968354
tags question: http://stackoverflow.com/q/52085139
tags question: http://stackoverflow.com/q/52033281
tags question: http://stackoverflow.com/q/52077888
tag name: beautifulsoup
tags question: http://stackoverflow.com/q/51986770
tags question: http://stackoverflow.com/q/52066560
tags question: http://stackoverflow.com/q/52054633
tags question: http://stackoverflow.com/q/51979596
tags question: http://stackoverflow.com/q/51978412
tags question: http://stackoverflow.com/q/51984646
tags question: http://stackoverflow.com/q/52077632
tags question: http://stackoverflow.com/q/52109321
tags question: http://stackoverflow.com/q/52021506
tags question: http://stackoverflow.com/q/52048617
tags question: http://stackoverflow.com/q/51970446
tags question: http://stackoverflow.com/q/52107161
tags question: http://stackoverflow.com/q/51996139
tags question: http://stackoverflow.com/q/52066734
tags question: http://stackoverflow.com/q/52010458
tags question: http://stackoverflow.com/q/52013610
tags question: http://stackoverflow.com/q/52040525
tags question: http://stackoverflow.com/q/51965259
tags question: http://stackoverflow.com/q/51976294
tags question: http://stackoverflow.com/q/52011353
tags question: http://stackoverflow.com/q/52017466
tags question: http://stackoverflow.com/q/52020762
tags question: http://stackoverflow.com/q/52058611
tags question: http://stackoverflow.com/q/52105663
tags question: http://stackoverflow.com/q/52065009
tags question: http://stackoverflow.com/q/51973998
tags question: http://stackoverflow.com/q/51977501
tags question: http://stackoverflow.com/q/52014327
tags question: http://stackoverflow.com/q/52067954
tags question: http://stackoverflow.com/q/51986817
tags question: http://stackoverflow.com/q/52023312
tags question: http://stackoverflow.com/q/52008532
tags question: http://stackoverflow.com/q/51977245
tags question: http://stackoverflow.com/q/52079733
tags question: http://stackoverflow.com/q/52005894
tags question: http://stackoverflow.com/q/52078362
type: Tag
tags question: http://stackoverflow.com/q/52075592
tags question: http://stackoverflow.com/q/51958411
tags question: http://stackoverflow.com/q/51982930
tags question: http://stackoverflow.com/q/52014418
tags question: http://stackoverflow.com/q/52093875
tags question: http://stackoverflow.com/q/52007488
tags question: http://stackoverflow.com/q/51960036
tags question: http://stackoverflow.com/q/52037382
tags question: http://stackoverflow.com/q/52072537
tags question: http://stackoverflow.com/q/52034621
tags question: http://stackoverflow.com/q/52027787
tags question: http://stackoverflow.com/q/52021254
tags question: http://stackoverflow.com/q/52074680
tags question: http://stackoverflow.com/q/51971046
tags question: http://stackoverflow.com/q/52019664
tags question: http://stackoverflow.com/q/52102257
tags question: http://stackoverflow.com/q/52040677
tags question: http://stackoverflow.com/q/52030543
tags question: http://stackoverflow.com/q/52010016
tags question: http://stackoverflow.com/q/52045596
tags question: http://stackoverflow.com/q/52076814
tags question: http://stackoverflow.com/q/52066389
tags question: http://stackoverflow.com/q/52043839
tags question: http://stackoverflow.com/q/52048485

http://stackoverflow.com/comment/91144157
score: 0
type: Comment
has text: How should I be setting the seed. I already set the seed for the data generation with numpy.random.seed(10) and tensorflow.set_random_seed(10) but how would I set the seed for keras? Also any idea why a model would start with a loss of ~0 when accuracy is low?
type: AnswerComment
comment on: http://stackoverflow.com/a/52085516

http://stackoverflow.com/comment/91161297
has text: Yes, exactly that.
comment on: http://stackoverflow.com/q/52104947
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52029571
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/91009801
linked to: http://stackoverflow.com/q/268629
has body: I have a little HTTPServer implementation I'm spinning up to listen for a callback from an API. In testing, this implimentation is keeping the innermost thread alive. Here's the server: import http import uuid from http import server class Server(server.HTTPServer): RequestLog:list = [] ErrorList:list = [] Serve:bool = True def __init__(self, server_address, RequestHandlerClass): self.RequestLog = [] self.ErrorList = [] self.Serve:bool = True return super().__init__(server_address, RequestHandlerClass) def LogRequest(self, clientAddress, success, state, params:dict={}): """docstring""" uid = uuid.uuid1() logItem = {"RequestID" : uid, "ClientAddress" : clientAddress, "Success" : success, "State" : state, "Params" : params} self.RequestLog.append(logItem) def GetRequestItem(self, state): """docstring""" logItem = {} if self.RequestLog and len(self.RequestLog): logItem = [d for d in self.RequestLog if d["State"] == state][0] return logItem def service_actions(self): try: if not self.Serve: self.shutdown() self.server_close() except Exception as e: err = e raise e return super().service_actions() def handle_error(self, request, client_address): logItem = {"clientAddress" : client_address, "success" : False, "state" : None, "params" : None} try: self.LogRequest(**logItem) x = request except Exception as e: self.shutdown() err = e raise e return super().handle_error(request, client_address) So what the server implementation above does, is log information about requests in the ResquestLog:list and then provided a method GetRequestItem that can be used to pull for the existence of a logged request. In the test I'm throwing and error and catching it with the handle_error() override. Here is the calling function that spins up the server, polls for request, and then shutdowns the sever by setting its Server.Serve method to False def AwaitCallback(self, server_class=Server, handler_class=OAuthGrantRequestHandler): """docstring""" server_address = ("127.0.0.1", 8080) self.Httpd …
has comment: http://stackoverflow.com/comment/91009993
has title: HTTP Server keeping thread alive in nested thread scheme
has comment: http://stackoverflow.com/comment/91009856
favorite count: 0
tagged with: python
score: 2
tagged with: python-3.x
answer count: 0
upvote count: 3
type: UnansweredQuestion
tagged with: multithreading
tagged with: httpserver

http://stackoverflow.com/q/52036021
linked to: http://stackoverflow.com/q/41526832
score: 4
accepted answer: http://stackoverflow.com/a/52048375
answer count: 3
has title: QTimer on a Qthread
tagged with: pyqt
possible better answer: http://stackoverflow.com/a/52036356
favorite count: 0
has answer: http://stackoverflow.com/a/52048375
has answer: http://stackoverflow.com/a/52036356
tagged with: qtimer
tagged with: python
has answer: http://stackoverflow.com/a/52038861
upvote count: 4
has body: I have a GUI witch i need to update constantly using a Qtimer, for that I use a worker Qthread, this is my code : from PyQt5.QtWidgets import QApplication, QPushButton, QWidget from PyQt5.QtCore import QThread, QTimer import sys import threading class WorkerThread(QThread): def run(self): print("thread started from :" + str(threading.get_ident())) timer = QTimer(self) timer.timeout.connect(self.work) timer.start(5000) self.exec_() def work(self): print("working from :" + str(threading.get_ident())) QThread.sleep(5) class MyGui(QWidget): worker = WorkerThread() def __init__(self): super().__init__() self.initUi() print("Starting worker from :" + str(threading.get_ident())) self.worker.start() def initUi(self): self.setGeometry(500, 500, 300, 300) self.pb = QPushButton("Button", self) self.pb.move(50, 50) self.show() app = QApplication(sys.argv) gui = MyGui() app.exec_() the output is: Starting worker from :824 thread started from :5916 working from :824 working from :824 the timer is working on the main thread witch freeze my Gui, How can i fix that ?
tagged with: qthread
type: AnsweredQuestion
downvote count: 0
tagged with: pyqt5
type: Question

http://stackoverflow.com/q/52093838
has answer: http://stackoverflow.com/a/52093874
answer count: 1
tagged with: arrays
has title: can't assign to function call, syntax error in python
tagged with: python
tagged with: matlab
type: AnsweredQuestion
tagged with: list
has comment: http://stackoverflow.com/comment/91137644
type: Question
accepted answer: http://stackoverflow.com/a/52093874
has body: I'm trying to translate a Matlab script into a Python script and, as I'm not expert in Python, I got the following error and I don't know how to solve it: Syntax error. There is an error in your program: *** can't assign to function call My code is: import numpy.matlib m=min(p) Sn=numpy.zeros(28) z=0 for i in range(init_Sn, end_Sn): if p(i)&lt;=m+20 and p(i)&gt;=m-20: z=z+1 Sn(z)=1 else: z=z+1 Sn(z)=0 The error seems to be in the line where I do: Sn(z)=1 I'm not sure if the problem comes from the definition of "Sn". In Matlab, all that I do is: Sn=zeros(1,28) I think what I'm doing in Python is not equivalent?
has comment: http://stackoverflow.com/comment/91137657
score: 0
tagged with: syntax-error

http://stackoverflow.com/comment/91042781
score: 0
comment on: http://stackoverflow.com/q/52045848
has text: `numexpr` could help here. Something like: `year = df.Year.values` `df1[numexpr.evaluate('year == 2000')]`
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51978463
score: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/90928709
has comment: http://stackoverflow.com/comment/90924691
has comment: http://stackoverflow.com/comment/90922045
type: Question
has comment: http://stackoverflow.com/comment/91002232
tagged with: python
tagged with: cryptography
linked to: http://stackoverflow.com/q/6682815
has comment: http://stackoverflow.com/comment/90924591
has body: I have generated a RSA Public and Private key pair (publickey.pem and privatekey.pem) and i want to calculate the public key fingerprint of the public key. what is the best way to do that in python? I have already searched many articles but couldn't fine any. My public key looks like this: -----BEGIN RSA PUBLIC KEY----- [binary] -----END RSA PUBLIC KEY----- Any help would be appreciated Edit: I will have several clients signing their http request with their private key and sending the request to the server along with the public key fingerprint so that from the fingerprint i can check which client has sent the request and i can look for the publick key of that particular client with the given fingerprint. Once i have the public key i can verify that the request is authenticated. My currentkey is in RSA format and i need the SSH fingerprint from my pubic key. Is there any way to convert the RSA key to OpenSSH format. I am able to do the same in Node.js with HTTP-Signature library. I want something similar in Python. Once i have the key in OpenSSH format i can use this: Deriving an SSH Fingerprint from a Public Key in Python to get the fingerprint Thanks in Advance.
has comment: http://stackoverflow.com/comment/90929028
duplicate of: http://stackoverflow.com/q/6682815
upvote count: 1
has comment: http://stackoverflow.com/comment/90929071
has comment: http://stackoverflow.com/comment/90921271
has comment: http://stackoverflow.com/comment/90927533
has comment: http://stackoverflow.com/comment/90926489
tagged with: rsa
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90928978
has comment: http://stackoverflow.com/comment/90925699
has title: Python How to generate fingerprint from rsa public key
downvote count: 0
answer count: 0

http://stackoverflow.com/a/51986491
downvote count: 0
score: 1
has body: I created a python module to create swagger + jsonapi services: https://github.com/thomaxxl/safrs If you run the demo, it creates an example method (send_mail) that can be invoked from the swagger UI: https://github.com/thomaxxl/safrs/blob/master/examples/demo.py If you make it a classmethod, you won't need object instances. This solution may not fit your requirements thoug, but it's like 5min work to get it running
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/51982564
upvote count: 1
type: Answer
accepted answer of: http://stackoverflow.com/q/51982564

http://stackoverflow.com/q/52110399
type: UnansweredQuestion
upvote count: 1
tagged with: python
has title: Stack and transpose multi-index table in Pandas
score: 1
type: Question
has body: I am relatively new to manipulating data tables in Pandas. I have a big table like the following, say 20x bigger than this one in number of columns and rows: import pandas as pd df = pd.DataFrame() df['col1']=['A','A','A','B','B','B','A','A','A','B','B','B'] df['col2']=['x','x','y','y','z','z','x','x','y','y','z','z'] df['col3']=['A1','A2','B1','B2','C1','C2','D1','D2','E1','E2','F1','F2'] df['col4']=['m','n','p','q','l','z','m','n','p','q','l','z'] df['num1']=[1,2,3,4,5,6,7,8,9,10,11,12] df['num2']=[5,6,7,1,2,3,4,5,6,9,7,8,] df['num3']=[11,12,13,14,15,16,17,18,19,10,11,12] df I want to format the table in such a way that I want to keep col1 col2, col3 as is say index them, transpose col4 elements to different rows and then stack num1, num2 and num3 columns in one column. I tried reshaping in Pandas but not having success. Getting numerous errors. How should I reshape it the way I want?
downvote count: 0
has comment: http://stackoverflow.com/comment/91197608
tagged with: pandas
duplicate of: http://stackoverflow.com/q/47152691
favorite count: 0
has comment: http://stackoverflow.com/comment/91171281
answer count: 0
linked to: http://stackoverflow.com/q/47152691

http://stackoverflow.com/a/52044910
has comment: http://stackoverflow.com/comment/91040856
type: Answer
has comment: http://stackoverflow.com/comment/91040888
answers question: http://stackoverflow.com/q/52044813
score: 2
has comment: http://stackoverflow.com/comment/91040918
upvote count: 2
has comment: http://stackoverflow.com/comment/91040954
has body: First Problem: It is because . is a special regex character. You can escape it using \: &gt;&gt;&gt; df.apply(lambda x: x.str.split("\.\.\.")) name name2 0 [0;0;*;1;1, 1, 1;1;*;1;1] [0;0;*;1;1, 1, 1;1;*;1;3] 1 [0;0;*;1;1, 1, 1;1;*;1;2] [0;0;*;1;1, 1, 1;1;*;1;4] Second problem: Use str again to index: &gt;&gt;&gt; df.apply(lambda x: x.str.split(".").str[0]) name name2 0 0;0;*;1;1 0;0;*;1;1 1 0;0;*;1;1 0;0;*;1;1
downvote count: 0

http://stackoverflow.com/comment/91006226
score: 0
type: AnswerComment
type: Comment
has text: How is this solving the OPs problem? Where are you collating the numbers into sorted sets?
comment on: http://stackoverflow.com/a/52027966

http://stackoverflow.com/comment/91171516
comment on: http://stackoverflow.com/a/52092635
has text: Thanks for your reply. Now I am able to bypass the errors, but I am not having the same value for the same variable in two different functions. I have tried this by checking the hex(id). Any idea what can be?
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/90973332
has text: Or use a default dict
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/52011112
type: Comment

http://stackoverflow.com/q/51981951
has answer: http://stackoverflow.com/a/51982070
score: 0
answer count: 3
has answer: http://stackoverflow.com/a/51982005
has title: skip first line from text file while inserting into sql table
has answer: http://stackoverflow.com/a/51981999
type: UnansweredQuestion
tagged with: python
has body: I have text file employee.txt and i am inserting it into sql table but i am getting 1st line same with headers followed by my table values.I am very new to python.how do i remove that first line in table which is header. inpfile=open('C:/Users/chari/Documents/employee.txt','r') while 1: line=inpfile.readline() if line=='': break serial_no,first_name,last_name,age,sex,city=line.split() stmt = ("""insert into employee(serial_no, first_name,last_name,age,sex,city)""" +"values" +str((serial_no,first_name,last_name,age,sex,city))) cursor.execute(stmt)
tagged with: mysql
type: Question

http://stackoverflow.com/comment/91104487
type: QuestionComment
has text: I'm really sure that both types of LSTM layers do and learn "exactly the same". The only difference is really "discarding or not" the states between batches. If you discard the states, each new batch will be seen as new sequences. If not, each new batch will be seen as new steps of the same sequences.
score: 0
comment on: http://stackoverflow.com/q/52071751
type: Comment

http://stackoverflow.com/comment/91119631
type: AnswerComment
comment on: http://stackoverflow.com/a/52078471
type: Comment
has text: @JoeIddon now it works for Grey as well. Have a nice day :D
score: 0

http://stackoverflow.com/a/52071560
type: Answer
downvote count: 0
score: 7
answers question: http://stackoverflow.com/q/52057540
accepted answer of: http://stackoverflow.com/q/52057540
upvote count: 7
type: AcceptedAnswer
has body: I didn't find a way for Dash to read the console output directly, so I used a workaround using a text file. Here is a sample code which prints the last 20 lines of the console output to an Iframe (as to keep the line breaks, which do not show in other text/div components): import dash_core_components as dcc import dash_html_components as html import dash import sys f = open('out.txt', 'w') f.close() app = dash.Dash() app.layout = html.Div([ dcc.Interval(id='interval1', interval=1 * 1000, n_intervals=0), dcc.Interval(id='interval2', interval=5 * 1000, n_intervals=0), html.H1(id='div-out', children=''), html.Iframe(id='console-out',srcDoc='',style={'width': '100%','height':400}) ]) @app.callback(dash.dependencies.Output('div-out', 'children'), [dash.dependencies.Input('interval1', 'n_intervals')]) def update_interval(n): orig_stdout = sys.stdout f = open('out.txt', 'a') sys.stdout = f print 'Intervals Passed: ' + str(n) sys.stdout = orig_stdout f.close() return 'Intervals Passed: ' + str(n) @app.callback(dash.dependencies.Output('console-out', 'srcDoc'), [dash.dependencies.Input('interval2', 'n_intervals')]) def update_output(n): file = open('out.txt', 'r') data='' lines = file.readlines() if lines.__len__()&lt;=20: last_lines=lines else: last_lines = lines[-20:] for line in last_lines: data=data+line + '&lt;BR&gt;' file.close() return data app.run_server(debug=False, port=8050)

svd
type: Tag
tags question: http://stackoverflow.com/q/52105389
tags question: http://stackoverflow.com/q/52101779
tag name: svd

http://stackoverflow.com/comment/91010316
type: Comment
type: QuestionComment
has text: I decided to create a new virtualenv and to install all the dependencies there
score: 1
comment on: http://stackoverflow.com/q/52029037

http://stackoverflow.com/comment/91039950
type: AnswerComment
type: Comment
has text: Its great that you figured it out. But, you should post whatever worked for you as an answer to help other users with the same problem.
comment on: http://stackoverflow.com/a/52039733
score: 0

http://stackoverflow.com/comment/91099420
type: QuestionComment
has text: @wildplasser, sorry for the typo. Corrected it
score: 0
comment on: http://stackoverflow.com/q/52073307
type: Comment

http://stackoverflow.com/q/52068007
answer count: 2
tagged with: for-loop
tagged with: pandas
possible better answer: http://stackoverflow.com/a/52068056
downvote count: 0
score: 1
accepted answer: http://stackoverflow.com/a/52069371
favorite count: 0
has title: Iterating over pandas columns and calculating new columns in each iteration
tagged with: python
upvote count: 1
has body: I have a dataframe that looks like this d = {'A': [10, 20, 30, 40], 'B': [20, 30, 40, 50],'C': [30, 40, 50, 60]} df = pd.DataFrame(data=d) A B C 10 20 30 20 30 40 30 40 50 40 50 60 I am trying to build a loop such that it creates three new columns (one in each iteration) using a complex formula wherein only one of them is increased by 10% while the other two remain the same in each iteration. The formula applied each time is: sqrt(((A ** 2)*B)+((B ** 2)*C)) So the desired output is - A B C X_A X_B X_C 10 20 30 120.08 129.30 123.29 20 30 40 224.77 238.24 227.16 30 40 50 351.51 369.32 352.14 40 50 60 496.79 519.13 494.98 What would be the easiest way to achieve this?
type: Question
has answer: http://stackoverflow.com/a/52069371
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52068056

http://stackoverflow.com/q/52096970
tagged with: machine-learning
tagged with: word2vec
upvote count: 1
tagged with: python
answer count: 0
score: 1
type: Question
has title: Error in standardizing vectors obtained from training my word2vec corpus
downvote count: 0
has body: After training word2vec i am not able to standardize my vectors. i'm getting an error: Input contains NaN, infinity or a value too large for dtype('float64'). My code &amp; error trace is below. What type is my word2vec vectors - are they a list? And how i could remove this error? # average Word2Vec # compute average word2vec for each review of train Dataset sent_vectors_train = []; for sent in list_of_sent_train: # for each review/sentence sent_vec = np.zeros(50) # as word vectors are of zero length cnt_words =0; # num of words with a valid vector in the sentence/review for word in sent: # for each word in a review/sentence try: vec = w2v_model.wv[word] sent_vec += vec cnt_words += 1 except: pass sent_vec /= cnt_words sent_vectors_train.append(sent_vec) print(len(sent_vectors_train)) print(len(sent_vectors_train[0])) output:-7000 50 from sklearn.preprocessing import StandardScaler standardized_data = StandardScaler(with_mean=False).fit_transform(sent_vectors_train) print(standardized_data.shape) ValueError Traceback (most recent call last) &lt;ipython-input-47-cb2854c305eb&gt; in &lt;module&gt;() 1 #from sklearn.preprocessing import StandardScaler 2 from sklearn.preprocessing import StandardScaler ----&gt; 3 standardized_data = StandardScaler(with_mean=False).fit_transform(sent_vectors_train) 4 print(standardized_data.shape) ~\Anaconda3\lib\site-packages\sklearn\base.py in fit_transform(self, X, y, **fit_params) 515 if y is None: 516 # fit method of arity 1 (unsupervised transformation) --&gt; 517 return self.fit(X, **fit_params).transform(X) 518 else: 519 # fit method of arity 2 (supervised transformation) ~\Anaconda3\lib\site-packages\sklearn\preprocessing\data.py in fit(self, X, y) 588 # Reset internal state before fitting 589 self._reset() --&gt; 590 return self.partial_fit(X, y) 591 592 def partial_fit(self, X, y=None): ~\Anaconda3\lib\site-packages\sklearn\preprocessing\data.py in partial_fit(self, X, y) 610 """ 611 X = check_array(X, accept_sparse=('csr', 'c…
tagged with: scikit-learn
favorite count: 0
has comment: http://stackoverflow.com/comment/91148022
type: UnansweredQuestion

http://stackoverflow.com/q/52000950
tagged with: wget
downvote count: 0
answer count: 1
tagged with: directory
favorite count: 0
tagged with: download
tagged with: python
has answer: http://stackoverflow.com/a/52001249
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/52001249
upvote count: 7
type: Question
score: 7
has body: Looking for a clean Python Wget solution of downloading multiple files at once. The url will be always the same : https://example.com/ So far I can do this : import wget print('Beginning file download with wget module') url = 'https://example.com/new_folder/1.jpg' wget.download(url) But i need to download also the -2.jpg, -3.jpg , -4.jpg, -5.jpg and rename the NWZV1WB to something like NEWCODE-1.jpg, NEWCODE-2.jpg... Also I need to download all content(22).jpg files inside a folder and rename the folder localy to something like NEWCODE, but keep the original name of the files Here the url also is always the same : import wget print('Beginning file download with wget module') url = 'https://example.com/big/1.jpg' #there's 18 jpg inside wget.download(url) What would be best, wget (can't find to many articles about) or requests ? Any help is appreciated.
has title: Python wget download multiple files at once

http://stackoverflow.com/q/52040017
has body: I am just trying to read a .csv file which I saved in a directory. At first I give path="E:\\Google\\Google Stock Market Data - google_stock_data.csv" It is interpreted successfully. I move to next line. And give the command file=open(path) Then it gives the error. Traceback (most recent call last): File "&lt;pyshell#1&gt;", line 1, in &lt;module&gt; file=open(path) FileNotFoundError: [Errno 2] No such file or directory: 'E:\\Google\\Google Stock Market Data - google_stock_data.csv'
answer count: 3
has comment: http://stackoverflow.com/comment/91051028
upvote count: 0
has comment: http://stackoverflow.com/comment/91030708
has comment: http://stackoverflow.com/comment/91030646
has comment: http://stackoverflow.com/comment/91030381
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/52040884
has answer: http://stackoverflow.com/a/52040251
has comment: http://stackoverflow.com/comment/91031056
downvote count: 2
has comment: http://stackoverflow.com/comment/91030666
has answer: http://stackoverflow.com/a/52040171
has title: Reading .csv file in Python
type: Question
has comment: http://stackoverflow.com/comment/91041632
has comment: http://stackoverflow.com/comment/91030569
score: -2

http://stackoverflow.com/comment/91007544
type: QuestionComment
comment on: http://stackoverflow.com/q/52028474
has text: Is it normal to have my validation accuracy like that? ( only .14 and .12 ). And what could be the cause? The data is split in 20000 training samples and 5000 validation samples
type: Comment
score: 0

http://stackoverflow.com/q/52082538
tagged with: tensorflow
type: Question
has comment: http://stackoverflow.com/comment/102295209
has body: I am working on a competition on Kaggle, where the evaluation metric is defined as This competition is evaluated on the mean average precision at different intersection over union (IoU) thresholds. The IoU of a proposed set of object pixels and a set of true object pixels is calculated as: IoU(A,B)=(A∩B)/(A∪B) The metric sweeps over a range of IoU thresholds, at each point calculating an average precision value. The threshold values range from 0.5 to 0.95 with a step size of 0.05: (0.5, 0.55, 0.6, 0.65, 0.7, 0.75, 0.8, 0.85, 0.9, 0.95). In other words, at a threshold of 0.5, a predicted object is considered a "hit" if its intersection over union with a ground truth object is greater than 0.5. At each threshold value t, a precision value is calculated based on the number of true positives (TP), false negatives (FN), and false positives (FP) resulting from comparing the predicted object to all ground truth objects: TP(t)/TP(t)+FP(t)+FN(t). A true positive is counted when a single predicted object matches a ground truth object with an IoU above the threshold. A false positive indicates a predicted object had no associated ground truth object. A false negative indicates a ground truth object had no associated predicted object. The average precision of a single image is then calculated as the mean of the above precision values at each IoU threshold: (1/|thresholds|)*∑tTP(t)/TP(t)+FP(t)+FN(t) Now, I have written this function in pure numpy as it was much easier to code in that and I have decorated it with tf.py_fucn() in order to use with it with Keras. Here is the sample code: def iou_metric(y_true_in, y_pred_in, fix_zero=False): labels = y_true_in y_pred = y_pred_in true_objects = 2 pred_objects = 2 if fix_zero: if np.sum(y_true_in) == 0: return 1 if np.sum(y_pred_in) == 0 else 0 intersection = np.histogram2d(labels.flatten(), y_pred.flatten(), bins=(true_objects, pred_objects))[0] # Compute areas (needed for finding the union between all objects) area_true = np.histogr…
has comment: http://stackoverflow.com/comment/94943894
has title: Using pure numpy metric as metric in Keras/TensorFlow
tagged with: deep-learning
upvote count: 7
answer count: 1
tagged with: keras
favorite count: 0
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/54922201
tagged with: machine-learning
tagged with: python
has comment: http://stackoverflow.com/comment/94943976
downvote count: 0
score: 7

http://stackoverflow.com/comment/91120942
comment on: http://stackoverflow.com/q/52085276
type: Comment
type: QuestionComment
score: 0
has text: "remove all the minimum elements"?

http://stackoverflow.com/q/52029408
type: AnsweredQuestion
score: 3
has answer: http://stackoverflow.com/a/52029734
accepted answer: http://stackoverflow.com/a/52029734
has title: Sklearn MLP Classifier Hyperparameter Optimization (RandomizedSearchCV)
type: Question
has body: I have the following parameters set up : parameter_space = { 'hidden_layer_sizes': [(sp_randint(100,600),sp_randint(100,600),), (sp_randint(100,600),)], 'activation': ['tanh', 'relu', 'logistic'], 'solver': ['sgd', 'adam', 'lbfgs'], 'alpha': stats.uniform(0.0001, 0.9), 'learning_rate': ['constant','adaptive']} All the parameters except the hidden_layer_sizes is working as expected. However, fitting this RandomizedSearchCV model and displaying it's verbose text shows that it treats hidden_layer_sizes as : hidden_layer_sizes=(&lt;scipy.stats._distn_infrastructure.rv_frozen object and goes on to throw : TypeError: '&lt;=' not supported between instances of 'rv_frozen' and 'int' This result is obtained instead of the expected 1 or 2 layer MLP with hidden layer neurons between 100 and 600. Any ideas / other related tips?
answer count: 1
downvote count: 0
tagged with: scikit-learn
tagged with: hyperparameters
favorite count: 0
tagged with: python
upvote count: 3
tagged with: machine-learning

http://stackoverflow.com/comment/91030563
has text: @user1596422 Saving the mask like you did is the cleanest option in my opinion. For more complex operations you can save the slices with pd.IndexSlice (for example `slc = pd.IndexSlice[df['a']==2, 'b':'e']` followed by `df.loc[slc]` returns the same thing as `df.loc[df['a']==2, 'b':'e']`).
comment on: http://stackoverflow.com/a/52037146
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/90929053
score: 0
has text: My guess is that, because stdout is line-buffered, and you’re trying to write to it from two different threads, the one that writes a partial line (the `input`) doesn’t show up until after the one that writes a complete line, or something like that. If you put a `\n` at the end of the input prompt for testing, what happens?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51989384

http://stackoverflow.com/q/52073938
has comment: http://stackoverflow.com/comment/91102143
has body: I am building a NN model using keras and tensorflow for time series binary classification. This is how my input looks like, with a shape of (124,4,591): | Col 1 | Col 2 | Col 3 | Col 4 | Row 1 | [x1, ..., x591] | [x1, ..., x591] | [x1, ..., x591] | [x1, ..., x591] | Row 2 | [x1, ..., x591] | [x1, ..., x591] | [x1, ..., x591] | [x1, ..., x591] | Row 3 | [x1, ..., x591] | [x1, ..., x591] | [x1, ..., x591] | [x1, ..., x591] | I split my data into X_train, X_test, y_train and y_test. I also encoded my labels from ['True', 'False'] into [0, 1] using LabelEncoder() and OneHotEncoder(). x = np.stack((np.vstack(x[:,0]),np.vstack(x[:,1]),np.vstack(x[:,2]),np.vstack(x[:,3]))) x = x.reshape((124,4,591)) y = table_raw_ptpt['Binding Known'] X_train, X_test, y_train, y_test = train_test_split(x, y, test_size = 0.3, random_state = 0) X_train.shape returns (86, 4, 591). Encoding for labels: label_encoder = LabelEncoder() integer_encoded_train = label_encoder.fit_transform(array(y_train)) integer_encoded_test = label_encoder.fit_transform(array(y_test)) onehot_encoded_y_train = OneHotEncoder(sparse=False) integer_encoded_train = integer_encoded_train.reshape(len(integer_encoded_train), 1) onehot_encoded_y_train = onehot_encoded_y_train.fit_transform(integer_encoded_train) onehot_encoded_y_test = OneHotEncoder(sparse=False) integer_encoded_test = integer_encoded_test.reshape(len(integer_encoded_test), 1) onehot_encoded_y_test = onehot_encoded_y_test.fit_transform(integer_encoded_test) onehot_encoded_y_train.shape returns (86, 2). Here is my NN: model = Sequential() model.add(Dense(86, activation='relu', input_shape=(4,591))) model.add(Dense(43, activation='relu')) model.add(Dense(20, activation='relu')) model.add(Dense(1, activation='sigmoid')) model.compile(loss = 'binary_crossentropy', optimizer = 'adam', metrics = ['accuracy']) model.summary() It works. But when I try to fit the X_train I get an error: Error when checking target: expected dense_227 to have shape (1,) but got array…
has comment: http://stackoverflow.com/comment/91102040
answer count: 1
tagged with: neural-network
score: 1
tagged with: keras
favorite count: 0
has comment: http://stackoverflow.com/comment/91101958
has comment: http://stackoverflow.com/comment/91098417
has title: Keras Neural Network model for binary classification with 3D tensor time series as input
type: UnansweredQuestion
tagged with: python
upvote count: 2
tagged with: machine-learning
downvote count: 1
tagged with: tensorflow
type: Question
has comment: http://stackoverflow.com/comment/91102079
has comment: http://stackoverflow.com/comment/91102249
has comment: http://stackoverflow.com/comment/91098373
linked to: http://stackoverflow.com/q/44704435
has answer: http://stackoverflow.com/a/52080656

http://stackoverflow.com/a/52106255
answers question: http://stackoverflow.com/q/52089760
type: Answer
has body: the easiest way to do this is to override save() method and do it there, you can see an example of it here: https://github.com/elastic/elasticsearch-dsl-py/blob/master/examples/parent_child.py#L84-L85
upvote count: 1
has comment: http://stackoverflow.com/comment/91203914
score: 1
accepted answer of: http://stackoverflow.com/q/52089760
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/51983498
has body: I have a matrix, and I want to find the index which has the maximum row sum: [[0. 0. 0. 0.] [0. 0. 0. 0.] [0. 0. 0. 0.] [2. 4. 4. 5.] [0. 0. 0. 0.] [0. 0. 0. 0.] [0. 0. 0. 0.] [0. 0. 0. 0.] [0. 0. 0. 0.]] Here it should be returned 3. Thanks
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/29217072
downvote count: 3
has answer: http://stackoverflow.com/a/51983577
has comment: http://stackoverflow.com/comment/90916344
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/90916315
answer count: 3
accepted answer: http://stackoverflow.com/a/51983577
has title: Get the index of which the sum is max Python 3
score: -2
favorite count: 0
has answer: http://stackoverflow.com/a/51983681
has comment: http://stackoverflow.com/comment/90916420
possible better answer: http://stackoverflow.com/a/51983618
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/51983618

http://stackoverflow.com/comment/91024806
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52036016
type: AnswerComment
has text: sir, I could not sort it using your solution. Btw, could you please assist me in the load file too

http://stackoverflow.com/comment/91142105
comment on: http://stackoverflow.com/q/52094804
has text: final['Valid to'].head() Out[78]: 2017-03-03 00:00:00 2016-01-23 00:00:00 2017-05-19 00:00:00 2013-06-27 00:00:00 2015-01-18 00:00:00 Name: Valid to, dtype: object
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91182691
type: Comment
has text: @ImportanceOfBeingErnest Doesn't `Spectral(norm(1))` give value equal to `Spectral(0.0)`?
type: AnswerComment
comment on: http://stackoverflow.com/a/52110108
score: 0

http://stackoverflow.com/q/52026978
score: 0
has comment: http://stackoverflow.com/comment/91004224
tagged with: python
has body: I have written the following code p1=1 p2=2 p3=set(p1).union(set(p2)) p3 In this case I would have expected for p3 to be equal to {1,2}, but when trying to run the program, I obtain: 'int' object is not iterable How may I fix this? Is there also a way to print the answer as an ordered pair? such as (1,2) in this case. I have changed the code a little, because this is what I would like to fix, since having this step solved, will let me know how I do the rest. Thanks in advance
tagged with: attributes
tagged with: integer
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91004589
tagged with: set
has answer: http://stackoverflow.com/a/52028998
type: Question
answer count: 1
tagged with: set-union
has comment: http://stackoverflow.com/comment/91008170
has title: error when taking the union of two integers which are in a set

http://stackoverflow.com/q/52041907
has comment: http://stackoverflow.com/comment/91034568
upvote count: 2
answer count: 1
downvote count: 1
linked to: http://stackoverflow.com/q/19483351
favorite count: 0
has comment: http://stackoverflow.com/comment/91034622
has body: im having trouble with a recursive function that i'm trying to make so i can transform a json file with several nested dicts and lists (and sometimes nested dicts and lists inside other nested dicts and lists). basically i'm trying to organize a JSON file in a simple OrderedDict so i can pass it to the MongoDB database here is the recursive function: def JSON_Treating(self,json_data): headers = [] data = [] for key, value in json_data.iteritems(): headers.append(key) try: if isinstance(value, (dict,list)): if isinstance(value, list) and isinstance(value[0], dict): value = value[0] self.JSON_treating(value) data.append(value) except: data.append(value) Dict = OrderedDict(zip(headers,dados)) self.JSON_treating(Dict) return Dict the objective here is, each time the code finds a nested table it gets its headers and values and append the headers to the headers and values to the data, then, when its finished the code will join the headers and the values in order. My problem is, i cannot get it right, see... Either the code doesn't get all the nested ones or the code simply don't work. Please help Thanks! EDIT: here is a example of the input JSON [ { "status": 0, "payment_value": 0, "date": "2018-07-28 12:18:00", "Payment": [ { "payment_general": 0, "code": 1, "total_value": 0, "payment_form": "card" } ], "id__": "", "Product": [ { "sku": "00000", "ID_delivery": null, "ammount": 1, "unitary_value": 55.34, "discount_name": null, "delivery_form": null, "discount_ammount": 0, "delivery_charge": 20.34, "taxes": 0, "comission": null, "id__discount": null } ], "client": { "delivery": { "phone": [ "1", "2" ], "fax": null, "name": "A name here", "state_tax": "free", "address": { "reference": "a reference here", "complement": "a complement here", "block": "N123", "city": "New York", "road_name": "a road name", "number": "413", "postal_code": "123234", "country": "US", "State": "NY" }, "email": "", "document": "" }, "taxation": { "phones": [ "1", "2" ], "fax": null, "type": "AN", "n…
tagged with: python
type: AnsweredQuestion
score: 1
tagged with: http://stackoverflow.com/tag/json
has comment: http://stackoverflow.com/comment/91034698
tagged with: pymongo
has answer: http://stackoverflow.com/a/52043262
accepted answer: http://stackoverflow.com/a/52043262
has comment: http://stackoverflow.com/comment/91035318
type: Question
tagged with: recursion
has title: recursive python-JSON reader

http://stackoverflow.com/q/52042298
upvote count: 0
score: -1
tagged with: data-science
has comment: http://stackoverflow.com/comment/91037096
tagged with: pandas
favorite count: 0
has answer: http://stackoverflow.com/a/52042449
possible better answer: http://stackoverflow.com/a/52042546
tagged with: python
downvote count: 1
has answer: http://stackoverflow.com/a/52042546
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91036175
has comment: http://stackoverflow.com/comment/91035474
has title: How to Insert a List of Data into Pandas Multi-Index Dataframe
tagged with: web-scraping
type: Question
accepted answer: http://stackoverflow.com/a/52042449
has body: How can I insert this list of data into a pandas DataFrame orgdata = ['somestring', data[2], data[3], data[4], data[8], data[9], data[10], data[14], data[15], data[16], data[20], data[21], data[22], data[26], data[27], data[28], data[32], data[33], data[34], data[38], data[39], data[40], data[44], data[45], data[46] ] where 'data' is another list of data out of which i parse specific data. I have a list of columns names which is also derived from the 'data' list colnames = ['USN', data[0], data[6], data[12], data[18], data[24], data[30], data[36], data[42]] Now I need to have three subcolumns under each column, so i do this cols = pd.MultiIndex.from_product([colnames, ['IA', 'EX', 'Total']]) But when i try to insert this list of 'data' into a DataFrame like this df = pd.DataFrame(orgdata, columns=cols) I get the following error ValueError: Wrong number of items passed 1, placement implies 27 Also i get this error ValueError: Shape of passed values is (1, 25), indices imply (27, 25) What am I doing wrong? The documentation provided online doesn't give much insight to this topic. Are there any other ways to work around this? Any help provided is Appreciated. Edit: First I make a list of 'data' from the response of a request I made to. Here's an instance of the data i received from the response. data = ['15EC41', 'LIC', '40', '60', 'P'] This is the sort of data i'm working with.
answer count: 2

http://stackoverflow.com/q/52067792
has title: python surface plot gradually varied color
has body: I need to make a figure for the project. Now I get 90% of it. However, I want my figure to have some gradually varied color, some mix of red and balck. Is there anyway in python where I can achieve it? Here's the figure I got: Here's the figure I want: Here's my code import numpy as np from matplotlib import cm, colors import matplotlib.pyplot as plt import scipy.special as sp from mpl_toolkits.mplot3d import Axes3D phi, theta = np.mgrid[0:2*np.pi:300j, 0:np.pi:150j] Y30 = sp.sph_harm(0, 3, phi, theta).real Y20 = sp.sph_harm(0, 2, phi, theta).real R0 = 1 alpha30 = 0.1 alpha20 = 0.02 prefactor = alpha30*Y30 + alpha20 * Y20 +1 X = R0 * prefactor * np.sin(theta) * np.cos(phi) Y = R0 * prefactor * np.sin(theta) * np.sin(phi) Z = R0 * prefactor * np.cos(theta) norm = colors.Normalize() fig, ax = plt.subplots(subplot_kw=dict(projection='3d'), figsize=(10.5,10)) m = cm.ScalarMappable(cmap=cm.jet) # hide the background axes plt.axis('off') # change the view ax.view_init(1, ) ax.plot_surface(X, Y, Z, rstride=10, cstride=10, color = 'orangered', edgecolors='k',shade = True) m.set_array(R0) I don't need my figure to be exactly the same. I just want it to have some mixture of red and black, varying gradually. I would be very appreciate for the help.
score: 0
tagged with: python
has comment: http://stackoverflow.com/comment/91086429
has comment: http://stackoverflow.com/comment/91085831
answer count: 0
type: UnansweredQuestion
tagged with: plot
linked to: http://stackoverflow.com/q/28232879
tagged with: matplotlib
type: Question

permissions
tag name: permissions
type: Tag
tags question: http://stackoverflow.com/q/51959205
tags question: http://stackoverflow.com/q/52102025
tags question: http://stackoverflow.com/q/52047665
tags question: http://stackoverflow.com/q/51957759

http://stackoverflow.com/a/52028274
accepted answer of: http://stackoverflow.com/q/52028219
type: Answer
has comment: http://stackoverflow.com/comment/91006937
has body: The simplest and most straightforward way to indicate a single thread is "done" is to put the required notification in the thread's implementation method, as the very last step. For example, you could print out a notification to the user. Or, you could use events, see: https://docs.python.org/3/library/threading.html#event-objects This is one of the simplest mechanisms for communication between threads: one thread signals an event and other threads wait for it. An event object manages an internal flag that can be set to true with the set() method and reset to false with the clear() method. The wait() method blocks until the flag is true. So, the "final act" in your thread implementation would be to set an event object, and your main thread can wait until it's set. Or, for an even fancier and more mechanism, use queues: https://docs.python.org/3/library/queue.html Each thread writes an "I'm done" object to the queue when done, and the main thread can read those notifications from the queue in sequence as each thread completes.
answers question: http://stackoverflow.com/q/52028219
type: AcceptedAnswer
score: 0

http://stackoverflow.com/a/52003938
upvote count: 1
answers question: http://stackoverflow.com/q/52003818
score: 1
downvote count: 0
has body: You can. The class B is bound to the instance of class A. But you can only access class variables of B. To access instance variable of B you have to create an instance of B and attach it to the object of A. class A(object): def __init__(self): self.b = A.B(100) def toto(self): print(self.b.a) # this will print 100 class B(object): def __init__(self, a): self.a = a
type: Answer

http://stackoverflow.com/a/52014038
has comment: http://stackoverflow.com/comment/90978773
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/90978569
type: Answer
answers question: http://stackoverflow.com/q/52014011
score: 1
upvote count: 1
accepted answer of: http://stackoverflow.com/q/52014011
has body: Use itertools.product and .join: from itertools import product l = [[(u'sss',)], [(u'ssss',), (u'sssssss',)], [(u'121',), (u'222',)]] result = [''.join(token + 'title' for [token] in tokens) for tokens in product(*l)] Output: ['ssstitlesssstitle121title', 'ssstitlesssstitle222title', 'ssstitlessssssstitle121title', 'ssstitlessssssstitle222title']

sensors
type: Tag
tag name: sensors
tags question: http://stackoverflow.com/q/51972632
tags question: http://stackoverflow.com/q/52100762
tags question: http://stackoverflow.com/q/51985916

http://stackoverflow.com/q/52073964
downvote count: 0
score: 4
favorite count: 0
tagged with: darkflow
tagged with: python
tagged with: yolo
type: UnansweredQuestion
tagged with: machine-learning
has answer: http://stackoverflow.com/a/54622898
has title: darkflow - AttributeError: 'NoneType' object has no attribute 'find'
tagged with: image-processing
type: Question
upvote count: 4
has answer: http://stackoverflow.com/a/62060761
answer count: 2
has body: new to darkflow and python. i am trying to train my own datasets by using https://github.com/thtrieu/darkflow and yolo weights. I'm currently having errors: AttributeError: 'NoneType' object has no attribute 'find' when executing pascal_voc_clean_xml.py line 41: 'w = (imsize.find('width').text) ' This is part of the code from https://github.com/thtrieu/darkflow/blob/master/darkflow/utils/pascal_voc_clean_xml.py: in_file = open(file) tree=ET.parse(in_file) root = tree.getroot() jpg = str(root.find('filename').text) imsize = root.find('size') w = int(imsize.find('width').text) h = int(imsize.find('height').text) all = list() for obj in root.iter('object'): current = list() name = obj.find('name').text if name not in pick: continue xmlbox = obj.find('bndbox') xn = int(float(xmlbox.find('xmin').text)) xx = int(float(xmlbox.find('xmax').text)) yn = int(float(xmlbox.find('ymin').text)) yx = int(float(xmlbox.find('ymax').text)) current = [name,xn,yn,xx,yx] all += [current] add = [[jpg, [w, h, all]]] dumps += add in_file.close() and this is my xml file: I know that the 'find' is a function from ElementTree.py in python but why it the 'find' function does not work as it should be?

pivot-table
tag name: pivot-table
tags question: http://stackoverflow.com/q/52037388
tags question: http://stackoverflow.com/q/52026707
tags question: http://stackoverflow.com/q/52024928
tags question: http://stackoverflow.com/q/52005592
tags question: http://stackoverflow.com/q/52024175
type: Tag

http://stackoverflow.com/a/52001957
score: 9
has comment: http://stackoverflow.com/comment/90955160
type: AcceptedAnswer
upvote count: 9
has body: When you use tix widgets, you also need to use the tix version of Tk(). So replace root = Tk() with: root = tix.Tk()
has comment: http://stackoverflow.com/comment/90953196
type: Answer
has comment: http://stackoverflow.com/comment/90954600
downvote count: 0
answers question: http://stackoverflow.com/q/52001532
accepted answer of: http://stackoverflow.com/q/52001532
has comment: http://stackoverflow.com/comment/90957517

http://stackoverflow.com/q/52012401
tagged with: django
has answer: http://stackoverflow.com/a/59214987
has answer: http://stackoverflow.com/a/52019418
has title: How and why I can't override related manager method on django?
type: Question
has body: I have this manager: class ConfigValueManager(models.Manager): def get(self, key): config_value = self.filter(key=key).first() if config_value: type_caster = locate(config_value.type) return type_caster(config_value.value) return config_value def set(self, key, value): self.filter(key=key).update(value=value) def set2(self, key, value): qs = self.filter(key=key) if qs: qs.update(value=value, type=type(value).__name__, company=self.instance) else: self.create(key=key, value=value, type=type(value).__name__, company=self.instance) the problem is that I can't overwrite set. The method is still coming from the parent, even though I've created set on the child. Funny thing is that get and set2 are fine. Even add which isn't in my example can't be overridden. My question is how can I overwrite set and why this happens?
score: 0
answer count: 2
tagged with: entitymanager
has comment: http://stackoverflow.com/comment/90987039
has comment: http://stackoverflow.com/comment/91029631
has comment: http://stackoverflow.com/comment/90981205
tagged with: python
has comment: http://stackoverflow.com/comment/90985852
type: UnansweredQuestion
tagged with: orm

http://stackoverflow.com/q/52013365
tagged with: python
type: AnsweredQuestion
has title: Is modifying sys.path the best way to handle a project specific module
type: Question
has body: I'm (re)writing in python part of the testing tools supporting a large multi-language project, which are stored along side the project itself. At some point it becomes obvious that some code can be refactored out into its own package. But where should this be stored to be shared among the python tools? In the python path, there is a company wide python-lib directory, but that shares with thousands what really is only important to tens of people, and more importantly, is not project specific. For c test tools, we use LD_LIBRARY_PATH to point to our test libs, either pointing to our own build of the libs, or to some automated build output. I can modify sys.path to include any directory I want, and behave kinda like LD_LIBRARY_PATH, except easier for my teammates. This doesn't seem pythonic. I am aware of virtualenv, though not well informed, but I have these concerns: Does this store multiple copies of the library, or is it simlinked? Python library size is negligible, but this is still frowned on by IT with our very large repositories. related, are the libraries kept in sync so bug fixes go to each tool? teammates would not want to run additional commands, ./gen_test_stimulus is best, and env LD_LIBRARY_PATH=../testlib is ok. Multiple commands would face some resistance. Is wrapping the virtualenv commands in a bash script the way to solve this?
tagged with: virtualenv
score: 0
answer count: 1
has answer: http://stackoverflow.com/a/52013414
accepted answer: http://stackoverflow.com/a/52013414

http://stackoverflow.com/q/52058695
score: 0
downvote count: 2
answer count: 3
has comment: http://stackoverflow.com/comment/91067705
has body: I have data in pandas DataFrame: import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns np.random.seed(786) df = pd.DataFrame({'a':np.arange(0, 1, 0.05), 'b':np.random.rand(20) - .5}) print (df) a b 0 0.00 0.256682 1 0.05 -0.192555 2 0.10 0.393919 3 0.15 -0.113310 4 0.20 0.373855 5 0.25 -0.423764 6 0.30 -0.123428 7 0.35 -0.173446 8 0.40 0.440818 9 0.45 -0.016878 10 0.50 0.055467 11 0.55 -0.165294 12 0.60 -0.216684 13 0.65 0.011099 14 0.70 0.059425 15 0.75 0.145865 16 0.80 -0.019171 17 0.85 0.116984 18 0.90 -0.051583 19 0.95 -0.096527 I would like plot barplot and add vertical line: plt.figure(figsize=(10,5)) sns.barplot(x = 'a', y = 'b', data = df) plt.vlines(x = 0.45, ymin = 0, ymax = 0.6, color = 'red', linewidth=5) There are problems with ticklabels, because overlaping and also line should be in point 0.45 instaed near 0 for x axis. I try many solutions from link1, link2, link3, link4 but still problem set correctly axis for both plots. What is problem? Is possible share x axis between plots? Expected output - correctly aligned vertical line and also not overlaping ticks in x axis:
has answer: http://stackoverflow.com/a/52099199
tagged with: axis
tagged with: axis-labels
has comment: http://stackoverflow.com/comment/91067678
has comment: http://stackoverflow.com/comment/91068308
favorite count: 0
linked to: http://stackoverflow.com/q/14373884
possible better answer: http://stackoverflow.com/a/52099199
has title: Share x axis between matplotlib and seaborn
tagged with: seaborn
has comment: http://stackoverflow.com/comment/91068389
tagged with: python
has comment: http://stackoverflow.com/comment/91067967
linked to: http://stackoverflow.com/q/38810009
has comment: http://stackoverflow.com/comment/91068781
has comment: http://stackoverflow.com/comment/91067794
has comment: http://stackoverflow.com/comment/91068215
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/52059472
has comment: http://stackoverflow.com/comment/91070624
type: Question
has answer: http://stackoverflow.com/a/52059472
has answer: http://stackoverflow.com/a/52058759
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/91068443
has comment: http://stackoverflow.com/comment/91067768
has comment: http://stackoverflow.com/comment/91068151
linked to: http://stackoverflow.com/q/33884910
linked to: http://stackoverflow.com/q/10984085
upvote count: 2

http://stackoverflow.com/comment/91074883
score: 0
has text: Although the duplicate is asking how to count from the left rather than the right, the second answer is actually counting from the right, and the accepted one can count from either side (it’s just a matter of negative indexing), so I think your best answers are all there.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52061936

http://stackoverflow.com/a/52088781
downvote count: 0
answers question: http://stackoverflow.com/q/52088035
score: 3
upvote count: 3
has body: import pandas as pd # 'dataframe' is the name of your data frame in the question, so that's what I use # in my code below, although I suggest using 'data' or something for it instead, # as 'DataFrame' is a keyword and its easy to make confusion. But anyway... features = ['list of column names you want one-hot encoded'] # for example, features = ['Cars', 'Model, 'Year', ... ] for f in features: df = dataframef df2 = (pd.get_dummies(df, prefix='', prefix_sep='') .max(level=0, axis=1) .add_prefix(f+' - ')) # the new feature names will be "&lt;old_feature_name&gt; - &lt;categorical_value&gt;" # for example, "Cars" will get transformed to "Cars - Minivan", "Cars - Truck", etc # add the new one-hot encoded column to the dataframe dataframe = pd.concat([dataframe, df2], axis=1) # you can remove the original columns, if you don't need them anymore (optional) dataframe = dataframe.drop([f], axis=1)
type: Answer

http://stackoverflow.com/comment/91173771
score: 0
type: Comment
type: QuestionComment
has text: Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/179164/discussion-between-shashi-shankar-singh-and-ansgar-wiechers).
comment on: http://stackoverflow.com/q/52098845

http://stackoverflow.com/q/51994575
has comment: http://stackoverflow.com/comment/90969424
downvote count: 1
accepted answer: http://stackoverflow.com/a/51994889
has comment: http://stackoverflow.com/comment/90956092
upvote count: 0
linked to: http://stackoverflow.com/q/5186520
has comment: http://stackoverflow.com/comment/90938895
has comment: http://stackoverflow.com/comment/90938992
has comment: http://stackoverflow.com/comment/90939620
type: Question
has comment: http://stackoverflow.com/comment/90938974
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90939423
score: -1
favorite count: 0
has comment: http://stackoverflow.com/comment/90938972
has comment: http://stackoverflow.com/comment/90939000
linked to: http://stackoverflow.com/q/1092531
has comment: http://stackoverflow.com/comment/90939011
tagged with: python
tagged with: dictionary
answer count: 1
has body: After changing a value in a dict i'd like to automatically save that dict to a file. I already do the saving to file but how to detect the change and trigger the saving? I'm using Python 3.7
has title: In Python: how to automatically save to file after dict changed?
has comment: http://stackoverflow.com/comment/90939077
has answer: http://stackoverflow.com/a/51994889
tagged with: file

http://stackoverflow.com/comment/91166261
has text: oh thank you really I was struggling a lot for it thanks for your contribution. I need one more if possible please help me I have used buttons also which covers whole area of grid layout suppose I have used grid layout with 4 columns and near by 8 buttons they cover all area on screen I just need that buttons to cover only text or make all buttons of same size. Thank you very much.
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52086896
score: 0

http://stackoverflow.com/comment/91084896
comment on: http://stackoverflow.com/q/52067222
score: 0
type: Comment
type: QuestionComment
has text: If c = [1, 2], then c[1] - c[0] will be 1 (2-1). Yes @Patrick, this is what I want to do, however, my list will be always updating, so how should i write in a code?

http://stackoverflow.com/comment/90876914
type: QuestionComment
comment on: http://stackoverflow.com/q/51963134
type: Comment
has text: @AlexHall not working locally.. strange.
score: 0

http://stackoverflow.com/q/52046016
score: 0
has comment: http://stackoverflow.com/comment/91043025
answer count: 1
tagged with: python-3.x
type: UnansweredQuestion
tagged with: python
has body: i am new to python so i hope you guys can help me out. Currently i am using the import function to get my output, but i wish to include def function to this set of code that count the top 10 most frequent word. But i can't figure it out. Hope you guys can help me. Thanks in advance!!! import collections import re file = open('partA', 'r') file = file.read() stopwords = set(line.strip() for line in open('stopwords.txt')) stopwords = stopwords.union(set(['it', 'is'])) wordcount = collections.defaultdict(int) """ the next paragraph does all the counting and is the main point of difference from the original article. More on this is explained later. """ pattern = r"\W" for word in file.lower().split(): word = re.sub(pattern, '', word) if word not in stopwords: wordcount[word] += 1 to_print = int(input("How many top words do you wish to print?")) print(f"The most common {to_print} words are:") mc = sorted(wordcount.items(), key=lambda k_v: k_v[1], reverse=True) [:to_print] for word, count in mc: print(word, ":", count) The output: How many top words do you wish to print?30 The most common 30 words are: hey : 1 there : 1 this : 1 joey : 1 how : 1 going : 1
has comment: http://stackoverflow.com/comment/91043029
has title: how to use the def function
type: Question
has answer: http://stackoverflow.com/a/52046623

http://stackoverflow.com/q/52077048
linked to: http://stackoverflow.com/q/21895756
has comment: http://stackoverflow.com/comment/91104008
has title: Python numpy.linspace behaves strangely with floats
tagged with: python
favorite count: 0
type: UnansweredQuestion
downvote count: 1
has answer: http://stackoverflow.com/a/52077106
score: -1
linked to: http://stackoverflow.com/q/588004
has body: I have an issue with numpy linspace import numpy as np temp = np.linspace(1,2,11) for t in temp: print(t) This return : 1.0 1.1 1.2 1.3 1.4 1.5 1.6 1.7000000000000002 1.8 1.9 2.0 The 1.7 value looks definitely wrong. It seems related to this issue https://github.com/numpy/numpy/issues/8909 Does anybody ever had such a problem with numpy.linspace ? is it a known issue ? François
type: Question
tagged with: numpy
upvote count: 0
has comment: http://stackoverflow.com/comment/91104004
answer count: 1

http://stackoverflow.com/q/52005888
has body: How to pass client certificate to WebSocket in Python? What are the options for specifying paths to SSL certifcate and key? I have following code: import websocket sslopt = { 'check_hostname': False } ws = websocket.WebSocket(sslopt=sslopt) ws = ws.connect('wss://domain.name/end-point/name') print(ws.recv()) I works when I am connecting directly, to WebSocket server, but I need to connect to WebSocket server hidden behind nginx with SSL enabled.
answer count: 0
downvote count: 0
type: Question
has title: How to pass client certificate to WebSocket in Python?
tagged with: websocket
tagged with: ssl
score: 4
has comment: http://stackoverflow.com/comment/138733240
favorite count: 0
has comment: http://stackoverflow.com/comment/116874353
type: UnansweredQuestion
tagged with: python
upvote count: 4

http://stackoverflow.com/a/65844520
type: Answer
has body: Try this approach to convert response['records'] into dataframe using columnMetadata: def results_to_df(response): columns = [ col['label'] for col in response['columnMetadata'] ] listed_results = [[list(col.values())[0] if list(col.values())[0] else '' for col in record] for record in response['records']] df = pd.DataFrame(listed_results, columns=columns) return df
score: 0
answers question: http://stackoverflow.com/q/52026405

http://stackoverflow.com/q/52076814
tagged with: pandas
favorite count: 0
tagged with: beautifulsoup
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/52078015
downvote count: 0
type: Question
score: 3
has answer: http://stackoverflow.com/a/52077589
has body: I'm using BeautifulSoup4 to scrape info from a website and using Pandas to export the data to a csv file. There are 5 columns of data represented by 5 lists in a dictionary. However, since the website doesn't have complete data for all 5 categories, some lists have fewer items than others. So when I try to export the data, pandas gives me ValueError: arrays must all be same length. What is the best way to handle this situation? To be specific, the lists with fewer items are "authors" and "pages". Thanks in advance! Code: import requests as r from bs4 import BeautifulSoup as soup import pandas #make a list of all web pages' urls webpages=[] for i in range(15): root_url = 'https://cross-currents.berkeley.edu/archives?author=&amp;title=&amp;type=All&amp;issue=All&amp;region=All&amp;page='+ str(i) webpages.append(root_url) print(webpages) #start looping through all pages titles = [] journals = [] authors = [] pages = [] dates = [] issues = [] for item in webpages: headers = {'User-Agent': 'Mozilla/5.0'} data = r.get(item, headers=headers) page_soup = soup(data.text, 'html.parser') #find targeted info and put them into a list to be exported to a csv file via pandas title_list = [title.text for title in page_soup.find_all('div', {'class':'field field-name-node-title'})] titles += [el.replace('\n', '') for el in title_list] journal_list = [journal.text for journal in page_soup.find_all('em')] journals += [el.replace('\n', '') for el in journal_list] author_list = [author.text for author in page_soup.find_all('div', {'class':'field field--name-field-citation-authors field--type-string field--label-hidden field__item'})] authors += [el.replace('\n', '') for el in author_list] pages_list = [pages.text for pages in page_soup.find_all('div', {'class':'field field--name-field-citation-pages field--type-string field--label-hidden field__item'})] pages += [el.replace('\n', '') for el in pages_list] date_list = [date.text for date in page_soup.find_all('div', {'class':'field field-…
tagged with: python-3.6
upvote count: 3
has title: BeautifulSoup4 scraping: Pandas "arrays must all be same length" when exporting data to csv
answer count: 2

http://stackoverflow.com/q/51983684
answer count: 2
upvote count: 1
favorite count: 0
tagged with: python-3.x
tagged with: pycharm
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51984862
tagged with: python
has title: PyCharm (Python 3.x) modify a class without re-running the script
downvote count: 0
score: 1
has answer: http://stackoverflow.com/a/68451384
type: Question
tagged with: debugging
tagged with: ide
has body: I am using PyCharm Pro 2018 and just made the switch to it recently (from Spyder). The first part of my script involves loading a lot of data and takes about 1-2 minutes. On completion or error of the script I get a python console with all the current variables where I can investigate. Now if I would like to change a method/function and run it again WITHOUT completely restarting the script, how can I do that? Here some pseudocode: class FetchData(): ... class ParseData(): ... def subroutine1(self, ...): ... data = FetchData(...) # takes a long time parser = ParseData(data,...) parser.subroutine1(...) After running this code and getting an error in subroutine1, I get a console and can look at "data" and "parser" (as well as any other variables). Is it possible to modify subroutine1 and manually re-run that method in the console "parser.subroutine1(...)" with the changed method and "data" still intact? If not, or in general, what would be the best practice to code on subroutine1 without having to constantly reload "data = FetchData(...)"? Thanks a lot!

http://stackoverflow.com/comment/90949354
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51962316
has text: I actually solved the problem: I used a merge and then two filters on my data after computing the time periods (instead of doing the comparison, I think it is more efficient). Thanks anyway :-)

http://stackoverflow.com/comment/91069183
has text: -f is an option to force installation of all package https://conda.io/docs/commands/conda-install.html
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52059386

http://stackoverflow.com/q/52019063
has body: I am learning Python from a book and reached classes. As I created my first program using classes, the program returns no output but just exits with code 0. class Restaurant(): def __init__(self, restaurant_name, cuisine_type): self.restaurant_name = restaurant_name self.cuisine_type = cuisine_type def describe_restaurant(self): print("\nThe restaurant is : " + self.restaurant_name) print('\nThe cuisine offered is : '+ self.cuisine_type) def open_restaurant(): print('\n\nThe restaurant is open! ') rest_1 = Restaurant("Good", 'Indian') rest_1.describe_restaurant() print("Hello") I included the print("Hello") just to check the output comes or not but there is nothing. I guess I seriously messed something which might even be a pretty silly one. Help me out on this one! Thanks.
tagged with: class
has comment: http://stackoverflow.com/comment/90997989
answer count: 0
has title: Python Class no output from print statements
has comment: http://stackoverflow.com/comment/90997959
has comment: http://stackoverflow.com/comment/90988462
type: Question
has comment: http://stackoverflow.com/comment/90989014
has comment: http://stackoverflow.com/comment/90988459
tagged with: python
has comment: http://stackoverflow.com/comment/90988375
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/90998028
score: 0
has comment: http://stackoverflow.com/comment/90988411
upvote count: 1
has comment: http://stackoverflow.com/comment/90988404
downvote count: 1
has comment: http://stackoverflow.com/comment/90997941
has comment: http://stackoverflow.com/comment/90997895
type: UnansweredQuestion

traitsui
tag name: traitsui
tags question: http://stackoverflow.com/q/52084758
type: Tag

http://stackoverflow.com/q/51992562
downvote count: 0
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/51993871
score: 3
has body: Consider the following fixture @pytest.fixture(params=['current', 'legacy']) def baseline(request): return request.param I wonder if there is a way to launch pytest so it overrides the fixture parameter list with the value(s) given on the command line, i.e.: pytest --baseline legacy tests/ The above should effectively result in params=['legacy'].
tagged with: python
upvote count: 3
has title: Pytest - How to override fixture parameter list from command line?
answer count: 1
tagged with: testing
tagged with: pytest
has answer: http://stackoverflow.com/a/51993871
type: AnsweredQuestion

http://stackoverflow.com/q/52017973
type: Question
has answer: http://stackoverflow.com/a/52018197
has body: I am new to handling data in json file and i am trying to extract specific information ( "expanded_url" in my case). when i am loading the json file as string using json.loads() i cannot select expanded_url data from the list of stings. i am proving my json data drive link for your reference. My query: i want to extract only "expanded_url" field mentioned in entity data (it may or may not be empty) from the json file. json data: https://drive.google.com/file/d/1Hgnwi74JTECY4cQRp3rG3zX4DX1dGa9A/view?usp=sharing
downvote count: 0
answer count: 1
favorite count: 0
has title: How to select a specific field in json data in python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90986260
tagged with: python
score: 1
tagged with: http://stackoverflow.com/tag/json
upvote count: 1

http://stackoverflow.com/comment/91167610
comment on: http://stackoverflow.com/a/52108443
has text: There is an anagram generator in the notes for Lecture 2. Write a different anagram generator that makes only one recursive call instead of n recursive calls as is done by the program in the notes. Set up an experiment to 2 compare the running times of the two programs. Produce a table showing your results. Carry out the calculations until you see a difference in the results or until you have exhausted the resources necessary to run the anagram generator. Describe your results, and project the future behavior of these two algorithms.
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/90992839
comment on: http://stackoverflow.com/a/52020441
score: 1
type: AnswerComment
has text: Did it do any help?
type: Comment

http://stackoverflow.com/a/52041849
has comment: http://stackoverflow.com/comment/91037430
has comment: http://stackoverflow.com/comment/91078223
answers question: http://stackoverflow.com/q/52041720
has comment: http://stackoverflow.com/comment/91089740
has comment: http://stackoverflow.com/comment/91054189
has comment: http://stackoverflow.com/comment/91054922
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/91036206
score: 2
has body: this line cleanText += myWord just concatenates all of the words to one long string. if you want to filter '\n', instead of: for myWord in text: if myWord != '\n': cleanText += myWord text = cleanText.strip().split() you can do this: text = [w for w in text if w != '\n']
upvote count: 2

http://stackoverflow.com/q/52022693
type: UnansweredQuestion
has body: I am trying to use ExponentialSmoothing (using pandas) to forecast electrical power demand. The code I wrote and its output follows are attached at the end of this message. Any clues on why is this producing all NaNs? Training is hourly spaced and I am assuming daily (24 measurement) seasonality. Thanks in advance, Juan Flores print('modeling') t1=time.time() model = ExponentialSmoothing(KWHTr, trend='add', seasonal='add', seasonal_periods=24).fit() t2=time.time() print('modeling time: ', t2-t1, 'sec') print('predicting') start_date = KWHVa.index[0] end_date = KWHVa.index[-1] print('period: (', start_date, '-', end_date,')') pred=KWHVa.copy() pred = model.predict(start=start_date, end=end_date) print(pred) print('*') Output: modeling modeling time: 109.9684362411499 sec predicting period: (2017-10-29 10:00:00 - 2017-11-02 13:00:00 ) 2017-10-29 10:00:00 NaN 2017-10-29 11:00:00 NaN 2017-10-29 12:00:00 NaN 2017-10-29 13:00:00 NaN 2017-10-29 14:00:00 NaN .. 2017-11-02 09:00:00 NaN 2017-11-02 10:00:00 NaN 2017-11-02 11:00:00 NaN 2017-11-02 12:00:00 NaN 2017-11-02 13:00:00 NaN Freq: H, Length: 100, dtype: float64 *
score: 2
has title: Exponential Smoothing in python produces all NaNs
tagged with: dataframe
type: Question
tagged with: time-series
tagged with: forecasting
answer count: 1
downvote count: 0
favorite count: 0
tagged with: pandas
has answer: http://stackoverflow.com/a/52026318
tagged with: python
upvote count: 2

http://stackoverflow.com/comment/90931951
type: Comment
score: 2
comment on: http://stackoverflow.com/q/51991069
has text: what your command is doing is actually installing a library called `requests`, can you confirm if you want to update `pip` or `requests`?
type: QuestionComment

http://stackoverflow.com/q/51990533
score: 0
answer count: 1
has body: from turtle import * epic = Turtle() epic.color('blue', 'red') epic.penup() epic.goto(0,0) epic.pd() epic.speed(10000) numb = 1 epic.begin_fill() while numb == 1: epic.right(90) epic.forward(40) epic.right(90) epic.forward(40) epic.right(90) epic.forward(40) epic.right(90) epic.forward(40) If I wanted the square to get bigger evenly on all four sides with each iteration of the loop, what would I add to the "while" loop in order to add one to the integer in the epic.forward() each time the loop runs?
tagged with: integer
tagged with: turtle-graphics
has title: How to increase the number in epic.foward() each iteration in a loop by one?
tagged with: python
accepted answer: http://stackoverflow.com/a/51991543
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51991543
type: Question

evaluation
tags question: http://stackoverflow.com/q/52102217
tag name: evaluation
type: Tag

http://stackoverflow.com/q/52063689
has comment: http://stackoverflow.com/comment/91081134
has answer: http://stackoverflow.com/a/52067640
downvote count: 0
favorite count: 0
has body: I have a dataframe of sentences that looks like this: text 0 this is great! 1 how dare you?! I can succesfully use TextBlob.words (https://textblob.readthedocs.io/en/dev/quickstart.html#tokenization) to break each sentence into its individual words. An example would be a = TextBlob('moon is big') print(a) WordList(['moon','is','big']) WordList creates a list type blob.Wordlist that saves each word. I can break the sentences in the dataframe into individual words and save it it in a variable using this code: for i in df.text: d = TextBlob(i) words_list=d.words To get the sentiment of every word, I need to reapply TextBlob to every word. I can do this with the below code and append the polarity score in a list. lst=[] for i in text.text: d = TextBlob(i) words_list=d.words for i in words_list: f = TextBlob(i) print(f.sentiment) lst.append(f.sentiment.polarity) At this point, I dont know which polarity score belongs to which sentence, because my goal is that I want to average the polarity score of every word per row of dataframe and generate a new column score. Is there anyway I can pass an index per blob.Wordlist so I can match the average back to the dataframe? code so far: from textblob import TextBlob import pandas as pd import statistics as s df = pd.DataFrame({'text':['this is great!','how dare you?!']}) lst=[] for i in text.text: d = TextBlob(i) words_list=d.words for i in words_list: f = TextBlob(i) print(f.sentiment) lst.append(f.sentiment.polarity) for i in lst: z = s.mean(lst) df['score'] = z New df should look like this: text score 0 this is great! 0.2 1 how dare you?! 0.3 NOT text score 0 this is great! 0.133333 1 how dare you?! 0.133333 Thank you in advance. edit: @kevin here is your code with the proper df names from textblob import TextBlob import pandas as pd import statistics as s df = pd.DataFrame({'text':['this is great!','how dare you?!']}) df['score'] = 0 for j in range(len(df.text)): lst=[] i = df.text[j] d = TextBlob(i) words_list=d.words for i i…
has comment: http://stackoverflow.com/comment/91085413
tagged with: pandas
tagged with: textblob
tagged with: python
has comment: http://stackoverflow.com/comment/91085340
tagged with: nlp
score: 2
accepted answer: http://stackoverflow.com/a/52067640
has comment: http://stackoverflow.com/comment/91179084
upvote count: 2
has answer: http://stackoverflow.com/a/52065587
tagged with: indexing
possible better answer: http://stackoverflow.com/a/52065587
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91167350
has comment: http://stackoverflow.com/comment/91081316
has comment: http://stackoverflow.com/comment/91200562
type: Question
has title: How to maintain index when splitting sentences into words and reapplying sentiment polarity to each word?
answer count: 2

http://stackoverflow.com/comment/90927234
type: AnswerComment
comment on: http://stackoverflow.com/a/51985197
type: Comment
has text: Thank you this was true and i tried it but then it gave a binary image instead of the Gaussian i wanted, i've got it now. Thanks for your help :)
score: 0

http://stackoverflow.com/a/52107984
has body: You could use In [300]: df.groupby(df.LoadedDate.astype('datetime64[M]')).last().reset_index(drop=True) Out[300]: LoadedDate 0 2016-02-27 1 2016-03-31 2 2016-04-30 3 2016-05-04 Or, In [295]: df.groupby(df.LoadedDate - pd.offsets.MonthEnd()).last().reset_index(drop=True) Out[295]: LoadedDate 0 2016-02-27 1 2016-03-31 2 2016-04-30 3 2016-05-04 Or, In [301]: df.groupby(df.LoadedDate.dt.to_period('M')).last().reset_index(drop=True) Out[301]: LoadedDate 0 2016-02-27 1 2016-03-31 2 2016-04-30 3 2016-05-04 Or, In [303]: df.groupby(df.LoadedDate.astype(str).str[:7]).last().reset_index(drop=True) Out[303]: LoadedDate 0 2016-02-27 1 2016-03-31 2 2016-04-30 3 2016-05-04 If the dates are not sorted. Using any of the above methods use idxmax and loc In [307]: df.loc[df.groupby(df.LoadedDate.astype(str).str[:7]).LoadedDate.idxmax().values] Out[307]: LoadedDate 7 2016-02-27 28 2016-03-31 49 2016-04-30 52 2016-05-04
score: 7
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52107914
type: Answer
answers question: http://stackoverflow.com/q/52107914
upvote count: 7

http://stackoverflow.com/comment/90903533
score: 0
type: Comment
type: QuestionComment
has text: pd.__version__ '0.23.3'
comment on: http://stackoverflow.com/q/51976576

http://stackoverflow.com/q/52063200
linked to: http://stackoverflow.com/q/25748683
score: -1
has title: Sum of values from csv using pandas
has answer: http://stackoverflow.com/a/52063389
possible better answer: http://stackoverflow.com/a/52063275
tagged with: pandas
downvote count: 1
favorite count: 0
tagged with: python-3.x
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
answer count: 4
has answer: http://stackoverflow.com/a/52063468
accepted answer: http://stackoverflow.com/a/52063468
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52063275
upvote count: 0
has body: I want to sum all the value from the 3rd column to get the result in a new csv file with the first and second column using pandas which a think is more efficient. The maximum values that can be added together are between 0 and 2 the addition will be ignored if there is a value or character other than 0.5 ,1 or 2 Sample of the csv file : https://pastebin.com/WwDWqU3U encounterId|chartTime|11885|67187|6711|6711|6710|1356|1357|1358|1359|1360|1361|1362|1366|140|140 325|2014-01-01 00:00:00|0 325|2014-01-01 01:00:00|0|0|0 325|2014-01-01 02:00:00|0 325|2014-01-01 03:00:00|0|0|0 325|2014-01-01 04:00:00|0 325|2014-01-01 05:00:00|1 325|2014-01-01 06:00:00|0|0|0 325|2014-01-01 07:00:00|1|0|0.5|1 325|2014-01-01 08:00:00|0 325|2014-01-01 09:00:00|1|0|0 325|2014-01-01 10:00:00|0 325|2014-01-01 11:00:00|1|0|0 325|2014-01-01 12:00:00|0 325|2014-01-01 13:00:00|0|0|0.5|1 325|2014-01-01 14:00:00|0 325|2014-01-01 15:00:00|0 what I'm looking for : 323|2013-06-03 00:00:00|0 323|2013-06-03 01:00:00|1 323|2013-06-03 02:00:00|1.5 323|2013-06-03 03:00:00|1.5 323|2013-06-03 04:00:00|0 323|2013-06-03 05:00:00|0.5 323|2013-06-03 06:00:00|0 323|2013-06-03 07:00:00|3.5 323|2013-06-03 08:00:00|0.5 I've tried without pandas it give me some weird result
has answer: http://stackoverflow.com/a/52063313
type: Question

http://stackoverflow.com/a/52079919
type: Answer
answers question: http://stackoverflow.com/q/52079641
upvote count: 1
score: 1
has body: I assume that this is a coding tutorial since there is a built in function to do this? The the problem in your code is that you are not breaking out of the loop when you found a match, so unless the match is in the final place you will not see it as the very next else statement will overwrite your answer. Modify your loop as follows: for j in range(len(T)): if num==T[j]: return True,j return False, "None" # or better still the keyword None (no quotes)
downvote count: 0

http://stackoverflow.com/a/52246169
answers question: http://stackoverflow.com/q/52008433
has body: You can try this code: import pandas as pd from sklearn.feature_extraction.text import TfidfVectorizer vec = TfidfVectorizer(ngram_range=(2,2),use_idf=False) corpus = ["he is not giving up so easily but he feels lonely all the time his mental is strong and he always meet new friends to get motivation and inspiration to success he stands firm for academic integrity when he was young he hope that santa would give him more friends after he is a grown up man he stops wishing for santa clauss to arrival he and his friend always eat out but they clean their hand to remove sand first before eating"] word_of_interest = ['santa', 'and', 'hand', 'stands', 'handy', 'sand'] matrix = vec.fit_transform(corpus).toarray() vocabulary = vec.get_feature_names() all_bigrams = [] all_frequencies = [] for word in word_of_interest: for bigram in vocabulary: if word in bigram: index = vocabulary.index(bigram) tuple_bigram = tuple(bigram.split(' ')) frequency = matrix[:,index].sum() all_bigrams.append(tuple_bigram) all_frequencies.append(frequency) df = pd.DataFrame({'bigram':all_bigrams,'frequency':all_frequencies}) df.sort_values('frequency',inplace=True) df.head() The output is a pandas dataframe showing the bigrams sorted by frequency. bigram frequency 0 (for, santa) 0.109764 19 (stands, firm) 0.109764 18 (he, stands) 0.109764 17 (their, hand) 0.109764 16 (hand, to) 0.109764 The rationale here is that TfidfVectorizer counts how many times a token is present in each document of a corpus, then computes the term-specific frequency, and then stores this information in a column associated with that token. The index of that column is the same as the index of the associated word in the vocabulary that is retrieved with the method .get_feature_names() on the vectorizer already fit. Then you just have to select all rows from the matrix containing the relative frequencies of the tokens, and sum along the column of interest. The double-nested for loop is not ideal though, and there may be a more e…
score: 0
type: Answer

http://stackoverflow.com/comment/91139681
has text: in csv, the default sep is `,` thus `a,b,c,d,e,f,g ` is correctly defined as being 7 columns
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52094808
score: 0

http://stackoverflow.com/comment/91072772
score: 0
has text: @AmirHadifar I've done
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/52060555

http://stackoverflow.com/q/52104673
type: UnansweredQuestion
has title: quicksort algorithm implementation in python
tagged with: python
has comment: http://stackoverflow.com/comment/91160711
has comment: http://stackoverflow.com/comment/91160734
answer count: 0
has body: My implementation doesn't give correct output. i implemented pseudo code present in introduction to algorithm. any help will be great. thanks. def quicksort(A,p,r): if (p &lt; r): q = partition(A,p,r) quicksort(A,p,q-1) quicksort(A,q+1,r) def partition(A,p,r): i = p - 1 pivot = A[r] for j in range(p, r-1): if A[j] &lt;= pivot: i = i +1 A[i] = A[j] A[j] = A[i] A[i+1] = A[r] A[r] = A[i+1] return i+1 A = [10, 7, 8, 9, 1, 5] quicksort(A,0, len(A)-1) print(A)
type: Question
has comment: http://stackoverflow.com/comment/91161426
has comment: http://stackoverflow.com/comment/91160650
has comment: http://stackoverflow.com/comment/91160910
score: 0
has comment: http://stackoverflow.com/comment/91161008
tagged with: python-3.x

http://stackoverflow.com/q/51957010
answer count: 2
has comment: http://stackoverflow.com/comment/90901923
tagged with: for-loop
has title: Divide string from query column and insert results into the same table
has body: I have a table in database, where one column contains first name and second name together (divided by space). I am trying to load these data, split each row and save it again into the table. It is possible to do that a display that data, but when I try to save it back, I am getting 'NoneType' object has no attribute 'split'. import sys, os, pyodbc conn_str = ( r'DRIVER={Microsoft Access Driver (*.mdb, *.accdb)};' r'DBQ=C:/Users/vlcek/Desktop/pokusdb.accdb;' ) connection = pyodbc.connect(conn_str) cursor = connection.cursor() cursor2 = connection.cursor() sql="Select whole_name from people" cursor.execute(sql) for change in cursor: devided=change[0].split() print(devided[0]+"--"+devided[1]) sql2="Insert into people (user_id, Name, Surname) values (27, ?,?)" cursor2.execute(sql2,(devided[0],devided[1])) connection.close() Without those two lines if would work fine and I can show the data in console, so there is problem in those tow lines: sql2="Insert into people (user_id, Name, Surname) values (27, ?,?)" cursor2.execute(sql2,(devided[0],devided[1])) I tried to create also two connection.cursor objects, but it doesn't work even when I worked just with cursor = connection.cursor() Thank you for your advice, Vaclav
downvote count: 0
tagged with: database
has comment: http://stackoverflow.com/comment/90867200
favorite count: 0
linked to: http://stackoverflow.com/q/51976146
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90865124
tagged with: python
tagged with: pyodbc
has answer: http://stackoverflow.com/a/51995146
score: 1
upvote count: 1
tagged with: loops
linked to: http://stackoverflow.com/q/5573724
type: Question
has answer: http://stackoverflow.com/a/51957380

http://stackoverflow.com/q/52085468
has comment: http://stackoverflow.com/comment/121439994
has comment: http://stackoverflow.com/comment/91121760
has title: Measuring the size of an object in photo via reference image
has body: I'm trying to find more information on how you can process an image that contains an object and a reference object to measure estimated sizes. An example, I place my hand flat on a table and place a 1" by 1" purple square next to my hand and take a picture. What algorithms, or techniques do I use to determine the width of my hand, along with the lengths of my fingers? As per the measuring I have found information regarding algorithms that do this here: Measure size of object using reference object in photo which state that if the object is in the same plane as the reference then it's possible. The problem I am having is how I would automatically detect the outlines of objects. I have looked through alot of the open-cv tutorials and such online and it seems the biggest problem is when trying to use the find contours method you need to do erosion based on a threshhold that is seemingly handpicked (meaning trial and error to choose the best one) but this won't work for what I want to use it for. I've written my own genetic algorithm based on a simple NN structure I devised myself but have never gotten much further than this into the field of NN's but I believe this would be a good candidate for NN usage. My idea was to rip several thousand or more images of hands and do the following: Scale them to a common size, keeping aspect ratio (say 500x500) Create new images from what I have, giving random noise, rotations, adding objects in the scences etc.. Slice the images into 400 sections (25x25) or for more accuracy go even smaller When I want to detect outline I would run the images through my classifier and save the outer-most detected pixels locations and I could overlay my lines on the image. Would this work? Also how would I go about labeling data automatically so I don't have to go through hundreds of thousands of images? Do you believe the resulting NN could be run by a common cellphone? (only for classifying). This is a side project to learn from so any relevant in…
score: 1
tagged with: image-processing
tagged with: neural-network
downvote count: 0
tagged with: keras
favorite count: 0
linked to: http://stackoverflow.com/q/35555375
tagged with: python
answer count: 0
type: UnansweredQuestion
upvote count: 1
tagged with: tensorflow
type: Question

web-scraping
tags question: http://stackoverflow.com/q/52091496
tags question: http://stackoverflow.com/q/52075592
tags question: http://stackoverflow.com/q/52058628
tags question: http://stackoverflow.com/q/52080846
tags question: http://stackoverflow.com/q/52057038
tags question: http://stackoverflow.com/q/52080024
tags question: http://stackoverflow.com/q/52097680
tags question: http://stackoverflow.com/q/52112142
tags question: http://stackoverflow.com/q/51964400
tags question: http://stackoverflow.com/q/52030536
tags question: http://stackoverflow.com/q/52068414
tags question: http://stackoverflow.com/q/51965133
tags question: http://stackoverflow.com/q/52074680
tags question: http://stackoverflow.com/q/52028721
tags question: http://stackoverflow.com/q/52042298
tags question: http://stackoverflow.com/q/51962229
tags question: http://stackoverflow.com/q/52045596
tags question: http://stackoverflow.com/q/52074916
tags question: http://stackoverflow.com/q/51992879
tags question: http://stackoverflow.com/q/52098260
tags question: http://stackoverflow.com/q/52066389
tags question: http://stackoverflow.com/q/52055518
tags question: http://stackoverflow.com/q/52068920
tags question: http://stackoverflow.com/q/52039637
tags question: http://stackoverflow.com/q/52104632
tags question: http://stackoverflow.com/q/52023979
tags question: http://stackoverflow.com/q/52077888
tags question: http://stackoverflow.com/q/52045083
tags question: http://stackoverflow.com/q/52102468
tags question: http://stackoverflow.com/q/52015361
tags question: http://stackoverflow.com/q/52056897
tags question: http://stackoverflow.com/q/51984646
tags question: http://stackoverflow.com/q/52109321
tags question: http://stackoverflow.com/q/52107161
tags question: http://stackoverflow.com/q/52082312
tags question: http://stackoverflow.com/q/52066734
tags question: http://stackoverflow.com/q/52027493
tags question: http://stackoverflow.com/q/52002758
tags question: http://stackoverflow.com/q/52069158
tags question: http://stackoverflow.com/q/51978428
tags question: http://stackoverflow.com/q/52049257
tags question: http://stackoverflow.com/q/51992140
tags question: http://stackoverflow.com/q/51965259
tags question: http://stackoverflow.com/q/52033155
tags question: http://stackoverflow.com/q/51976294
tags question: http://stackoverflow.com/q/52097577
tags question: http://stackoverflow.com/q/52031397
tags question: http://stackoverflow.com/q/52020484
tag name: web-scraping
tags question: http://stackoverflow.com/q/52105663
tags question: http://stackoverflow.com/q/51988363
tags question: http://stackoverflow.com/q/52103834
tags question: http://stackoverflow.com/q/52091111
tags question: http://stackoverflow.com/q/52066560
tags question: http://stackoverflow.com/q/52018333
tags question: http://stackoverflow.com/q/52082207
tags question: http://stackoverflow.com/q/52002135
tags question: http://stackoverflow.com/q/51991170
tags question: http://stackoverflow.com/q/52063354
type: Tag
tags question: http://stackoverflow.com/q/51973860
tags question: http://stackoverflow.com/q/51982930
tags question: http://stackoverflow.com/q/51960036
tags question: http://stackoverflow.com/q/52025186
tags question: http://stackoverflow.com/q/51984774
tags question: http://stackoverflow.com/q/52048112
tags question: http://stackoverflow.com/q/52054605
tags question: http://stackoverflow.com/q/52059893
tags question: http://stackoverflow.com/q/52065009
tags question: http://stackoverflow.com/q/52035719
tags question: http://stackoverflow.com/q/51965561
tags question: http://stackoverflow.com/q/52102257
tags question: http://stackoverflow.com/q/52079496
tags question: http://stackoverflow.com/q/52079733
tags question: http://stackoverflow.com/q/52010016
tags question: http://stackoverflow.com/q/52065496
tags question: http://stackoverflow.com/q/52005894
tags question: http://stackoverflow.com/q/52004145
tags question: http://stackoverflow.com/q/52110829

http://stackoverflow.com/q/52109913
tagged with: flask
favorite count: 0
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/52113254
tagged with: python
tagged with: pyodbc
has body: I create a Python Flask API,but when I tried to build a docker image,It builds successfully,then when I tried to run the docker image,It also runs fine.But then,when I wanted to test the API,but hitting the API,It gives error,such as this.. ' conn = pyodbc.connect(r'DRIVER={ODBC Driver 13 for SQL Server};' pyodbc.Error: ('01000', "[01000] [unixODBC][Driver Manager]Can't open lib 'ODBC Driver 13 for SQL Server' : file not found (0) (SQLDriverConnect)") ' for your information,the dockerfile of mine is: FROM python:3.6 COPY . /app WORKDIR /app/ RUN bash odbc.sh RUN python3 -m pip install -r requirements.txt EXPOSE 6000 ENTRYPOINT [ "python" ] CMD [ "dup_invoice_new.py" ] and the odbc.sh file is- curl https://packages.microsoft.com/keys/microsoft.asc | apt-key add - curl https://packages.microsoft.com/config/ubuntu/16.04/prod.list | tee /etc/apt/sources.list.d/mssql-tools.list apt-get -y install unixodbc-dev unixodbc apt-get -y update ACCEPT_EULA=Y apt-get -y install mssql-tools apt-get -y install unixodbc-dev unixodbc echo 'export PATH="$PATH:/opt/mssql-tools/bin"' &gt;&gt; ~/.bash_profile echo 'export PATH="$PATH:/opt/mssql-tools/bin"' &gt;&gt; ~/.bashrc source ~/.bashrc The app is running in a server.Please let me know how can I remove this error and dockerize my app successfully. for further info,dbconnection is done by the dbconn function- def dbconnection(supp_inv_date): logging.basicConfig(level=logging.INFO, format='%(asctime)s %(levelname)s %(message)s', filename='myapp.log', filemode='w') # logging.info('Input request is : %s',js) conn = pyodbc.connect(r'DRIVER={ODBC Driver 13 for SQL Server};' r'SERVER=&lt;&gt;.database.windows.net;' r'DATABASE=&lt;&gt;;' r'UID=&lt;&gt;;' r'PWD=&lt;&gt;;') query = "" return conn,query and this is my flask api structure- @app.route('/', methods=['GET', 'POST']) def main(): js = request.json res = {&lt;&gt;} response = {'dupes': res} return json.dumps(response) if __name__ == "__main__": app.run(host='localhost', port='6000', d…
upvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/91174822
tagged with: odbc
has title: Giving pyodbc.Error while Dockerizing a Python API/Flask APP
tagged with: docker
answer count: 1
has comment: http://stackoverflow.com/comment/91175138
downvote count: 0
score: 1

http://stackoverflow.com/comment/90943770
comment on: http://stackoverflow.com/q/51996989
has text: `ex_data[ex_data[:,0] == 0]` is advanced indexing, so makes a copy. It is not a view.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/90866192
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51957721
has text: Okay, I got it working with this: r"^(?=.*[\d])(?=.*[A-Z])(?=.*[a-z])" Still a little confused as to why the ^ is used, since I get the idea that it insists the password begin with a number?
score: 0

http://stackoverflow.com/comment/90924810
comment on: http://stackoverflow.com/q/51987657
type: Comment
type: QuestionComment
score: 2
has text: The u simply indicates that it is unicode

rest
tags question: http://stackoverflow.com/q/51976479
tags question: http://stackoverflow.com/q/52053044
tags question: http://stackoverflow.com/q/51959587
tags question: http://stackoverflow.com/q/52042689
tags question: http://stackoverflow.com/q/51991365
tags question: http://stackoverflow.com/q/51994665
tags question: http://stackoverflow.com/q/52112331
tags question: http://stackoverflow.com/q/51974147
tags question: http://stackoverflow.com/q/51988650
type: Tag
tag name: rest

http://stackoverflow.com/q/52028047
has body: I have this problem, given a set of numbers S and a number N find some combination of numbers S that sum to N such that the solution uses the minimal amount of numbers. ie minimize |Solution| So for example say S = {1000, 500, 250, 100}, and A = 900 then Solution = {500, 100, 100, 100, 100} This was my attempt numbers = [1000, 500, 250, 100] amount = 900 def solve(numbers, amount, sum, solution): for num in numbers: if sum + num &lt;= amount: if sum + num == amount: print(solution + [num]) return solve(numbers, amount, sum + num, solution + [num]) solve(numbers, amount, 0, []) And it works! Sort of, I get the right answer and its always the first value I print (Since I ensure the set of numbers is in decreasing order). But the algorithm goes on to print every other correct answer (correct here meaning in sum not minimizing the |Solution|) [500, 100, 100, 100, 100] [250, 250, 100, 100, 100, 100] [250, 100, 250, 100, 100, 100] [250, 100, 100, 250, 100, 100] [250, 100, 100, 100, 250, 100] [250, 100, 100, 100, 100, 250] and so on How could I exit this algorithm when I find the first answer?
has title: Exiting a tree of recursive calls when a solution is found
tagged with: algorithm
score: 0
has answer: http://stackoverflow.com/a/52028073
accepted answer: http://stackoverflow.com/a/52028073
answer count: 1
tagged with: python
type: AnsweredQuestion
type: Question

http://stackoverflow.com/a/51965797
type: Answer
score: 3
downvote count: 0
has body: You need to use a recursive approach: { ((?:[^{}]|(?R))*) } This is only supported by the newer regex module, see a demo on regex101.com.
has comment: http://stackoverflow.com/comment/90882000
upvote count: 3
has comment: http://stackoverflow.com/comment/90881989
answers question: http://stackoverflow.com/q/51965650

http://stackoverflow.com/q/52060860
accepted answer: http://stackoverflow.com/a/52076636
answer count: 1
has comment: http://stackoverflow.com/comment/91072107
has title: Detect, from a frame, which class a method is associated with
favorite count: 0
tagged with: python
has comment: http://stackoverflow.com/comment/91072612
has body: I'm writing an incredibly hackish piece of not-quite-production code in Python, and I need some way of detecting whether a _XYZ__foo attribute access was called from a method defined on a class called /_*XYZ/. It's not quite as easy as that, though, since I need to detect the original method access in case anything has overridden __getattribute__ and called super(). I'm bad at explaining, so... the rules are similar to Java's private, except I want to prevent cheating. (Yes, I know that this is counter to the Python philosophy; bear with me here.) My current plan of attack is: Use re.compile('_(?P&lt;class&gt;.*?)__(?P&lt;name&gt;.*)') to detect the name of the class (with preceding _s stripped). Climb the super chain with sys._getframe(n) to find out where the attribute access was. Detect what class it was on... somehow. I'm stuck here. I might be able to do this by emulating super's walking of the MRO, but I'd much rather rely on detection because checking what's been called by super and what's been called by user functions is hard. So, to my actual question. Given a frame, how can I detect which class a method is associated with? If I had access to the function object I could do f.__qualname__[:-1-len(f.__name__)], but I don't (or, at least, I don't think I do). As is, I have no idea how to do this! Here's a simple example that demonstrates what I want to do: import sys import re import itertools import builtins from builtins import __build_class__ def build_class(func, name, *bases, metaclass=None, **kwds): if bases[-1] is object: bases = bases[:-1] bases += HackishClass, object if metaclass is None: return __build_class__(func, name, *bases, **kwds) return __build_class__(func, name, *bases, metaclass=metaclass, **kwds) private_regex = re.compile('_(?P&lt;class&gt;.*?)__(?P&lt;name&gt;.*)') class HackishClass: __slots__ = () def __getattribute__(self, key): match = private_regex.match(key) if match is not None: for depth in itertools.count(1): frame = sys._getf…
has comment: http://stackoverflow.com/comment/91072073
type: AnsweredQuestion
tagged with: super
upvote count: 2
score: 1
tagged with: sys
has answer: http://stackoverflow.com/a/52076636
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/91072625
tagged with: internal
has comment: http://stackoverflow.com/comment/91101868
has comment: http://stackoverflow.com/comment/91072511
has comment: http://stackoverflow.com/comment/91101875
tagged with: python-3.7

mfcc
type: Tag
tags question: http://stackoverflow.com/q/52112204
tag name: mfcc

http://stackoverflow.com/a/52033025
downvote count: 0
score: 1
has body: Try the follwoing: df = ... # The dataframe N = 5 # The value to test df_b = df.filter(df['A'] &gt;= N).select('B') This will first filter the dataframe only containing rows where A is >= N with its corresponding 'B' values. After applying the filter select only column B to obtain the final result.
has comment: http://stackoverflow.com/comment/91016824
has comment: http://stackoverflow.com/comment/91017281
upvote count: 1
has comment: http://stackoverflow.com/comment/91016981
has comment: http://stackoverflow.com/comment/91061196
answers question: http://stackoverflow.com/q/52032966
has comment: http://stackoverflow.com/comment/91017434
type: Answer

http://stackoverflow.com/q/52018664
tagged with: list
accepted answer: http://stackoverflow.com/a/52018723
upvote count: 3
answer count: 3
linked to: http://stackoverflow.com/q/19798153
possible better answer: http://stackoverflow.com/a/52018738
has answer: http://stackoverflow.com/a/52018738
has comment: http://stackoverflow.com/comment/90988590
tagged with: pandas
type: AnsweredQuestion
has title: What is the best way to convert a string in a pandas dataframe to a list?
downvote count: 0
has answer: http://stackoverflow.com/a/52018723
tagged with: string
has answer: http://stackoverflow.com/a/52018803
has body: Basically I have a dataframe with lists that have been read in as strings and I would like to convert them back to lists. Below shows what I am currently doing but I m still learning and feel like there must be a better (more efficient/Pythonic) way to go about this. Any help/constructive criticism would be much appreciated! import pandas as pd import ast df = pd.DataFrame(data=['[-1,0]', '[1]', '[1,2]'], columns = ['example']) type(df['example'][0]) &gt;&gt; str n = df.shape[0] temp = [] temp2 = [] for i in range(n): temp = (ast.literal_eval(df['example'][i])) temp2.append(temp) df['new_col_lists'] = temp2 type(df['new_col_lists'][0]) &gt;&gt; list
favorite count: 0
type: Question
score: 3
has comment: http://stackoverflow.com/comment/90987574
tagged with: python

http://stackoverflow.com/comment/103660835
type: Comment
type: QuestionComment
has text: Check out [dask](https://examples.dask.org/array.html) package. It supports Numpy arrays and multi-core execution.
comment on: http://stackoverflow.com/q/52010861
score: 0

http://stackoverflow.com/comment/91003563
score: 0
type: QuestionComment
type: Comment
has text: Why is it `(-4)` for the 3rd a and not `(-5)`? Should the previous position be referenced and not the first?
comment on: http://stackoverflow.com/q/52026592

http://stackoverflow.com/comment/104714100
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52013300
has text: It did not solve for me. I dont know why is this a accepted answer
type: AnswerComment

http://stackoverflow.com/comment/91109704
has text: Please refer to updated post for solution to display both strings, "*How to Operate: Some text here*" and "*Some title Some more text*" as one i.e. using only one Label widget.
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52058923

http://stackoverflow.com/q/51966858
tagged with: python
has answer: http://stackoverflow.com/a/51967088
has body: I have a list: L = [1,2,3,4,5,6,7,8] I want to iterate consecutive elements in the list such that, when it comes to last element i'e 8 it pairs with the first element 1. The final output I want is: [1,2],[2,3],[3,4],[4,5],[5,6],[6,7],[7,8],[8,1] I tried using this way: for first,second in zip(L, L[1:]): print([first,second]) But I am getting only this result: [1,2],[2,3],[3,4],[4,5],[5,6],[6,7],[7,8] How do I make a pair of last element with first? I have heard about the negative indexing property of a list.
accepted answer: http://stackoverflow.com/a/51966912
has title: Iterate consecutive elements in a list in Python such that the last element combines with first
has answer: http://stackoverflow.com/a/51969557
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51967279
score: 10
upvote count: 10
has answer: http://stackoverflow.com/a/51967185
possible better answer: http://stackoverflow.com/a/51966974
has answer: http://stackoverflow.com/a/51966992
type: Question
has answer: http://stackoverflow.com/a/51966982
has answer: http://stackoverflow.com/a/51966974
has answer: http://stackoverflow.com/a/51966912
downvote count: 0
has answer: http://stackoverflow.com/a/51966910
favorite count: 0
answer count: 9

http://stackoverflow.com/a/57242476
answers question: http://stackoverflow.com/q/52096473
has comment: http://stackoverflow.com/comment/101308652
type: Answer
has comment: http://stackoverflow.com/comment/101094417
downvote count: 0
score: 5
has comment: http://stackoverflow.com/comment/115112024
has comment: http://stackoverflow.com/comment/117931223
has body: The new best answer is to use the bulk_update() method found here: with database.atomic(): User.bulk_update(user_list, fields=['username'], batch_size=50)
upvote count: 5

http://stackoverflow.com/comment/91074265
type: AnswerComment
has text: i dont see the file ...dont know either its being created and if yes then where is that ?
type: Comment
comment on: http://stackoverflow.com/a/52061308
score: 0

http://stackoverflow.com/q/52034426
linked to: http://stackoverflow.com/q/50622525
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/111596212
type: UnansweredQuestion
has title: What versions of python, anaconda and tensorflow work best to gether on windows 8.1?
has comment: http://stackoverflow.com/comment/91020639
tagged with: python
has body: taking different machine learning courses. i tried to install tensorflow after deleting my old anaconda/python (which took a while) and downloading 3.7, but then ran into version problems like this. downloading anaconda3 5.20 now. so is there a preferred combination of recent python, anaconda, and tensorflow versions that play well together on windows 8.1. edit: looks like anaconda can deal with different versions of python. edit2: trying: conda create -n tensorflow pip python=3.5 activate tensorflow pip install --ignore-installed --upgrade tensorflow gets tensorflow installed and working but issues a warning: You are using pip version 10.0.1, however version 18.0 is available. You should consider upgrading via the 'python -m pip install --upgrade pip' command. (tensorflow) C:\Users\ray&gt;python -m pip install --upgrade pip Collecting pip Using cached https://files.pythonhosted.org/packages/5f/25/e52d3f31441505a5f3a f41213346e5b6c221c9e086a166f3703d2ddaf940/pip-18.0-py2.py3-none-any.whl tensorflow 1.10.0 has requirement setuptools&lt;=39.1.0, but you'll have setuptools 40.0.0 which is incompatible. Installing collected packages: pip Found existing installation: pip 10.0.1 Uninstalling pip-10.0.1: Successfully uninstalled pip-10.0.1 Successfully installed pip-18.0 so now i have a red warning.
answer count: 0
score: 1
linked to: http://stackoverflow.com/q/15221473
upvote count: 1
tagged with: tensorflow
type: Question
tagged with: anaconda
has comment: http://stackoverflow.com/comment/91020771
has comment: http://stackoverflow.com/comment/111583947

http://stackoverflow.com/q/52084665
favorite count: 0
has title: Unable to import storage from google.cloud
has answer: http://stackoverflow.com/a/56928462
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/91120092
has comment: http://stackoverflow.com/comment/91125208
type: Question
score: 5
has answer: http://stackoverflow.com/a/52106795
tagged with: google-cloud-datalab
upvote count: 5
answer count: 3
has body: I'm new to Google Cloud Platform, and have uploaded some machine learning code on Jupyter notebook in DataLab. My issue is although, I installed Google Cloud Storage (using the command: pip install --upgrade google-cloud-storage), I'm unable to import this. The following is how I'm importing this package: &gt;&gt;import numpy &gt;&gt;import pandas as pd &gt;&gt;from google.cloud import storage But I'm getting the following error: ImportErrorTraceback (most recent call last) in () ----> 1 from google.cloud import storage ImportError: cannot import name storage Note: This is the content of my JSON config file: {"TokenSources":["env"]} I tried export GOOGLE_APPLICATION_CREDENTIALS="/path/to/file.json", but the error persists. I verified that this package is indeed installed in my environment by typing pip freeze in the command shell: google-cloud==0.34.0 google-cloud-datastore==1.7.0 google-cloud-spanner==1.4.0 google-cloud-storage==1.10.0 What am I missing here?
tagged with: google-cloud-platform
downvote count: 0
has answer: http://stackoverflow.com/a/52085208
tagged with: jupyter-notebook

http://stackoverflow.com/q/52019050
upvote count: 1
has comment: http://stackoverflow.com/comment/90988824
has comment: http://stackoverflow.com/comment/90988795
has comment: http://stackoverflow.com/comment/90988505
has comment: http://stackoverflow.com/comment/90988803
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/90988676
has comment: http://stackoverflow.com/comment/90988553
has comment: http://stackoverflow.com/comment/90988665
type: UnansweredQuestion
tagged with: python
tagged with: kivy
has comment: http://stackoverflow.com/comment/90988461
has comment: http://stackoverflow.com/comment/90988649
downvote count: 0
answer count: 0
has comment: http://stackoverflow.com/comment/90988340
score: 1
has comment: http://stackoverflow.com/comment/90988472
has comment: http://stackoverflow.com/comment/90988630
type: Question
has title: What affect does inheriting from Kivy Widget class have on the child?
has body: First, a heads up - I am not too familiar with OOP concepts, so this may just be some form of python functionality that I am not aware of. In Kivy we can modify the behaviour and appearance of widgets by creating classes child to the widgets whose functions we want to alter, for instance: class MyWidget(Button): def __init__(self, **kwargs): super(MyWidget, self).__init__(**kwargs) self.size_hint = None self.size = 200, 100 Then use MyWidget: or &lt;MyWidget&gt; to instantiate the widget in kv. This is good if I wish for my widgets to be parent to the root widget, but there are times when this is not wanted for instance when requiring a temporary Popup. In which case I would just create a typical class which is instantiated when an event is triggered. Like so: class Interface(): def __init__(self): btn = Button() btn.bind(on_press=self.some_callback) self.popup = Popup(content=btn) self.popup.open() def some_callback(self, instance): print('woo') And this, to all appearances, looks fine, but the widget events (on_press here) don't trigger callback functions??? The bind() function will call the callback on the event, since I will be notified if the callback function definition has incorrect syntax, but for some reason the contents of the callback are not executed - only when Interface() inherits from the Widget() class (Interface(Widget): ...). From the docs: Widget interaction is built on top of events that occur. If a property changes, the widget can respond to the change in the ‘on_’ callback. If nothing changes, nothing will be done. btn is the widget, it is instance of Button() which itself is a child of Widget, its method has no connection at all to what may be the parent class of Interface so why then is the callback only fully executed when Widget is the parent class of Interface? What am I missing?

http://stackoverflow.com/a/56257106
score: 0
type: Answer
has body: Updated solution as of 2019: This is an error that happens if you have cufflinks version 0.13 or older which was not compatible with plotly 3.0. This may happen because you installed from conda or another source and not with pip. To solve it, run: pip install cufflinks --upgrade
answers question: http://stackoverflow.com/q/51998661

http://stackoverflow.com/a/51969683
score: 6
answers question: http://stackoverflow.com/q/51969634
has body: Just append the filtered data frame df3 = df2.loc[~df2.Code.isin(df.Code)] df.append(df3) Code Title 0 103 general checks 1 107 limits 2 421 horseshoe 3 319 scheduled 4 501 zonal 1 108 lucky eight 4 503 new item Notice that you might end up with duplicated indexes, which may cause problems. To avoid that, you can .reset_index(drop=True) to get a fresh df with no duplicated indexes. df.append(df3).reset_index(drop=True) Code Title 0 103 general checks 1 107 limits 2 421 horseshoe 3 319 scheduled 4 501 zonal 5 108 lucky eight 6 503 new item
downvote count: 0
type: Answer
upvote count: 6

http://stackoverflow.com/comment/91140925
has text: Added your separators.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52095313
type: AnswerComment

http://stackoverflow.com/comment/91125656
type: Comment
score: 1
has text: I used group(0) just because it was unclear if the OP wanted to read that value into a dict or what. It identifies which value was captured.
type: AnswerComment
comment on: http://stackoverflow.com/a/52085432

http://stackoverflow.com/q/51997542
has title: Python tkinter : Add a vertical and horizontal scrollbar in the listbox
has comment: http://stackoverflow.com/comment/90957182
type: Question
has comment: http://stackoverflow.com/comment/90944487
tagged with: python-2.7
score: 0
has comment: http://stackoverflow.com/comment/90944536
upvote count: 1
has comment: http://stackoverflow.com/comment/90944470
tagged with: python
favorite count: 0
tagged with: python-3.x
tagged with: tkinter
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90944704
has comment: http://stackoverflow.com/comment/90944452
downvote count: 1
has body: I have this render_gui function in Python. def render_gui(): global root global prev_key global listbox, label1, entry1 prev_key = 0 root = tk.Tk() root.title('Server Chat Application') scroll = Scrollbar(root) scroll.pack(side = "right" , fill= "y") listbox = Listbox(root, width=80, height=30) listbox.grid(row=1,column=1, columnspan=5,rowspan=3) scroll.config(command = listbox.yview) label1 = ttk.Label(root, text='Message Entry Box : ') label1.grid(row=4,column=1) entry1 = ttk.Entry(root, width=60) entry1.grid(row=4, column=2) root.geometry('490x520') #print('before main loop') root.bind('&lt;KeyPress&gt;', onKeyPress) #print('after main loop') root.mainloop() It was throwing an error after I added the scrollbar thing. How will I encorporate a vertical and horizontal scrollbar in my listbox. Thanks. UPDATE: Below is the complete code. I have edited it and omit the pack thing replace it with grid function but the scrollbar wasn't showing. How am I gonna deal with this? import os import signal import socket import time import threading import keyboard from threading import Thread import tkinter as tk from tkinter import ttk from tkinter import * import webbrowser def onKeyPress(event): global prev_key global root global listbox, label1, entry1 if(event.keycode == 13): print(Entry.get(entry1)) msg = Entry.get(entry1) if len(str.encode(msg)) &gt; 0: client.send(str.encode("\nserver &gt; " + msg)) listbox.insert(END, "server &gt; " + msg) entry1.delete(0,END) if(event.keycode == 88) and (prev_key == 17): root.destroy() try: raise client.send(str.encode("***Server has been shutdowned***")) except: print ("You are not yet connected to any client to send shutdown notice.") sys.exit() os.kill(os.getpid(), signal.SIGUSR1) prev_key = event.keycode def render_gui(): global root global prev_key global listbox, label1, entry1 prev_key = 0 root = tk.Tk() root.title('Server Chat Application') scroll = Scrollbar(root) #scroll.pack(side = "right" , fill= "y") scroll.grid(row=0, colu…

http://stackoverflow.com/comment/91158388
score: 0
type: Comment
has text: If you mean does it exist on Windows, sorry, I have no idea.
comment on: http://stackoverflow.com/a/52103555
type: AnswerComment

http://stackoverflow.com/comment/90880020
comment on: http://stackoverflow.com/a/51964919
type: Comment
score: 0
type: AnswerComment
has text: Take a time to read [PEP 3104](https://www.python.org/dev/peps/pep-3104/) that will help you understand why your code does not works.

http://stackoverflow.com/comment/91080093
type: Comment
comment on: http://stackoverflow.com/a/52011147
score: 0
type: AnswerComment
has text: @GilbertoRoblesSilva Don’t try to deal with the JSON directly; just create a new `User.from_json(j)` and use it the same way you would any other `User` instance.

http://stackoverflow.com/a/51969667
type: Answer
upvote count: 11
has body: Yes, the images will still match the corresponding labels so you can safely set shuffle to True. Under the hood it works as follows. Calling .flow() on the ImageDataGenerator will return you a NumpyArrayIterator object, which implements the following logic for shuffling the indices: def _set_index_array(self): self.index_array = np.arange(self.n) if self.shuffle: # if shuffle==True, shuffle the indices self.index_array = np.random.permutation(self.n) self.index_array is then used to yield both the images (x) and the labels (y) (code truncated for readability): def _get_batches_of_transformed_samples(self, index_array): batch_x = np.zeros(tuple([len(index_array)] + list(self.x.shape)[1:]), dtype=self.dtype) # use index_array to get the x's for i, j in enumerate(index_array): x = self.x[j] ... # data augmentation is done here batch_x[i] = x ... # use the same index_array to fetch the labels output += (self.y[index_array],) return output Check out the source code yourself, it might be easier to understand than you think. Shuffling the validation data shouldn't matter too much. The main point of shuffling is to introduce some extra stochasticity in the training process.
accepted answer of: http://stackoverflow.com/q/51969472
score: 11
answers question: http://stackoverflow.com/q/51969472
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/52054705
has body: These are my scripts - models.py from django.db import models class Leave(models.Model): ... from_date = models.DateField() to_date = models.DateField() def __str__(self): return self.name I wanted to have datepickers for the above DateField(s). This is my form template:- {% extends "base.html" %} {% block content %} Fill out the form please! {% csrf_token %} {{ form.as_p }} Submit {% endblock %} So far, what i have done - I have included this in my base.html. In my forms.py as I'm using ModelForms, I have included this code - class LeaveRequestForm(ModelForm): class Meta: fields = ("from_date", "to_date") model = Leave widgets = { 'from_date' : DateInput(attrs={'class': 'datepicker'}), 'to_date' : DateInput(attrs={'class': 'datepicker'}), } But no datepicker is being reflected in my html template. I have read many other question related to this but couldn't understand. Hope, anyone explains me in detail. base.html ... ... ...
tagged with: django-templates
type: Question
tagged with: datepicker
tagged with: django
tagged with: python
answer count: 1
has answer: http://stackoverflow.com/a/52057426
accepted answer: http://stackoverflow.com/a/52057426
score: 0
has title: How to add a datepicker into Django ModelFrom?
has comment: http://stackoverflow.com/comment/91062225
has comment: http://stackoverflow.com/comment/91062083
type: AnsweredQuestion

http://stackoverflow.com/comment/91091391
comment on: http://stackoverflow.com/a/52070859
type: AnswerComment
score: 0
type: Comment
has text: It didn't fix my problem, but thank you for the help nonetheless!

http://stackoverflow.com/q/52100228
tagged with: python
has body: def open_csv(): import csv with open('//Users//samuel//Desktop//L8 More File Processing (1)//students.csv', 'r') as f: reader = csv.reader(f) for row in reader: print(row) print(open_csv()[1]) This is the output for open_csv(): ['Name', 'Gender', 'Test 1', 'Test 2', 'Test 3', 'Test 4', 'Test 5', 'Test 6'] ['Aisha', 'F', '0', '33', '67', '27', '12', '14'] ['Alex', 'M', '12', '90', '34', '56', '93', '39'] ['Bala', 'M', '13', '25', '58', '17', '49', '29'] ['Denise', 'F', '13', '93', '84', '53', '65', '62'] ['Farhan', 'M', '15', '5', '10', '62', '34', '11'] ['Gopi', 'M', '21', '61', '39', '32', '91', '32'] ['Irfan', 'M', '26', '36', '3', '95', '36', '39'] ['Jun Ming', 'M', '29', '86', '77', '6', '91', '61'] ['Lily', 'F', '30', '34', '46', '96', '100', '44'] ['Mei Ling', 'F', '39', '58', '9', '61', '32', '46'] ['Muthu', 'M', '39', '60', '13', '69', '55', '100'] ['Nurul', 'F', '50', '35', '4', '27', '11', '97'] ['Priya', 'F', '50', '25', '47', '15', '35', '86'] ['Siti', 'F', '58', '71', '13', '19', '58', '30'] ['Elisa', 'F', '59', '22', '73', '52', '77', '49'] ['Dennis', 'M', '65', '94', '83', '67', '37', '22'] ['Harry', 'M', '74', '75', '76', '82', '57', '1'] ['Gary', 'M', '90', '12', '70', '86', '50', '59'] ['Terry', 'M', '93', '84', '26', '99', '90', '72'] ['Corinne', 'F', '100', '17', '88', '14', '33', '9'] When I run this code, I get TypeError:"NoneType" object is not subscriptable. Why is this so and how do I fix it?
has comment: http://stackoverflow.com/comment/91151204
upvote count: 3
type: UnansweredQuestion
downvote count: 2
has answer: http://stackoverflow.com/a/52100574
score: 1
type: Question
has answer: http://stackoverflow.com/a/52100356
answer count: 2
favorite count: 0
has title: How do I avoid this error for this piece of code-TypeError: 'NoneType' object is not subscriptable

http://stackoverflow.com/q/52101431
tagged with: python
has comment: http://stackoverflow.com/comment/91154397
tagged with: selenium-webdriver
has answer: http://stackoverflow.com/a/52101841
possible better answer: http://stackoverflow.com/a/52102338
score: 0
has answer: http://stackoverflow.com/a/52102338
tagged with: selenium
has title: clicking on a button i cant find with selenium in python
has comment: http://stackoverflow.com/comment/91153965
has comment: http://stackoverflow.com/comment/91154036
has comment: http://stackoverflow.com/comment/91154233
accepted answer: http://stackoverflow.com/a/52101841
has comment: http://stackoverflow.com/comment/91154026
has comment: http://stackoverflow.com/comment/91153966
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91153895
has comment: http://stackoverflow.com/comment/91153786
has comment: http://stackoverflow.com/comment/91154203
has comment: http://stackoverflow.com/comment/91154776
linked to: http://stackoverflow.com/q/37771604
has comment: http://stackoverflow.com/comment/91154337
has comment: http://stackoverflow.com/comment/91153647
has body: I have this html element: &lt;button class="expedition_button awesome-button " onclick="attack(null, '6', 2, 0, '')"&gt;&lt;div&gt;&lt;/div&gt;&lt;div&gt;&lt;/div&gt;&lt;/button&gt; and I cant click on it for some reason with my code... just gives me an error about not finding the element by class... Is there a way sending the function of the button "onclick" the information the button hold? i.e sending the function of this button the information - "attack(null, '6', 2, 0, '')" or finding the button using this information Tried xpath but I cant seem to find it.. just gives me this: selenium.common.exceptions.NoSuchElementException: Message: Unable to locate element: /html/body/div[2]/div/div[3]/div/div[2]/div[2]/div[2]/div[2]/div[2]/button When I check the xpath I see it changes every time the page opens up..
type: Question
has comment: http://stackoverflow.com/comment/91154086
answer count: 2

http://stackoverflow.com/comment/90913510
has text: Thanks yes it worked fine for the standalone script, but I am using with diffrent library so i dont have the customer token file json ,module that i am using import google.oauth2.credentials import googleapiclient.discovery kind of stuck with authentication flow
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51975956

http://stackoverflow.com/comment/90926479
score: 0
has text: @Wiltor Stribizew
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51970066

http://stackoverflow.com/tag/xml
tags question: http://stackoverflow.com/q/51991458
tags question: http://stackoverflow.com/q/52000418
tags question: http://stackoverflow.com/q/51973231
tags question: http://stackoverflow.com/q/51966541
type: Tag
tags question: http://stackoverflow.com/q/52059254
tags question: http://stackoverflow.com/q/52009718
tags question: http://stackoverflow.com/q/52047920
tags question: http://stackoverflow.com/q/52087335
tags question: http://stackoverflow.com/q/52055435
tags question: http://stackoverflow.com/q/51975369
tag name: xml
tags question: http://stackoverflow.com/q/52059566
tags question: http://stackoverflow.com/q/51981121
tags question: http://stackoverflow.com/q/52101476
tags question: http://stackoverflow.com/q/52005830
tags question: http://stackoverflow.com/q/52004344
tags question: http://stackoverflow.com/q/52093464
tags question: http://stackoverflow.com/q/52054842

http://stackoverflow.com/q/51991891
type: UnansweredQuestion
tagged with: python
tagged with: python-requests
has comment: http://stackoverflow.com/comment/91012439
has answer: http://stackoverflow.com/a/51993543
tagged with: ssl
type: Question
score: 2
has comment: http://stackoverflow.com/comment/90939065
has comment: http://stackoverflow.com/comment/90965591
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/91026900
has title: python3 and requests: still getting 'sslv3 alert handshake failure'
tagged with: openssl
has comment: http://stackoverflow.com/comment/90934170
linked to: http://stackoverflow.com/q/40741361
has body: I have been trying to perform an HTTPS request in Python 3 using requests and aggregating pretty much all the knowledge from the prior attempts documented on StackOverflow. I cannot for the life of me seem to get out of the sslv3 alert handshake failure rabbit hole. This is my environment: macOS 10.13.6 Python 3.7.0 (installed via Homebrew along with openssl) OpenSSL 1.0.2p 14 Aug 2018 (output of print(ssl.OPENSSL_VERSION)) requests 2.19.1 (output of print(requests.__version__)) installed via pip install requests[security] even cryptography 2.3.1 is installed This is the bare-bone failing code: &gt;&gt;&gt; import requests &gt;&gt;&gt; requests.get('https://iris.nuigalway.ie') And this is the output: Traceback (most recent call last): File "/usr/local/lib/python3.7/site-packages/urllib3-1.23-py3.7.egg/urllib3/contrib/pyopenssl.py", line 444, in wrap_socket cnx.do_handshake() File "/usr/local/lib/python3.7/site-packages/pyOpenSSL-18.0.0-py3.7.egg/OpenSSL/SSL.py", line 1907, in do_handshake self._raise_ssl_error(self._ssl, result) File "/usr/local/lib/python3.7/site-packages/pyOpenSSL-18.0.0-py3.7.egg/OpenSSL/SSL.py", line 1639, in _raise_ssl_error _raise_current_error() File "/usr/local/lib/python3.7/site-packages/pyOpenSSL-18.0.0-py3.7.egg/OpenSSL/_util.py", line 54, in exception_from_error_queue raise exception_type(errors) OpenSSL.SSL.Error: [('SSL routines', 'ssl3_read_bytes', 'sslv3 alert handshake failure')] Needless to say it works with cURL, browsers etc. curl --verbose "https://iris.nuigalway.ie" Here's a handshake snippet of the ouput: * ALPN, offering h2 * ALPN, offering http/1.1 * Cipher selection: ALL:!EXPORT:!EXPORT40:!EXPORT56:!aNULL:!LOW:!RC4:@STRENGTH * successfully set certificate verify locations: * CAfile: /etc/ssl/cert.pem CApath: none * TLSv1.2 (OUT), TLS handshake, Client hello (1): * TLSv1.0 (IN), TLS handshake, Server hello (2): * TLSv1.0 (IN), TLS handshake, Certificate (11): * TLSv1.0 (IN), TLS handshake, Server finished (14): * TLSv1.0 (OU…
favorite count: 0
tagged with: python-3.x
upvote count: 2

http://stackoverflow.com/q/52054719
tagged with: pandas
upvote count: 1
downvote count: 1
has body: I want to do feature engineering using multiple numeric features, the idea is do pair multiplication across dataframe, preferred answer is something that available on machine learning library, such as TensorFlow, Keras, TPOT, H20, etc (I don't know the scientific name of this process), but is fine to do this without library. Here's my simplified dataset No feature_1 feature_2 feature_3 1 10 20 30 2 20 30 40 Here's what I need No feature_1 feature_2 feature_3 feature_1xfeature2 feature_1xfeature_2 feature_2xfeature_3 1 10 20 30 200 300 600 2 20 30 40 600 800 1200 What I did df['feature_1xfeature2'] = df['feature_1'] * df['feature_2'] df['feature_1xfeature3'] = df['feature_1'] * df['feature_3'] df['feature_2xfeature3'] = df['feature_2'] * df['feature_3'] This is prone to mistakes for tons of features. How to do this automatically?
favorite count: 0
has answer: http://stackoverflow.com/a/52054881
tagged with: python
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/65492161
has title: How do I pair multiplication across dataframe efficiently
has answer: http://stackoverflow.com/a/65492161
type: Question
answer count: 2
tagged with: feature-extraction
tagged with: dataframe
accepted answer: http://stackoverflow.com/a/52054881
score: 0

http://stackoverflow.com/a/55525810
downvote count: 0
answers question: http://stackoverflow.com/q/52070514
has body: Pytesseract writes and reads every image you pass it. This is unnecessary when running 35 images. Instead, you should use a python tesseract API interface. This will be significantly faster.
score: 4
type: Answer
upvote count: 4

http://stackoverflow.com/a/52086279
type: Answer
accepted answer of: http://stackoverflow.com/q/52085200
has body: You can use a helper function that: tries to convert what's in your object to a float - so "2.5" and "2" will be able to be translated (as well as anything that Python's float function can interpret as a float value), but "hello there. how are you?" won't... then tries to convert that float to an int then returns its str value If the float conversion fails - then it'll just return your original object as technically only the float conversation can fail, as if that succeeds you can always int(some_float) and str will always work (failing some weird custom class - that deliberately causes it to fail). eg: def try_to_int(obj): try: return str(int(float(obj))) except (ValueError, TypeError): return obj Then use it with new_df = df.applymap(try_to_int)
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/91327377
score: 2
downvote count: 0
answers question: http://stackoverflow.com/q/52085200
upvote count: 2

http://stackoverflow.com/q/52080028
has comment: http://stackoverflow.com/comment/91113124
type: UnansweredQuestion
tagged with: python
type: Question
has comment: http://stackoverflow.com/comment/91110909
has comment: http://stackoverflow.com/comment/91111408
has body: I have a Question, I have 2 dataset, AdultTest and AdultData. In these Dataset I have many Rows like this: 39, State-gov, 77516, Bachelors, 13, Never-married, Adm-clerical, Not-in-family, White, Female , 2174, 0, 40, United-States, &gt;50K And I want to calculate the probability of that a "Female" have ">50K", for that I did this: from sklearn.naive_bayes import BernoulliNB #Read AdultData.csv and encoded in Integer, so can I calculate the NaiveBAyes data1 = np.genfromtxt('AdultData.csv', delimiter=',', dtype='int', skip_footer=1) datatest=np.genfromtxt('adultTest.csv', delimiter=',', dtype='int', skip_footer=1) #Delete the last Column, because the last column is the Target data_new = np.delete(data1, 14, 1) dataTest_new = np.delete(datatest, 14, 1) class_ = [row[14] for row in data2] clf = BernoulliNB() clf.fit(data_new, class_) print(clf.predict_proba(dataTest_new)) And the result is the prediction of the probability, and I get always: [1. 0.] but I dont know why, even if I put the AdultTest(these have another Data) , I receive the same results. Why I dont receive another results? Besides, why I have 2 Columns? P.S. I do it because I want to do the massaging algorithmus for Classifying without Discriminating Somebody could me help? Thanks!
tagged with: naivebayes
has comment: http://stackoverflow.com/comment/91111001
has comment: http://stackoverflow.com/comment/91111444
has comment: http://stackoverflow.com/comment/91110868
has title: Naive Bayes Probability Error Python
has comment: http://stackoverflow.com/comment/91112864
score: 0
answer count: 1
has answer: http://stackoverflow.com/a/52080699
tagged with: scikit-learn

http://stackoverflow.com/q/51985401
has comment: http://stackoverflow.com/comment/90920220
favorite count: 0
tagged with: twilio
has comment: http://stackoverflow.com/comment/90920274
upvote count: 2
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90920217
tagged with: python
tagged with: module
has answer: http://stackoverflow.com/a/51985483
score: 2
tagged with: installation
type: Question
has answer: http://stackoverflow.com/a/53578904
answer count: 2
has body: how to install twilio via pip? I tried to install twilio python module but i can't install it i get following error no Module named twilio When trying to install twilio pip install twilio I get the following error. pyopenssl 18.0.0 has requirement six&gt;=1.5.2, but you'll have six 1.4.1 which is incompatible. Cannot uninstall 'pyOpenSSL'. It is a distutils installed project and thus we cannot accurately determine which files belong to it which would lead to only a partial uninstall. i got the answer and installed pip install --ignore-installed twilio but i get following error Could not install packages due to an EnvironmentError: [Errno 13] Permission denied: '/Library/Python/2.7/site-packages/pytz-2018.5.dist-info' Consider using the `--user` option or check the permissions. i have anaconda installed is this a problem?
has title: How to install twilio via pip
downvote count: 0

http://stackoverflow.com/comment/90911420
has text: Could you add a sample of the data? and the full error message to see exactly where it's occurring...
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51978308

http://stackoverflow.com/comment/90900455
has text: Thank you. I appreciate all of the feedback on this. Your response was the closest to what I was trying to do and I also appreciate that you added information regarding my question about the range() function.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51974652
type: Comment

http://stackoverflow.com/q/52027711
has comment: http://stackoverflow.com/comment/91005765
score: 0
answer count: 2
tagged with: python-3.x
has body: I'm reading json data and converting it into a .csv file in python3. I called the "utf-8" encoding like: csv = open(download_dir, "w", encoding='utf-8') When writing I coded something like this: csv.write(str(message.content_excerpt[:30].encode("utf-8")) + ';') I have two problems: The enconding is outputing on EXCEL with messed chars I want to get rid of blank lines due the original post formating. Example 1 shows the actual cenario, Example 2 shows what I want to get. Example 1 (actual) Example 2 (pretended) Thank you!
has answer: http://stackoverflow.com/a/52028937
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
has answer: http://stackoverflow.com/a/52028078
tagged with: excel
type: Question
has title: From JSON data to CSV encoding

http://stackoverflow.com/q/52046077
score: 0
has comment: http://stackoverflow.com/comment/91065909
has comment: http://stackoverflow.com/comment/91069200
answer count: 1
has comment: http://stackoverflow.com/comment/91063775
tagged with: flask-sqlalchemy
has comment: http://stackoverflow.com/comment/91068998
has comment: http://stackoverflow.com/comment/91044709
linked to: http://stackoverflow.com/q/24060553
accepted answer: http://stackoverflow.com/a/52059988
tagged with: python
has body: I'm building a flask application foo, up until this point this is how files are organized foo |-- app | |-- __init__.py | |-- models.py | |-- foo.py in __init__.py I define a function to create the app, which it is then called from foo.py. This is how __init__.py looks like: from flask_sqlalchemy import SQLAlchemy db = SQLAlchemy() def create_app(config_name): app = Flask(__name__) ... db.init_app(app) The module models.py imports db and access an existing database. So far I've been using db.engine.execute(&lt;...&gt;) to make queries, but it seems kind of inefficient. For example, I have a table called var which I constantly access in my app, so I define a class in models.py class Var(object): def query ... but I'd like to use alchemy instead: class Var(db.Model): ... I tried to follow the answers here to build my application, but these are the problems I've found so far If I insert base.metadata.reflect(db.engine) inside the create_app function I get an error saying I need to create a context, which doesn't make a lot of sense, since this is the the place where I'm creating it. Of course, if I do with app.app_context(): base.metadata.reflect(db.engine) I can get around, but then the problem is still there when I create the class Var: class Var(db.Model): table = db.Model.metadata.tables['var'] The dictionary is empty, so I get a KeyError. When I try to create a context inside models to create my class Var it also fails, because it cannot import it. I've tried all the suggestions I've found, but none of them seems to work. Thanks for your help
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/17652937
has title: models module for flask application
has comment: http://stackoverflow.com/comment/91063020
type: Question
has answer: http://stackoverflow.com/a/52059988
tagged with: flask
has comment: http://stackoverflow.com/comment/91069287

http://stackoverflow.com/q/52098464
has answer: http://stackoverflow.com/a/52098503
type: Question
has answer: http://stackoverflow.com/a/52098550
score: 0
answer count: 2
has title: Sort list of list with dates strings python
possible better answer: http://stackoverflow.com/a/52098550
has comment: http://stackoverflow.com/comment/91147359
tagged with: python
accepted answer: http://stackoverflow.com/a/52098503
type: AnsweredQuestion
has body: I'm trying to sort my list of list with a.sort(key=lambda x: x[0]) or a.sort(). The first element of my date is the day and I need to sort by it. a = [['1/8/2018', 71], ['10/8/2018', 76], ['11/8/2018', 6], ['12/8/2018', 60], ['13/8/2018', 81], ['14/8/2018', 74], ['15/8/2018', 7], ['16/8/2018', 77], ['17/8/2018', 81], ['18/8/2018', 69], ['19/8/2018', 66], ['2/8/2018', 81], ['20/8/2018', 74], ['21/8/2018', 88], ['22/8/2018', 92], ['23/8/2018', 90], ['24/8/2018', 84], ['25/8/2018', 66], ['26/8/2018', 64], ['27/8/2018', 82], ['28/8/2018', 82], ['29/8/2018', 79], ['3/8/2018', 8], ['4/8/2018', 64], ['5/8/2018', 64], ['6/8/2018', 12], ['7/8/2018', 8], ['8/8/2018', 83], ['9/8/2018', 77]] the results I need: [['1/8/2018', 71],['2/8/2018', 81], ['3/8/2018', 8], ['4/8/2018', 64], ['5/8/2018', 64], ['6/8/2018', 12],['7/8/2018', 8], ['8/8/2018', 83], ['9/8/2018', 77], ['10/8/2018', 76], ['11/8/2018', 6], ['12/8/2018', 60], ['13/8/2018', 81], ['14/8/2018', 74], ['15/8/2018', 7], ['16/8/2018', 77], ['17/8/2018', 81], ['18/8/2018', 69], ['19/8/2018', 66], ['20/8/2018', 74], ['21/8/2018', 88], ['22/8/2018', 92], ['23/8/2018', 90], ['24/8/2018', 84], ['25/8/2018', 66], ['26/8/2018', 64], ['27/8/2018', 82], ['28/8/2018', 82], ['29/8/2018', 79]]

http://stackoverflow.com/comment/91016643
score: 0
type: AnswerComment
type: Comment
has text: Haha, Unix oneliners sometimes affect people that way. :)
comment on: http://stackoverflow.com/a/52033048

http://stackoverflow.com/q/52004248
accepted answer: http://stackoverflow.com/a/52004305
type: AnsweredQuestion
score: 3
has answer: http://stackoverflow.com/a/52004305
type: Question
tagged with: numpy
answer count: 1
upvote count: 3
favorite count: 0
has title: Numpy - Apply a custom function on all combination of rows in matrix to get a new matrix?
has body: I have the following function, that applies the histogram intersection kernel for 2 arrays: def histogram_intersection_kernel(X, Y): k = np.array([]) for x_i,y_i in zip(X,Y): k = np.append(k,np.minimum(x_i,y_i)) return np.sum(k) now, lets say I have the following matrix "mat": [[1,0,0,2,3], [2,3,4,0,1], [3,3,5,0,1]] I would like to find an efficient way to get the matrix that is the result of applying "histogram_intersection_kernel" to all of the combinations of rows in mat. In this example it would be: [[6,2,2], [6,10,10], [2,10,12]]
downvote count: 0
tagged with: python

http://stackoverflow.com/comment/91114687
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/52079733
score: 0
has text: I'm guessing there isn't a clean way to do this as the values in a visual are not stored in the pbix file. You'd have to recreate the filter context or else scrape the data programmatically.

http://stackoverflow.com/comment/90890931
comment on: http://stackoverflow.com/q/51970145
score: 0
type: Comment
type: QuestionComment
has text: It would be a bit hard as the array it's quite big

http://stackoverflow.com/comment/90964141
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52006912
has text: Because you are using `matplotlib.pyplot.yticks(pos,(names))`, you see the names on the y axis
score: 0

http://stackoverflow.com/a/51970123
has comment: http://stackoverflow.com/comment/90913966
type: Answer
has comment: http://stackoverflow.com/comment/90913134
answers question: http://stackoverflow.com/q/51969420
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/90908150
has comment: http://stackoverflow.com/comment/90912974
has body: Popen can only execute one command or shell script. You can simply provide the whole shell script as single argument using ; to separate the different commands: proc = Popen('set variable=abc;echo %variable%', shell=True) Or you can actually just use a multiline string: &gt;&gt;&gt; from subprocess import call &gt;&gt;&gt; call('''echo 1 ... echo 2 ... ''', shell=True) 1 2 0 The final 0 is the return-code of the process The communicate method is used to write to the stdin of the process. In your case the process immediately ends after running set variable and so the call to communicate doesn't really do anything. You could spawn a shell and then use communicate to write the commands: &gt;&gt;&gt; proc = Popen(['sh'], stdin=PIPE, stdout=PIPE, stderr=PIPE) &gt;&gt;&gt; proc.communicate('echo 1; echo 2\n') ('1\n2\n', '') Note that communicate also closes the streams when it is done, so you cannot call it mulitple times. If you want an interactive session you hvae to write directly to proc.stdin and read from proc.stdout. By the way: you can specify an env parameter to Popen so depending on the circumstances you may want to do this instead: proc = Popen(['echo', '%variable%'], env={'variable': 'abc'}) Obviously this is going to use the echo executable and not shell built-in but it avoids using shell=True.
upvote count: 1
has comment: http://stackoverflow.com/comment/90910450
has comment: http://stackoverflow.com/comment/90914320

http://stackoverflow.com/comment/91020263
comment on: http://stackoverflow.com/q/52035093
score: 0
type: Comment
type: QuestionComment
has text: @MisterMiyagi i would like to do this without using any liberaries which already calculate permuations

http://stackoverflow.com/a/51963255
score: 0
type: Answer
has body: Do you mean that you just want to get the minimal Y for each X? Try this: Imagine your input file is like 100 3 200 3 300 3 400 3 ... The dict will be: d = {} for line in s.split('\n'): parts = line.trim().split() x = int(parts[0]) y = int(parts[1]) d.setdefault(x, []).append(y) result = dict((k, min(v)) for k, v in d.iteritems())
answers question: http://stackoverflow.com/q/51962854

http://stackoverflow.com/q/51995558
has answer: http://stackoverflow.com/a/55346789
answer count: 3
has body: I am trying to use the latest (2nd) 0.3 version of the Prophet package for Python. My model should include an exogenous regressor, but I receive a ValueError stating that the indeed existing regressor is missing from dataframe. Is this a bug or what am I doing wrong? #Random Dataset Preparation import random random.seed(a=1) df = pandas.DataFrame(data = None, columns = ['ds', 'y', 'ex'], index = range(50)) datelist = pandas.date_range(pandas.datetime.today(), periods = 50).tolist() y = numpy.random.normal(0, 1, 50) ex = numpy.random.normal(0, 2, 50) df['ds'] = datelist df['y'] = y df['ex'] = ex #Model prophet_model = Prophet(seasonality_prior_scale = 0.1) Prophet.add_regressor(prophet_model, 'ex') prophet_model.fit(df) prophet_forecast_step = prophet_model.make_future_dataframe(periods=1) #Result-df prophet_x_df = pandas.DataFrame(data=None, columns=['Date_x', 'Res'], index = range(int(len(y)))) #Error prophet_x_df.iloc[0,1] = prophet_model.predict(prophet_forecast_step).iloc[0,0]
favorite count: 0
tagged with: facebook-prophet
type: UnansweredQuestion
tagged with: python
has title: Prophet Python ValueError: Regressor missing from dataframe
score: 3
upvote count: 3
has answer: http://stackoverflow.com/a/78300082
has answer: http://stackoverflow.com/a/54066112
type: Question
downvote count: 0
has comment: http://stackoverflow.com/comment/94241509

http://stackoverflow.com/comment/91182512
comment on: http://stackoverflow.com/a/52112224
score: 0
type: AnswerComment
has text: Hi w-m thanks for your contribution. Yeah that would be similar to my mentioned attempt with the If statements. The problem is that it will always output the other objects. Take for example this file https://imgur.com/a/L1tivfV The problem I am facing is to determine which colors are present, but since the mask simply covers everything and shows only colors defined by the boundaries, it gets tricky. Maybe there is some other methods within OpenCV to do thr trick.
type: Comment

http://stackoverflow.com/q/51993862
has answer: http://stackoverflow.com/a/51993891
has comment: http://stackoverflow.com/comment/90937556
has answer: http://stackoverflow.com/a/51994118
downvote count: 0
favorite count: 0
tagged with: range
tagged with: python
accepted answer: http://stackoverflow.com/a/51993891
answer count: 4
type: AnsweredQuestion
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/90937749
upvote count: 3
has answer: http://stackoverflow.com/a/51994081
possible better answer: http://stackoverflow.com/a/51993973
has title: Counting the items in a range
has answer: http://stackoverflow.com/a/51993973
type: Question
score: 3
linked to: http://stackoverflow.com/q/30081275
has body: p1 = (0, 10, 1) p2 = (0, -20, -2) p3 = (0,10,2) Hi, I have the above code and I'd simply like a quick way to count how many items are in each range without iterating through it? (its part of a few nested loops). So p1 would return 9. Also is there a better way to pass those variables in to the range function? right now i'm suing: range(p1[0], p1[1], p1[2])

gensim
tags question: http://stackoverflow.com/q/51985536
tags question: http://stackoverflow.com/q/52072855
tag name: gensim
tags question: http://stackoverflow.com/q/52012579
tags question: http://stackoverflow.com/q/52038651
tags question: http://stackoverflow.com/q/52080365
type: Tag

http://stackoverflow.com/comment/91089569
has text: @Msquare How about: `print(modules_pmpp_df.groupby(modules_pmpp_df[i].dt.strftime('%B'))[j].max(axis=1))`
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/52069731
score: 0

http://stackoverflow.com/comment/126578777
comment on: http://stackoverflow.com/a/61467635
score: 0
type: AnswerComment
type: Comment
has text: input tensor shape is (m, n_H_prev, n_W_prev, n_C_prev) , he is correct

http://stackoverflow.com/q/51992864
tagged with: postgresql
score: 0
has comment: http://stackoverflow.com/comment/90935404
has comment: http://stackoverflow.com/comment/90936002
has body: I have multiple thousands of csvs that I need to dump into postgres as a table each. But the problem is, these tables are not identical in structure. I'm looking for a way I can create the table on the fly from the structure of the csv and dump the csv into the table created. If I were to do it manually, it would involve 2 steps: 1. Create the table based on the csv data structure 2. Dump the csv data into the created table But since I have thousands of these csvs, it would extremely inefficient to do this manually. I'm looking for a way I could dynamically create a postgres table based on a csv structure and dump data into this table and automate this entire process for thousands of files. Most of the research I did points me to PG commands to dump data into a single existing table, but those solutions won't work here because the number of tables is huge here. Efficient way to import a lot of csv files into PostgreSQL db - This pointed me to a similar problem, but his tables are all identical in structure, unlike mine.
answer count: 0
linked to: http://stackoverflow.com/q/12646305
type: UnansweredQuestion
tagged with: python
has title: Create multiple non-identical postgres tables dynamically from csvs and dump csv data using Python
type: Question

http://stackoverflow.com/q/52106083
has answer: http://stackoverflow.com/a/52318191
upvote count: 1
answer count: 1
downvote count: 0
tagged with: pywin32
tagged with: python
linked to: http://stackoverflow.com/q/44910566
favorite count: 0
tagged with: xlwings
type: UnansweredQuestion
has body: The code snippet came from the official documentation of xlwings here and it is the setup for my question. import xlwings as xw sht = xw.Book().sheets[0] sht.range('A1').value = [['Foo1', 'Foo2'], [1, 2]] chart = sht.charts.add() chart.set_source_data(sht.range('A1').expand()) chart.chart_type = 'line' chart.name Running print(chart.api) outputs the tuple below. (&lt;xlwings._xlwindows.COMRetryObjectWrapper at 0x1fcd60c9a90&gt;, &lt;xlwings._xlwindows.COMRetryObjectWrapper at 0x1fcd60c9f28&gt;) If I want to use the api attribute to do some basic chart manipulation like remove the legend and add a title, it only works if I do it to chart.api[1]. For instance the code below works fine. It removes the chart legend and adds a title. chart.api[1].HasLegend = 0 chart.api[1].SetElement(2) chart.api[1].ChartTitle.Text = 'A title' However, anything I do to chart.api[0] yields an error, (for instance print(chart.api[0].HasLegend) yields an error). I can't understand what kind of object this is or how it is useful. I can't find anything regarding this in the official documentation. Finally my question is: what is the object at the index 0 above? Please, help me grok what it is.
has title: Chart objects in xlwings
type: Question
score: 1

http://stackoverflow.com/q/51967374
has answer: http://stackoverflow.com/a/51968064
tagged with: list
has body: I am trying to make a program that outputs all possibilities to put + or - or nothing between the numbers 1,2,…,9 such that the result is 100 Understandably, there are a few people who have uploaded solutions already on the internet, but I want to come up with my own. Here's the non working code: """ This program outputs all possibilities to put + or - or nothing between the numbers 1,2,…,9 (in this order) such that the result is 100 """ class solver: def __init__(self): """ self.possibilities stores Arrays of type : [0]- always the sum of all operations [1:9] all operations in int, where 0 equals plus, 1 equals minus, 2 equals nothing """ self.possibilities = [] self.possibilities.append([100]) for i in range(7): self.possibilities.extend(self.makeNewIteration(i+1)) print(self.possibilities) for obj in self.possibilities: if 100 is obj[0]: print(obj) def makeNewIteration(self, i): for obj in self.possibilities: if(len(obj)&lt;9): if(obj[-1] is 3):#if case 3 #recalculate the result currentResult = int(obj[0] + self.conceal(i-1, i)) else: currentResult = int(obj[0]) #print(obj) possibilitiesNew = [] possibilitiesNew.append([currentResult + i] + obj[1:] + [1])#case 1 possibilitiesNew.append([currentResult - i] + obj[1:] + [2])#case 2 possibilitiesNew.append([currentResult] + obj[1:] + [3])#case 3 print("Iteration: "+str(i)+" : "+str(possibilitiesNew)) self.possibilities.remove(obj)#remove the old object else: print("finished.") return possibilitiesNew def conceal(self, x, y): # makes 12 out of x=1 and y=2 return int(f'{x}{y}') solve = solver() The more I think about it the more problems I have. I used to learn programming with an OOP mindset, and both the fact that it was a while ago and that this question is much easier with a procedural work flow makes me stuck. For example, what happens if there is two times "nothing" in a row ? does 1, 2, 3, 4 become 12,23 and ? ... I hope someone could fix the code a bit and I would figure out what I did wrong
score: 0
has comment: http://stackoverflow.com/comment/90884909
has answer: http://stackoverflow.com/a/51968454
answer count: 2
has comment: http://stackoverflow.com/comment/90884971
type: UnansweredQuestion
has title: How to solve this Array task in python that I couldn't for days?
has comment: http://stackoverflow.com/comment/90884808
tagged with: arrays
type: Question
tagged with: python

http://stackoverflow.com/comment/91083502
score: 3
comment on: http://stackoverflow.com/q/52065970
type: Comment
type: QuestionComment
has text: that's fair, IMO people are less likely to follow a link and *then* read a long question than they are to read one that's inlined :) As long as all of the information is "minimal and necessary" it's okay for it to be long. A cursory look at that link makes it clear that *not* everything is necessary. There's a fair amount of text about kings and their children, which is irrelevant to any programming problem. Maybe you don't need *any* of the text, and can put a reduced part of the code and then your attempt to optimize it, e.g., with the resultant problem in complexity

deserialization
type: Tag
tag name: deserialization
tags question: http://stackoverflow.com/q/51978421
tags question: http://stackoverflow.com/q/52064512

http://stackoverflow.com/comment/90925946
has text: @JohnStark I don't think you have gone to the details of the question. I don't have a fixed start, stop or step params. I have an index list which I can use to slice it into two lists may be. Definitely not a duplicate
type: QuestionComment
type: Comment
score: 1
comment on: http://stackoverflow.com/q/51988142

http://stackoverflow.com/comment/91140670
type: QuestionComment
comment on: http://stackoverflow.com/q/52089554
score: 0
has text: I am really curious, what solution is faster?
type: Comment

http://stackoverflow.com/comment/90996058
comment on: http://stackoverflow.com/a/52022782
type: AnswerComment
score: 0
has text: There was a missing `-f` option (fixed).
type: Comment

http://stackoverflow.com/comment/91038620
comment on: http://stackoverflow.com/q/52043378
has text: Your session object needs a proxy detail so you can use s.proxies=proxies
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/52059318
has comment: http://stackoverflow.com/comment/127320434
upvote count: 6
has body: Interestingly I'd expect you to get an AmbiguousForeignKeyError but instead you seem to get a CircularDependencyError? According to the docs this is caused by two scenarios: In a Session flush operation, if two objects are mutually dependent on each other, they can not be inserted or deleted via INSERT or DELETE statements alone; an UPDATE will be needed to post-associate or pre-deassociate one of the foreign key constrained values. The post_update flag described at Rows that point to themselves / Mutually Dependent Rows can resolve this cycle. In a MetaData.sorted_tables operation, two ForeignKey or ForeignKeyConstraint objects mutually refer to each other. Apply the use_alter=True flag to one or both, see Creating/Dropping Foreign Key Constraints via ALTER. I'm not sure what you're executing that's causing this particular error, but most likely you'll be able to solve it by solving the ambiguous reference. The ambigious reference is due to SQLAlchemy not being able to figure out how to perform the join when there are multiple references (users and created_by in this case). This can be resolved by specifying how the relationship should join which can be done by either giving the specific foreign key it should use or by explicitly determining the join condition. You can see these being applied to your example here: class User(Base): # Other setup / fields group_id = Column(Integer, ForeignKey('group.id')) class Group(Base): # Other setup / fields created_by_id = Column(Integer, ForeignKey('user.id'), nullable=False) created_by = relationship("User", foreign_keys=[created_by_id]) users = relationship("User", backref="group", primaryjoin=id==User.group_id) Documentation regarding relationship joins: http://docs.sqlalchemy.org/en/latest/orm/join_conditions.html#configuring-how-relationship-joins
score: 6
type: Answer
has comment: http://stackoverflow.com/comment/127320481
downvote count: 0
answers question: http://stackoverflow.com/q/52057470

http://stackoverflow.com/a/52079755
answers question: http://stackoverflow.com/q/52079185
downvote count: 0
score: 9
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/91112776
upvote count: 9
has comment: http://stackoverflow.com/comment/91118520
accepted answer of: http://stackoverflow.com/q/52079185
type: Answer
has body: Vertical window is set by ylim option. I recommend to also use some explicit limits for x, the default -10 to 10 is not necessarily best for you. And I do recommend reading the page on SymPy plotting. Color is set by line_color option. Different colors require different calls to plot, but those can be combined. Example: p = plot(y, (x, -5, 5), ylim=(-20, 20), line_color='b', show=False) p.extend(plot(yp, (x, -5, 5), ylim=(-20, 20), line_color='r', show=False)) p.show() results in The function reuse is easy: def derivative(a, b, c, d): y = f1(a, b, c, d) yprime = y.diff(x) return yprime Aside: what happens if we try line_color=['b', 'r'], as in plot(y, yp, ylim=(-20, 20), line_color=['b', 'r'])? Funny stuff happens:

http://stackoverflow.com/q/52030458
score: 2
downvote count: 0
tagged with: vertex
has answer: http://stackoverflow.com/a/52030534
linked to: http://stackoverflow.com/q/27948363
tagged with: multidimensional-array
has comment: http://stackoverflow.com/comment/91011489
answer count: 1
tagged with: python
favorite count: 0
has comment: http://stackoverflow.com/comment/91011413
upvote count: 2
has body: i have numpy array in python which contains lots (10k+) of 3D vertex points (vectors with coordinates [x,y,z]). I need to calculate distance between all possible pairs of these points. it's easy to do using scipy: import scipy D = spdist.cdist(verts, verts) but i can't use this because of project policy on introducing new dependencies. So i came up with this naive code: def vert_dist(self, A, B): return ((B[0]-A[0])**2+(B[1]-A[1])**2+(B[2]-A[2])**2)**(1.0/2) # Pairwise distance between verts #Use SciPy, otherwise use fallback try: import scipy.spatial.distance as spdist D = spdist.cdist(verts, verts) except ImportError: #FIXME: This is VERY SLOW: D = np.empty((len(verts), len(verts)), dtype=np.float64) for i,v in enumerate(verts): #self.app.setStatus(_("Calculating distance %d of %d (SciPy not installed =&gt; using SLOW AF fallback method)"%(i,len(verts))), True) for j in range(i,len(verts)): D[j][i] = D[i][j] = self.vert_dist(v,verts[j]) vert_dist() calculates 3D distance between two vertices and rest of code just iterates over vertices in 1D array and for each one it calculates distance to every other in the same array and produces 2D array of distances. But that's extremely slow (1000 times) when compared to scipy's native C code. I wonder if i can speed it up using pure numpy. at least to some extent. Some more info: https://github.com/scipy/scipy/issues/9172 BTW i've tried PyPy JIT compiler and it was even slower (10 times) than pure python. UPDATE: I was able to speed things up a little like this: def vert_dist_matrix(self, verts): #FIXME: This is VERY SLOW: D = np.empty((len(verts), len(verts)), dtype=np.float64) for i,v in enumerate(verts): D[i] = D[:,i] = np.sqrt(np.sum(np.square(verts-verts[i]), axis=1)) return D This eliminates the inner loop by computing whole row at once, which makes stuff quite faster, but still noticeably slower than scipy. So i still look at @Divakar's solution
accepted answer: http://stackoverflow.com/a/52030534
has comment: http://stackoverflow.com/comment/91011578
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91011498
has title: Vectorized spatial distance in python using numpy
linked to: http://stackoverflow.com/q/51352699
tagged with: scipy
type: Question
tagged with: numpy

http://stackoverflow.com/q/52082823
tagged with: regex
favorite count: 0
has title: Parsing ID from List of Strings with Regex
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91115963
downvote count: 1
has comment: http://stackoverflow.com/comment/91116143
score: -1
type: Question
has answer: http://stackoverflow.com/a/52083001
has body: If you have a list of strings: Z100 = [ '[ship, \'house\', "boat": 65, "price":10000, "car_id":"128bhsdfb03-2389-1379be8", "age":15]', '[ ]', '[shoe, 8000, "car_id":"asdlp-2394397-2njn84-kncbka", \'store\', "boat": 20, "price":4050, "age":43]' ] How do you use a regex do get the following list? car_id = ['128bhsdfb03-2389-1379be8', '', 'asdlp-2394397-2njn84-kncbka'] I tried using the following code, but it did not work: new_results = [] for item in car_id: new_list = re.search(r"car_id[^\d]*?(\d+)", item) if new_list: new_results.append(str(item.group(1)))
upvote count: 0
has comment: http://stackoverflow.com/comment/91115995
answer count: 1
tagged with: python

http://stackoverflow.com/comment/90925618
type: AnswerComment
type: Comment
has text: That works. I am going to mark Wen's answer as the solution though because he already has it posted and your answer is just a small variation of that.
score: 0
comment on: http://stackoverflow.com/a/51987693

http://stackoverflow.com/comment/91129421
type: Comment
score: 0
has text: @YogeshSP this post has been updated. Please accept this answer instead.
type: AnswerComment
comment on: http://stackoverflow.com/a/52089336

colander
type: Tag
tags question: http://stackoverflow.com/q/52006010
tag name: colander

http://stackoverflow.com/comment/91127086
comment on: http://stackoverflow.com/q/52088299
has text: i am trying to do datetimes remover with python, this is an example file .my file is too large .
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91087658
has text: This post will help you: https://stackoverflow.com/questions/22470690/get-list-of-pandas-dataframe-columns-based-on-data-type
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52068828

http://stackoverflow.com/q/51967191
has comment: http://stackoverflow.com/comment/90914643
score: 0
has body: I am trying to install jep with pip on Windows. It gave me following error: error: Microsoft Visual C++ 14.0 is required. Get it with "Microsoft Visual C++ Build Tools": http://landinghub.visualstudio.com/visual-cpp-build-tools It seems that we need c compiler for installing this jep. I dont have c compiler installed on Windows. So I was trying to install it on cygwin. But installing it on cygwin also gives me following problem: $ pip3 install jep Collecting jep Using cached https://files.pythonhosted.org/packages/3e/0c/d78776bc56fcef175470c3a7081361cffedd10ca3e8fff9ebdb2c51f9e7e/jep-3.8.2.tar.gz Building wheels for collected packages: jep Running setup.py bdist_wheel for jep ... error Complete output from command /usr/bin/python3 -u -c "import setuptools, tokenize;__file__='/tmp/pip-build-2lilr_ba/jep/setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" bdist_wheel -d /tmp/tmpimho8uljpip-wheel - --python-tag cp36: numpy include found at /usr/lib/python3.6/site-packages/numpy/core/include running bdist_wheel running build running setup_java Using JAVA_HOME: D:\Mahesh\Programs\jdk1.8.0_74 running build_java D:\Mahesh\Programs\jdk1.8.0_74/bin/javac -deprecation -d build/java -classpath src src/main/java/jep/AbstractNDArray.java src/main/java/jep/ClassEnquirer.java src/main/java/jep/ClassList.java src/main/java/jep/DirectNDArray.java src/main/java/jep/Jep.java src/main/java/jep/JepConfig.java src/main /java/jep/JepException.java src/main/java/jep/JepScriptEngine.java src/main/java/jep/JepScriptEngineFactory.java src/main/java/jep/LibraryLocator.java src/main/java/jep/MainInterpreter.java src/main/java/jep/NamingConventionClassEnquirer.java src/main/java/jep/NDArray.java src/main/java/jep/Proxy.ja va src/main/java/jep/PyConfig.java src/main/java/jep/Run.java src/main/java/jep/SharedInterpreter.java src/main/java/jep/Util.java src/main/java/jep/python/InvocationHandler.java src/main/jav…
type: UnansweredQuestion
tagged with: pip
tagged with: python
answer count: 0
type: Question
tagged with: jepp
has comment: http://stackoverflow.com/comment/90889926
has title: Unable to install jepp with pip
has comment: http://stackoverflow.com/comment/90916816

http://stackoverflow.com/q/52010458
tagged with: beautifulsoup
accepted answer: http://stackoverflow.com/a/52010865
has title: selenium python beautifulsoup stuck on currentpage
upvote count: 1
tagged with: python
tagged with: selenium-webdriver
has body: I am trying to scrape a public facebook group using beautifulsoup, I am using the mobile site for the lack of javascript there. So this script supposed to get the link from the 'more' keyword and get the text from p tag there, but it just gets the text from the current page's p tag. Can someone point me the problem? I am new to python and everything in this code. from selenium import webdriver from selenium.webdriver.common.keys import Keys from selenium.common.exceptions import NoSuchElementException from bs4 import BeautifulSoup import requests browser = webdriver.Firefox() browser.get('https://mobile.facebook.com/groups/22012931789?refid=27') for elem in browser.find_elements_by_link_text('More'): page = requests.get(elem.get_attribute("href")) soup=BeautifulSoup(page.content,'html.parser') print(soup.find_all('p')[0].get_text())
type: AnsweredQuestion
score: 1
type: Question
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/52010865
favorite count: 0

http://stackoverflow.com/comment/91166982
type: Comment
comment on: http://stackoverflow.com/a/52108045
has text: Thanks so much! It's obvious now, but i was scratching my head for a couple of hours.
type: AnswerComment
score: 0

http://stackoverflow.com/comment/90976962
has text: Beautiful. Thank you. Is the .T a pandas related function to return the last item of the tail?
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/52010617
type: Comment

http://stackoverflow.com/comment/91014795
type: Comment
comment on: http://stackoverflow.com/q/52032262
has text: Try looking into sets.
score: 0
type: QuestionComment

http://stackoverflow.com/comment/91027297
type: QuestionComment
comment on: http://stackoverflow.com/q/52038483
has text: It looks like [this](https://github.com/conda/conda/issues/7130)
score: 0
type: Comment

http://stackoverflow.com/comment/91162567
type: QuestionComment
has text: You'll get much better help if you post a [Minimal, complete, verifiable example](http://stackoverflow.com/help/mcve): show your best attempt at one of those loops, along with actual and desired output. Get rid of all the input overhead that's not part of the problem; just directly assign the principal, period, etc.
comment on: http://stackoverflow.com/q/52105707
score: 1
type: Comment

anaconda
tags question: http://stackoverflow.com/q/52056247
tags question: http://stackoverflow.com/q/52045098
tags question: http://stackoverflow.com/q/52108946
type: Tag
tags question: http://stackoverflow.com/q/52034426
tags question: http://stackoverflow.com/q/52053383
tags question: http://stackoverflow.com/q/52013452
tags question: http://stackoverflow.com/q/52020738
tags question: http://stackoverflow.com/q/52051760
tags question: http://stackoverflow.com/q/51991004
tags question: http://stackoverflow.com/q/52045599
tags question: http://stackoverflow.com/q/52068083
tags question: http://stackoverflow.com/q/51987299
tags question: http://stackoverflow.com/q/51997619
tags question: http://stackoverflow.com/q/51977805
tags question: http://stackoverflow.com/q/52027756
tags question: http://stackoverflow.com/q/51959836
tags question: http://stackoverflow.com/q/51987825
tags question: http://stackoverflow.com/q/51973603
tags question: http://stackoverflow.com/q/51998310
tags question: http://stackoverflow.com/q/52029253
tags question: http://stackoverflow.com/q/52063996
tags question: http://stackoverflow.com/q/52067954
tag name: anaconda
tags question: http://stackoverflow.com/q/52068922
tags question: http://stackoverflow.com/q/52053222
tags question: http://stackoverflow.com/q/51957827
tags question: http://stackoverflow.com/q/52045877
tags question: http://stackoverflow.com/q/52004335
tags question: http://stackoverflow.com/q/52038483
tags question: http://stackoverflow.com/q/51963760
tags question: http://stackoverflow.com/q/51994752
tags question: http://stackoverflow.com/q/52007396
tags question: http://stackoverflow.com/q/52096590
tags question: http://stackoverflow.com/q/52003889
tags question: http://stackoverflow.com/q/51978816
tags question: http://stackoverflow.com/q/52066156
tags question: http://stackoverflow.com/q/51995053
tags question: http://stackoverflow.com/q/52102437
tags question: http://stackoverflow.com/q/51973396
tags question: http://stackoverflow.com/q/51995350
tags question: http://stackoverflow.com/q/51996547
tags question: http://stackoverflow.com/q/52031190
tags question: http://stackoverflow.com/q/52109370
tags question: http://stackoverflow.com/q/52063463
tags question: http://stackoverflow.com/q/52045131
tags question: http://stackoverflow.com/q/51971192

http://stackoverflow.com/comment/91000739
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52024946
has text: Yes, I know that it is memory expensive, but for my task this method is safe. However, writing the frames to disc is nice tip, Than you.
score: 0

http://stackoverflow.com/q/52035644
answer count: 0
tagged with: tensor
type: UnansweredQuestion
upvote count: 1
tagged with: python
downvote count: 1
has body: I have a tensor with the dimensions &lt;tf.Tensor 'conv2d_1/Relu:0' shape=(?, 32, 24, 24) dtype=float32&gt;. The first dimension is not known. How do I convert this to a numpy array? I have used the following code sess = tf.Session() with sess.as_default(): y = tf.shape(x) nx = y.eval() print(nx) Here, x is the input tensor.
has comment: http://stackoverflow.com/comment/102206339
has comment: http://stackoverflow.com/comment/91021872
has title: How to covert a tensor with an unknown dimension to a numpy array
tagged with: tensorflow
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/91022656
favorite count: 0
score: 0
has comment: http://stackoverflow.com/comment/91100796

http://stackoverflow.com/q/52064233
type: UnansweredQuestion
tagged with: python
tagged with: inference
answer count: 0
score: 1
upvote count: 1
tagged with: tensorflow
type: Question
has comment: http://stackoverflow.com/comment/91411946
tagged with: for-loop
has body: I've created a system that chooses some 20,000 or so locations that contain classified training data, extracts the values to a DataFrame, and trains and saves a vanilla neural net (mlp). I then create the large np.ndarray that needs inference (data.shape = (60, 8000, 8000)), restore the model, and begin a ~6-10 hr for-loop that classifies each location in the 8000x8000 pixel space to produce a classified ndarray, new_array.shape = (1, 8000, 8000). My question is simple: Is there a better way than doing a Python for-loop over the 64*10**6 pixel locations to infer this large pixel space? Context: This is a project that gathers a feature array from a stack of Landsat images, and samples areas of known land classes according to vector GIS data. Then it infers the rest of the image and writes a new raster with rasterio. The tensorflow multilayer perceptron is here, the training array construction is here. Code: I've tried to remove all cruft. def classify_stack(data, model, out_location=None): final_shape = 1, data.shape[1], data.shape[2] # reshape, mask np.nan values data = data.reshape((data.shape[0], data.shape[1] * data.shape[2])) data[data == 0.] = np.nan m_stack = marray(data, mask=np.isnan(stack)) n = m_stack.shape[0] new_array = np.zeros_like((data.shape[1], data.shape[2]), dtype=float16) g = tf.get_default_graph() with tf.Session() as sess: saver = tf.train.import_meta_graph('{}.meta'.format(model)) saver.restore(sess, model) pixel = tf.placeholder("float", [None, n]) wh = sess.graph.get_tensor_by_name('Wh:0') wo = sess.graph.get_tensor_by_name('Wo:0') bh = sess.graph.get_tensor_by_name('Bh:0') bo = sess.graph.get_tensor_by_name('Bo:0') classify = tf.add(tf.matmul(multilayer_perceptron(pixel, wh, bh), wo), bo) time = datetime.now() ct_nan = 0 ct_out = 0 for i in range(m_stack.shape[-1]): if not np.ma.is_masked(m_stack[:, i]): dat = m_stack[:, i] dat = array(dat).reshape((1, dat.shape[0])) loss = sess.run(classify, feed_dict={pixel: dat}) new_array[0, i] = np.arg…
downvote count: 0
has title: Tensorflow inference on large ndarray: cython or muliprocessing speed-up possible?
favorite count: 0
tagged with: multidimensional-array

http://stackoverflow.com/q/52104433
tagged with: python
has comment: http://stackoverflow.com/comment/91167661
answer count: 0
type: UnansweredQuestion
tagged with: django
has body: I have this Model: class Complaint(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, default=1) date_created = models.DateTimeField(auto_now_add=True, null=True, blank=True) name = models.CharField(max_length=255, unique=True) definition = models.TextField(blank=False, default="") is_violent = models.BooleanField(default=False) is_active = models.BooleanField(default=True) def __str__(self): return self.name class Meta: ordering = ['name'] def get_absolute_url(self): return reverse('complaint-details', kwargs={'pk': self.pk}) class Service(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, default=1) date_created = models.DateTimeField(auto_now_add=True, null=True, blank=True) name = models.CharField(max_length=255, unique=True) definition = models.TextField(blank=True, default="") is_active = models.BooleanField(default=True) def __str__(self): return self.name def get_absolute_url(self): return reverse('service-details', kwargs={'pk': self.pk}) class Location(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, default=1) date_created = models.DateTimeField(auto_now_add=True, null=True, blank=True) location_name = models.CharField(max_length=255, unique=True) loc_lat = models.DecimalField(max_digits=9, decimal_places=6) loc_long = models.DecimalField(max_digits=9, decimal_places=6) pop = models.PositiveIntegerField(default=500) is_AOR = models.BooleanField(default=False) is_active = models.BooleanField(default=True) def __str__(self): return self.location_name class Blotter(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, default=1) date_created = models.DateTimeField(auto_now_add=True, null=True, blank=True)#default=timezone.now().date() date = models.DateField(blank=True) time = models.TimeField(blank=True) entry_number = models.CharField(max_length=255, unique=True,validators=[RegexValidator(r'^\d{1…
has comment: http://stackoverflow.com/comment/91167619
has comment: http://stackoverflow.com/comment/91167781
has comment: http://stackoverflow.com/comment/91167299
type: Question
has comment: http://stackoverflow.com/comment/91167899
tagged with: django-rest-framework
has title: Django: get the max count of a foreign key based on other foreign key
score: 0

http://stackoverflow.com/q/52009483
upvote count: 1
tagged with: python
score: 1
type: Question
downvote count: 0
has body: I want to read some csv files from my folder and concatenate them to a big pandas dataframe. All of my csv files end with a number, and I only want to read files whose number end with (6~10, 16~20, 26~30.) My goal is to read the files iteratively. Attached is my code so far: import pandas as pd data_one = pd.read_csv('Datafile-6.csv', header=None) for i in range(7,11): data99 = pd.read_csv('Datafile-'+i+'*.csv', header=None) #this line needs work data_one = pd.concat([data_one, data99.iloc[:,1]],axis=1,ignore_index=True) data_two = pd.read_csv('Datafile-16.csv', header=None) for j in range(17,21): #Repeat similar process What should I do about 'data99' such that 'data_one' contains columns from 'Datafile-6' through 'Datafile-10'? The first five rows of data_one should look like this, after getting data from Datafiles 6-10. 0 1 2 3 4 5 0 -40.0 0.179836 0.179630 0.179397 0.179192 0.179031 1 -39.0 0.183696 0.183441 0.183204 0.182977 0.182795 2 -38.0 0.186720 0.186446 0.186191 0.185949 0.185762 3 -37.0 0.189490 0.189207 0.188935 0.188686 0.188475 4 -36.0 0.192154 0.191851 0.191569 0.191301 0.191086 Column 0 is included in all of the data files, so I'm only concatenating column 1 of all of the subsequent data files.
tagged with: http://stackoverflow.com/tag/csv
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/90970345
has answer: http://stackoverflow.com/a/52009738
type: UnansweredQuestion
has title: Python: read through multiple but not all csv files in my folder

http://stackoverflow.com/comment/91187494
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52085986
score: 0
has text: Do not post code in the comments, when you can edit your question.

http://stackoverflow.com/q/52108685
has body: Im busy building an OCR with MNIST, Tensorflow and Keras but I am having problems uploading the MNIST datasets because of an error with in MNIST. Can I upload only the first few items with out setting of an error
has comment: http://stackoverflow.com/comment/91167981
tagged with: mnist
has answer: http://stackoverflow.com/a/52110167
tagged with: tensorflow
type: Question
upvote count: 2
answer count: 2
downvote count: 2
tagged with: keras
favorite count: 0
has title: Is it possible to only load part of mnist or other tuples
score: 0
has answer: http://stackoverflow.com/a/52109621
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/comment/91093038
has text: Actually, your sample actually works. I just tried adding it to my will be snake game and it got that bug, sorry for the inconvinience.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52070859
type: Comment

http://stackoverflow.com/comment/91038712
type: QuestionComment
has text: I'm not sure why you are using *code to split text* on BeautifulSoup elements. Please, do [read the library documentation](https://www.crummy.com/software/BeautifulSoup/bs4/doc/), you'll find that the API offered is very different from what you are using here.
comment on: http://stackoverflow.com/q/52043839
type: Comment
score: 1

http://stackoverflow.com/comment/101885690
has text: Note to future self: K.print_tensor not printing in Jupyter notebook. Fine when the script is run from console.
score: 0
type: Comment
comment on: http://stackoverflow.com/q/52023119
type: QuestionComment

http://stackoverflow.com/comment/91081927
has text: @AnkurSingh thank you Ankur. I have to admit that solution seems a little bit over my head, I was hoping to have a solution sticking to selenium but thank you very much for your help.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52045120
score: 0

http://stackoverflow.com/comment/91054448
has text: @FlyingTeller - apologies! Guess, I am just too tense. Yes, there are 708 items in that directory. But, I can't get the "ls" command to work. I had to get the details from finder.
score: 0
comment on: http://stackoverflow.com/q/52051760
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/90990479
has text: what is inside your `html` variable? You might have to first search for a block of code/ class inside your `google_search` as in `html = soup.find_all(class_='CLASS_NAME_INSIDE_HTML')` and then just `return html` not `soup.html`
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52019664

http://stackoverflow.com/q/51979312
has comment: http://stackoverflow.com/comment/90946296
has comment: http://stackoverflow.com/comment/90978685
score: 0
answer count: 2
accepted answer: http://stackoverflow.com/a/52015620
tagged with: mysql
tagged with: django
has title: Django TypeError: id() takes exactly one argument (0 given)
has comment: http://stackoverflow.com/comment/90910680
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90909633
type: Question
possible better answer: http://stackoverflow.com/a/51982913
has comment: http://stackoverflow.com/comment/90944030
has body: So I have been trying to implement a way to upload multiple images to a post. The way I did it is to have tables. One for the actual post, and one of the multiple images uploaded. I was planning to link them with a foreign key but it is not working. My terminal started throwing the error "TypeError: id() takes exactly one argument (0 given)" . It throws me this error whenever I migrate it. I am not sure how to fix this. MY code: models.py from django.db import models from django.utils import timezone from django.forms import ModelForm from django.utils.text import slugify from django.utils.crypto import get_random_string from django.conf import settings from PIL import Image import os DEFAULT_IMAGE_ID = 1 # Create your models here. class Projects(models.Model): title = models.CharField(max_length=30) description = models.TextField(max_length=150) publish_date = models.DateTimeField(auto_now=False, auto_now_add=True) update_date = models.DateTimeField(auto_now=True, auto_now_add=False) slug = models.SlugField(unique=True) files = models.FileField(upload_to='files/', blank=True) images = models.ImageField(upload_to='images/', height_field = 'img_height', width_field = 'img_width',blank=True) img_height = models.PositiveIntegerField(default=600) img_width = models.PositiveIntegerField(default=300) #feature_images = models.ForeignKey(P_Images, on_delete=models.CASCADE, default=DEFAULT_IMAGE_ID) feature_images = models.AutoField(primary_key=True) def __str__(self): return self.title def save(self, *args, **kwargs): # Generates a random string unique_string = get_random_string(length=32) # Combines title and unique string to slugify slugtext = self.title + "-" + "unique_id=-" + unique_string self.slug = slugify(slugtext) return super(Projects, self).save(*args, **kwargs) class P_Images(models.Model): p_file = models.ImageField(upload_to='images/', blank=None) p_uploaded_at = models.DateTimeField(auto_now_add=True, auto_now=False) #fk_post = models fk_post = models.Foreign…
tagged with: python
has answer: http://stackoverflow.com/a/51982913
has answer: http://stackoverflow.com/a/52015620

http://stackoverflow.com/comment/90929987
type: QuestionComment
has text: `[''.join(your_list)]` something like this?
score: 0
type: Comment
comment on: http://stackoverflow.com/q/51990132

http://stackoverflow.com/comment/90976561
has text: I've added the stack trace. As mentioned, the print statements both return <class 'str'>
score: 0
comment on: http://stackoverflow.com/q/52012729
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52052048
has title: Output a variable list of values from a function
accepted answer: http://stackoverflow.com/a/52053572
type: Question
answer count: 2
score: 0
has comment: http://stackoverflow.com/comment/91054293
tagged with: python
has answer: http://stackoverflow.com/a/52052634
has comment: http://stackoverflow.com/comment/91054474
possible better answer: http://stackoverflow.com/a/52052634
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52053572
has body: I have a function that returns a variable list of values and I know you can do this by using a tuple. To assign these variables you can then do something like a, b = func(..). However, if there is only one value returned you have to do a, = func(..) [notice the ,] rather than a = func(..). To achieve the latter you can include a test to see if there is one value to be returned or more (see example below) but I wonder if there is no easier or less verbose way to do this. def foo(*args): returnvalues = [] for arg in args: arg += 100 returnvalues.append(arg) if len(returnvalues) == 1: return returnvalues[0] else: return tuple(returnvalues) def baz(*args): returnvalues = [] for arg in args: arg += 100 returnvalues.append(arg) return tuple(returnvalues) a = foo(10) b, c = foo(20, 30) print(f'a={a}, b={b}, c={c}') a, = baz(10) b, c = baz(20, 30) print(f'a={a}, b={b}, c={c}') # a=110, b=120, c=130 a=110, b=120, c=130

http://stackoverflow.com/q/52034957
has answer: http://stackoverflow.com/a/52035027
tagged with: pandas
score: 2
type: AnsweredQuestion
downvote count: 0
has body: I am working with a DataFrame that is expected to contain only float type index values, but I suspect that for some reason there are values of a different type, resulting in the dtype='object' type of the index. I would like to extract the values of the index that are not of the float type to see if this is the case. Example df = pd.DataFrame({'a': [1,2,3], 'b': [4,5,6]}, index=[0.0,1.5,'a']) The result of extraction in this case would be a list containing a single element ['a'].
favorite count: 0
tagged with: extract
type: Question
upvote count: 2
has answer: http://stackoverflow.com/a/52035061
tagged with: python
has answer: http://stackoverflow.com/a/52035445
has title: Extract the index values of DataFrame that are not float in pandas
tagged with: indexing
has answer: http://stackoverflow.com/a/52035033
tagged with: floating-point
possible better answer: http://stackoverflow.com/a/52035033
accepted answer: http://stackoverflow.com/a/52035445
answer count: 4

http://stackoverflow.com/comment/91088669
type: Comment
comment on: http://stackoverflow.com/q/52069303
has text: @e4c5 I've edited the blocks to remove all of those comment blocks. If I run them as is with SGE, I get the displayed output, but the entire job does not stop (i.e. always hang in the `r` state in `qstat`).
score: 0
type: QuestionComment

http://stackoverflow.com/q/51986770
has comment: http://stackoverflow.com/comment/90923229
has title: Getting table from web page using Beautiful Soup and Pandas
score: 0
answer count: 1
has answer: http://stackoverflow.com/a/51986971
tagged with: beautifulsoup
has body: Running with Python 3.6.1 the code import requests import pandas as pd from bs4 import BeautifulSoup # url_addr = "https://www.uspto.gov/web/offices/ac/ido/oeip/taf/mclsstc/mcls1.htm" url_addr = "https://www.cefconnect.com/closed-end-funds-daily-pricing" html_text = requests.get(url_addr).content bs_obj = BeautifulSoup(html_text) tables = bs_obj.findAll('table') dfs = list() for table in tables: df = pd.read_html(str(table))[0] dfs.append(df) print(df) gets only column headings but not the actual data, with output Empty DataFrame Columns: [Ticker, Fund Name, Strategy, ClosingPrice, PriceChange, NAV, Premium/Discount, DistributionRate, DistributionRate on NAV, 1 Yr Rtnon NAV] Index: [] It works for the url_addr that is commented out.
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90923426
tagged with: python
type: Question

http://stackoverflow.com/comment/91063885
comment on: http://stackoverflow.com/a/52051613
type: Comment
score: 1
type: AnswerComment
has text: ThankYou For the Edit , and i Accepted it too.

http://stackoverflow.com/a/51989985
score: 3
has comment: http://stackoverflow.com/comment/90929808
upvote count: 3
answers question: http://stackoverflow.com/q/51989866
has body: I think you want to set_index and unstack: out = df.set_index(['Id', 'field']).unstack() out.columns = out.columns.get_level_values(1) out.reset_index() field Id first_name last_name number type 0 1 a aa 123 NaN 1 2 b bb 456 p
has comment: http://stackoverflow.com/comment/90929628
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/90929545

http://stackoverflow.com/a/52096074
answers question: http://stackoverflow.com/q/52096050
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52096050
has comment: http://stackoverflow.com/comment/91142394
type: Answer
score: 11
upvote count: 11
has body: Try using plt.title('Season Winners Goal and Win Regression', y=1.3, fontsize = 16) where you can play around with the y position by changing the number. Here the position of y axis is in relative coordinate system which means y=1 means at the highest y position in the plot and anything beyond 1 would mean pushing title further higher.

http://stackoverflow.com/comment/90990305
type: Comment
comment on: http://stackoverflow.com/a/52014421
has text: For that matter, what output do you expect to see?
score: 0
type: AnswerComment

http://stackoverflow.com/a/52040099
score: 1
answers question: http://stackoverflow.com/q/52039925
accepted answer of: http://stackoverflow.com/q/52039925
has comment: http://stackoverflow.com/comment/91034142
type: Answer
has body: Use os.path.exists from the os module. import os def convert_to_non_overlapping(name): query = name i = 1 while os.path.exists(query): query = name + '({})'.format(i) i += 1 return query And a test shows its good: &gt;&gt;&gt; convert_to_non_overlapping('bob') 'bob' &gt;&gt;&gt; open('bob', 'w') #creates file &lt;_io.TextIOWrapper name='bob' mode='w' encoding='UTF-8'&gt; &gt;&gt;&gt; convert_to_non_overlapping('bob') 'bob(1)' &gt;&gt;&gt; open('bob(1)', 'w') #creates file &lt;_io.TextIOWrapper name='bob(1)' mode='w' encoding='UTF-8'&gt; &gt;&gt;&gt; convert_to_non_overlapping('bob') 'bob(2)'
has comment: http://stackoverflow.com/comment/91030640
has comment: http://stackoverflow.com/comment/91031235
upvote count: 1
has comment: http://stackoverflow.com/comment/91070610
has comment: http://stackoverflow.com/comment/91056738
has comment: http://stackoverflow.com/comment/91030760
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/a/51998260
type: AcceptedAnswer
type: Answer
score: 2
downvote count: 0
answers question: http://stackoverflow.com/q/51997619
accepted answer of: http://stackoverflow.com/q/51997619
upvote count: 2
has body: There is no idiomatic way to approach this issue other than some bash hackery: An issue is that conda's repository may not be as comprehensive, and does not cover all versions. Assuming all versions will work, here is an easy script: conda install $(pip freeze | sed 's/==/=/g') Because pip requires == to pin the version meanwhile conda requires =, simply sed the input to be in the correct format. If it doesn't work, then you have to go for the riskier method: (sandbox) ❯ for pkg in $(pip freeze | sed 's/==/=/g'); do conda install -y $pkg; done I even made a sandbox conda environment in case I screw up my python. This will install anything you have in pip, and if it fails(i.e. corresponding version doesnt exist in conda repos), then it silently goes on to install the next package. Note that this is highly risky and you should definitely check what you installed and what you didn't afterwards.

http://stackoverflow.com/comment/102666298
type: AnswerComment
comment on: http://stackoverflow.com/a/51957867
score: 0
type: Comment
has text: @Jon to move follow this link. I suggest just uninstall and start over: https://docs.anaconda.com/anaconda/user-guide/tasks/move-directory/

http://stackoverflow.com/a/51993219
has comment: http://stackoverflow.com/comment/90940975
upvote count: 2
has comment: http://stackoverflow.com/comment/90940278
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/51992641
type: Answer
has comment: http://stackoverflow.com/comment/90938819
answers question: http://stackoverflow.com/q/51992641
has comment: http://stackoverflow.com/comment/90938028
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/90940160
has body: Pandas has fantastic support for time series, so it's a good idea to leverage the appropriate tools. After we convert our columns to a single Datetime column, we can do time arithmetic on it: # demo dataframe df = pd.DataFrame({ 'birthMonth': [5, 2], 'birthDay': [4, 24], 'birthYear': [1924, 1997], 'deathMonth': [3, None], 'deathDay': [1, None], 'deathYear': [2008, None] }) # convert birth dates to datetimes birth = pd.to_datetime(df'birthMonth', 'birthDay', 'birthYear' .rename(columns={'birthMonth': 'month', 'birthDay': 'day', 'birthYear': 'year'})) # convert death dates to datetimes death = pd.to_datetime(df'deathMonth', 'deathDay', 'deathYear' .rename(columns={'deathMonth':'month', 'deathDay': 'day', 'deathYear': 'year'})) # calculate age in days, normalizing 'now' to midnight of today age = (pd.Timestamp.now().normalize() - birth).where(death.isnull(), other=death-birth) Edit: see discussion by @ALollz below regarding timestamp normalization.
has comment: http://stackoverflow.com/comment/90937861

http://stackoverflow.com/comment/91088583
type: Comment
type: QuestionComment
has text: hello all, view below my solution, but I know it could be cleaner. Just seraching for a way to have logic like ( remove all special characters (something like \w) Except for dashes, underscores spaces)
score: 0
comment on: http://stackoverflow.com/q/52069098

http://stackoverflow.com/comment/91109184
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52079572
has text: I heard great things about `startswith()`...
score: 0

http://stackoverflow.com/a/52101934
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/52101829
has comment: http://stackoverflow.com/comment/91154754
type: Answer
has body: use assign and groupby df = df.assign(**df.groupby('ID')['Data1', "Data2"].cumsum()) print(df) Year ID Data1 Data2 0 2010 A 1 2 1 2011 A 3 4 2 2012 A 6 6 3 2013 A 10 8 4 1922 B 2 3 5 1923 B 5 6 6 1924 B 9 9
has comment: http://stackoverflow.com/comment/91154830
score: 1
upvote count: 1
accepted answer of: http://stackoverflow.com/q/52101829

http://stackoverflow.com/comment/108775713
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52043377
has text: @Mark, finally I found out that I should run ppserver (https://softwarerecs.stackexchange.com/questions/38802/best-parallel-python-for-a-cluster); but there are two problems: 1) the ppserver is not in pathos library. 2) The ppserver available in pp library is old and its version does not match with pathos. System says PP version mismatch (local: pp-1.6.6.1, remote: pp-1.6.4.4) so I receive this error on server: RuntimeError: Socket connection is broken. There should be a ppserver alternative in pathos; but I don't know it. Please advise.
score: 0

http://stackoverflow.com/q/52040205
has title: PyQt5 - exit code 3 when using QSortFilterProxyModel --> filterAcceptsRow
has body: i m trying to use a QSortFilterProxyModel in PyQt5 (Python 3.7 -IDE PyCharm). I always get "Process finished with exit code 3" and nothing else happens. Here is the code I use for trying (found it also in Stackoverflow): from PyQt5.QtCore import * from PyQt5.QtWidgets import * import sys class Model(QAbstractTableModel): def __init__(self, parent=None, *args): QAbstractTableModel.__init__(self, parent, *args) self.items = ['Item_A_001','Item_A_002','Item_B_001','Item_B_002'] def rowCount(self, parent=QModelIndex()): return len(self.items) def columnCount(self, parent=QModelIndex()): return 1 def data(self, index, role): if not index.isValid(): return QVariant() elif role != Qt.DisplayRole: return QVariant() row=index.row() if row&lt;len(self.items): return QVariant(self.items[row]) else: return QVariant() class Proxy(QSortFilterProxyModel): def __init__(self): super(Proxy, self).__init__() def filterAcceptsRow(self, row, parent): if '_B_' in self.sourceModel().data(self.sourceModel().index(row, 0), Qt.DisplayRole).toPyObject(): return True return False class MyWindow(QWidget): def __init__(self, *args): QWidget.__init__(self, *args) tableModel=Model(self) proxyModel=Proxy() proxyModel.setSourceModel(tableModel) self.tableview=QTableView(self) self.tableview.setModel(proxyModel) self.tableview.clicked.connect(self.viewClicked) self.tableview.horizontalHeader().setStretchLastSection(True) layout = QVBoxLayout(self) layout.addWidget(self.tableview) self.setLayout(layout) def viewClicked(self, indexClicked): print('index of proxy row', indexClicked.row()) if __name__ == "__main__": app = QApplication(sys.argv) w = MyWindow() w.show() sys.exit(app.exec_()) Thanks in advance for any help.
tagged with: qsortfilterproxymodel
tagged with: python
accepted answer: http://stackoverflow.com/a/52042965
type: AnsweredQuestion
tagged with: pyqt5
type: Question
tagged with: qabstractitemmodel
score: 0
has answer: http://stackoverflow.com/a/52042965
tagged with: pyqt
answer count: 1

http://stackoverflow.com/a/52008540
has comment: http://stackoverflow.com/comment/90990960
has comment: http://stackoverflow.com/comment/90990006
has comment: http://stackoverflow.com/comment/90990302
has comment: http://stackoverflow.com/comment/90994928
score: 0
answers question: http://stackoverflow.com/q/52008289
has body: The reason is because the "UnMark" tag has a higher priority than the "Mark" tag. You can add the "Mark" tag, but the configuration of "UnMark" takes precedence. I recommend instead of an "UnMark" tag, you simply remove the "Mark" tag when you don't want something to be marked.
type: Answer

http://stackoverflow.com/comment/91060759
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52054825
type: Comment
has text: You have three related models which makes it slightly complex, so I can't writie your save method for you. You need to fetch the category from the `category_id`, then loop through the keys and values of `self.cleaned_data` and set the correct values.

http://stackoverflow.com/q/52097086
type: Question
tagged with: scheduling
tagged with: optimization
answer count: 1
has body: I am having some issues with defining my objective function for a scheduling optimization problem. I simply want to minimize undercapacity. My setup: import pulp nr_employees = 61 #len(dfRolePreferences['Naam']) nr_shifts = 3 nr_roles = 5 #len(dfRolePreferences.columns) - 1 nr_days = 5 employees = range(1,nr_employees + 1) roles = range(1, nr_roles + 1) days = range(1, nr_days + 1) shifts = range(1, nr_shifts + 1) hours = range(24) #Export proces D = {} # Demand matrix X = {} # Assignment matrix Assignment matrix X = pulp.LpVariable.dicts("X", product(employees, days, shifts, hours), cat=pulp.LpBinary) Demand matrix This is a pandas dataframe I import from an Excel. It has simply three columns 'Weekday' - the weekday (1-5) 'Hour'- the specific hour slot (0-23) 'Demand' - the required resources for the combination I transform the demand dataframe to a pulp dict: for d in days: for h in hours: D[(d, h)] = pulp.LpVariable(int(dfDemand.loc[(dfDemand['Weekday']==d) &amp; (dfDemand['Hour']==h), "Demand"])) But now I want to create the objective function like this: # Create the problem scheduling_problem = pulp.LpProblem("Employee Scheduling", pulp.LpMinimize) obj = None for d in days: for h in hours: obj += (sum(X[(e,d,s,h)] for e in employees for s in shifts) - D[(d,h)]) scheduling_problem += obj scheduling_problem I want to substract the demand value from X (sum of employees for X value) but I have the feeling that this syntax is incorrect to program the following formula: Could you help me with the right syntax for this formula?
type: UnansweredQuestion
has title: PuLP objective function syntax not right
tagged with: python
has answer: http://stackoverflow.com/a/52097821
score: 0
tagged with: pulp

http://stackoverflow.com/q/52032661
has comment: http://stackoverflow.com/comment/91016292
has comment: http://stackoverflow.com/comment/91016225
tagged with: python
answer count: 0
upvote count: 3
has title: prevent requests-mock from lower casing my post data
tagged with: python-requests
type: Question
has comment: http://stackoverflow.com/comment/91016173
tagged with: requests-mock
score: 3
has comment: http://stackoverflow.com/comment/91016009
has comment: http://stackoverflow.com/comment/91015912
has comment: http://stackoverflow.com/comment/91016105
has body: When using requests-mock, my querystring data is lowercased: request.post('http://foo.bar', params={'Foo': 'Bar'}) def foo_bar(self, request, context): import pdb; pdb.set_trace() The actual value of request.qs will be {'foo': ['bar']}. How do I get it to not lower case my query string data? There's a bug that should be fixed in 1.1: https://bugs.launchpad.net/requests-mock/+bug/1584008 I'm using 1.3 though and still having this issue.
has comment: http://stackoverflow.com/comment/91015642
has comment: http://stackoverflow.com/comment/91016430
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/91016369
has comment: http://stackoverflow.com/comment/91015750
type: UnansweredQuestion

http://stackoverflow.com/a/51961558
has body: Do it the other way round. Set self.output to the environment variable, if it is not set: if not self.output: self.output = os.environ.get('MY_UTILITY_PATH', os.getcwd())
upvote count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/90875777
answers question: http://stackoverflow.com/q/51961434
type: Answer
score: 1

ebnf
type: Tag
tags question: http://stackoverflow.com/q/52037501
tag name: ebnf
tags question: http://stackoverflow.com/q/52100394

http://stackoverflow.com/a/52013414
score: 1
upvote count: 1
type: AcceptedAnswer
downvote count: 0
has body: If this is solely for testing purposes, updating your PYTHONPATH while running test code would be roughly the Python equivalent to updating LD_LIBRARY_PATH for testing C code. In much the same way LD_LIBRARY_PATH pushes some directories to the front of the shared object lookup path, PYTHONPATH pushes specific directories to the front of sys.path, and does so from the moment Python begins running (so you know there aren't any weird site triggered imports that might take place before you have time to update sys.path in your main module). Using it for production is frowned upon (among other things, the same environment variable is read by both Python 2 and 3, so it can cause problems if any code at that location isn't compatible with both versions), but for test code, it's no more unreasonable than tweaking LD_LIBRARY_PATH. Virtual environments might work, but only if you could somehow publish the virtualenv company-wide; they store full copies of their local libraries, and (by default) prevent access to otherwise site-wide installed packages (to provide a clean environment). A test-centered virtualenv might want to pass the switch that allows access to system modules so it acts as a supplement to the system, not a replacement. Activating virtualenvs in bash-like shells is simply a matter of running source /path/to/virtualenv/bin/activate, while deactivating them is just running deactivate (it's added to your shell as a function when the activate script is sourceed). They're generally safer than modifying PYTHONPATH (among other things, they use version-specific sub-directories for each major.minor version of Python, so you won't accidentally run 3.6 specific code on 2.7), but you do need to write your test code as real packages (with setup.py files and all) to manage them properly. I personally think this is worth it (you'll need to learn the Python packaging mechanisms eventually), but it is a higher initial skill bar.
answers question: http://stackoverflow.com/q/52013365
type: Answer
accepted answer of: http://stackoverflow.com/q/52013365

http://stackoverflow.com/q/51978308
has body: I have grouped a dataframe called "full_df2" by the "filter" column. Then I put the distinct 'filter' group names in a list called "unique_list". I want to iterate through my dataframe with the following code so that I can get a plot for each grouping. 'Rating' and 'hhs' are the columns in my dataframe that I will run the regression on. When I run the code below, I get this error. ValueError: too many values to unpack (expected 4) I've tried adding .split(',') at the end of line 2, but it doestn't help. I've been surfing through boards trying to get past this error. I'm new to Python. So, any help and explanation would be greatly appreciated. Here's some sample data and the real code I used. full_df2 = np.array([['Letter', 'Sync', 'Status', 'filter', 'Rating', 'hhs'], ['A', 'And', 'Off', 'A And Off', .4, 300], ['A', 'And', 'On', 'A And On', .5, 300] ['A', 'Or', 'Off', 'A Or Off', .7, 300] ['A', 'Or', 'On', 'A Or On', .3, 300] ['A', 'Between', 'Off', 'A Between Off', .6, 300] ['A', 'Between', 'On', 'A Between On', .4, 300] ['A', 'And', 'Off', 'A And Off', .6, 400], ['A', 'And', 'On', 'A And On', .4, 400] ['A', 'Or', 'Off', 'A Or Off', .3, 400] ['A', 'Or', 'On', 'A Or On', .4, 400] ['A', 'Between', 'Off', 'A Between Off', .3, 400] ['A', 'Between', 'On', 'A Between On', .8, 400] ['A', 'And', 'Off', 'A And Off', .4, 250], ['A', 'And', 'On', 'A And On', .5, 250] ['A', 'Or', 'Off', 'A Or Off', .7, 250] ['A', 'Or', 'On', 'A Or On', .3, 250] ['A', 'Between', 'Off', 'A Between Off', .6, 250] ['A', 'Between', 'On', 'A Between On', .4, 250] ]) unique_df = dict(tuple(full_df2.groupby(['Letter', 'Sync', 'Status', 'filter']))) unique_list = ([x[-1] for x in unique_df]) for x in unique_list: print (x) for p in unique_list: slope, intercept, r_value, p_value, std_err = stats.linregress(full_df2.query("filter == @p")'rating', full_df2.query("filter == @p")'hhs') filter_df = full_df2.query("filter == @p") ax = sns.regplot(x="rating", y="hhs", data=filter_df, color='b', line_k…
type: AnsweredQuestion
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/90930758
type: Question
has comment: http://stackoverflow.com/comment/90930656
has answer: http://stackoverflow.com/a/52000916
has comment: http://stackoverflow.com/comment/90928068
accepted answer: http://stackoverflow.com/a/52000916
has comment: http://stackoverflow.com/comment/90935128
tagged with: pandas
answer count: 1
has comment: http://stackoverflow.com/comment/90927110
downvote count: 0
tagged with: scikit-learn
has comment: http://stackoverflow.com/comment/90911420
favorite count: 0
tagged with: python
has comment: http://stackoverflow.com/comment/90927105
has comment: http://stackoverflow.com/comment/90914943
has title: Iterate through grouping with a query used in argument to linregress

http://stackoverflow.com/comment/90909461
comment on: http://stackoverflow.com/q/51977051
score: 2
has text: If not, it's most likely because your keyboard layout.
type: Comment
type: QuestionComment

kivy-language
type: Tag
tags question: http://stackoverflow.com/q/51987320
tags question: http://stackoverflow.com/q/52084887
tags question: http://stackoverflow.com/q/51968900
tags question: http://stackoverflow.com/q/51957668
tags question: http://stackoverflow.com/q/52017494
tags question: http://stackoverflow.com/q/52048698
tags question: http://stackoverflow.com/q/52016931
tags question: http://stackoverflow.com/q/52032126
tags question: http://stackoverflow.com/q/51970356
tags question: http://stackoverflow.com/q/52035496
tags question: http://stackoverflow.com/q/52034573
tags question: http://stackoverflow.com/q/51978077
tag name: kivy-language
tags question: http://stackoverflow.com/q/52017835

http://stackoverflow.com/q/51982306
favorite count: 0
has answer: http://stackoverflow.com/a/51988820
has comment: http://stackoverflow.com/comment/90914772
type: Question
linked to: http://stackoverflow.com/q/48006551
has comment: http://stackoverflow.com/comment/90914871
linked to: http://stackoverflow.com/q/51966096
tagged with: python
tagged with: pyodbc
answer count: 1
accepted answer: http://stackoverflow.com/a/51988820
upvote count: 6
has comment: http://stackoverflow.com/comment/90914500
tagged with: performance
has comment: http://stackoverflow.com/comment/90914655
has title: pyodbc/sqlAchemy enable fast execute many
tagged with: sqlalchemy
linked to: http://stackoverflow.com/q/50689082
downvote count: 0
has body: In response to my question How to speed up data wrangling A LOT in Python + Pandas + sqlAlchemy + MSSQL/T-SQL I was kindly directed to Speeding up pandas.DataFrame.to_sql with fast_executemany of pyODBC by @IljaEverilä. NB For test purposes I am only reading/writing 10k rows. I added the event listener and a) the function is called but b) clearly executemany is not set as the IF fails and cursor.fast_executemay is not set. def namedDbSqlAEngineCreate(dbName): # Create an engine and switch to the named db # returns the engine if successful and None if not # 2018-08-23 added fast_executemany accoding to this https://stackoverflow.com/questions/48006551/speeding-up-pandas-dataframe-to-sql-with-fast-executemany-of-pyodbc?rq=1 engineStr = 'mssql+pyodbc://@' + defaultDSN engine = sqla.create_engine(engineStr, echo=False) @event.listens_for(engine, 'before_cursor_execute') def receive_before_cursor_execute(conn, cursor, statement, params, context, executemany): # print("FUNC call") if executemany: print('executemany') cursor.fast_executemany = True try: engine.execute('USE ' +dbName) return(engine) except sqla.exc.SQLAlchemyError as ex: if ex.orig.args[0] == '08004': print('namedDbSqlAEngineCreate:Database %s does not exist' % dbName) else: print(ex.args[0]) return(None) Naturally there is no change in speed. The code in my original question is unchanged in the to_sql nasToFillDF.to_sql(name=tempTableName, con=engine.engine, if_exists='replace', chunksize=100, index=False) because I tried, per the example, setting chunksize = None and receive the error message (which I had encountered previously) (pyodbc.ProgrammingError) ('The SQL contains -31072 parameter markers, but 100000 parameters were supplied', 'HY000') What have I done wrong? I guess the executemany parameter of the receive_before_cursor_execute is not set, but if that is the answer I have no idea how to fix it. Setup is pyodbc 4.0.23, sqlAchemy 1.2.6, Python 3.6.something
has comment: http://stackoverflow.com/comment/90915648
score: 6
type: AnsweredQuestion

http://stackoverflow.com/q/52054135
favorite count: 0
score: 2
has body: getting the below when trying to import tensorflow: import tensorflow Traceback (most recent call last): File "", line 1, in File "/Applications/PyCharm.app/Contents/helpers/pydev/_pydev_bundle/pydev_import_hook.py", line 20, in do_import module = self._system_import(name, *args, **kwargs) ModuleNotFoundError: No module named 'tensorflow'
type: UnansweredQuestion
has title: Cannot import tensorflow: No module named 'tensorflow'
has answer: http://stackoverflow.com/a/52054333
tagged with: import
type: Question
upvote count: 2
answer count: 2
downvote count: 0
has answer: http://stackoverflow.com/a/52054591
tagged with: python

http://stackoverflow.com/comment/91150207
has text: @mm_nieder So you don't need step 2-4, but I think it can be helpful for other peoples.
score: 0
comment on: http://stackoverflow.com/a/52094518
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/90936000
score: 0
type: AnswerComment
type: Comment
has text: What a beautiful layout. Thank you so much! Learned a lot from your answer.
comment on: http://stackoverflow.com/a/51989032

http://stackoverflow.com/q/52106966
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91174537
tagged with: python
has comment: http://stackoverflow.com/comment/91175898
downvote count: 0
answer count: 0
type: Question
score: 1
tagged with: plotly
has title: Projections of a 3D Surface in R
tagged with: surface
tagged with: 3d
upvote count: 1
has comment: http://stackoverflow.com/comment/91176278
has comment: http://stackoverflow.com/comment/91179166
favorite count: 0
tagged with: http://stackoverflow.com/tag/r
has body: I have created a 3D plot and now I would like to create a heat map of projections of this 3D surface in 2D using R. Here is a reproducible code of the 3D plot that I tried library(plotly) kd &lt;- with(MASS::geyser, MASS::kde2d(duration, waiting, n = 50)) p &lt;- plot_ly(x = kd$x, y = kd$y, z = kd$z) %&gt;% add_surface() I have found a python version of doing this using the same library. https://plot.ly/python/2d-projection-of-3d-surface/

http://stackoverflow.com/q/52009771
has comment: http://stackoverflow.com/comment/90970777
has comment: http://stackoverflow.com/comment/100560008
tagged with: selenium
score: 8
has comment: http://stackoverflow.com/comment/90973871
answer count: 5
type: UnansweredQuestion
tagged with: webdriver
has body: I have the following HTML span: I also have a webElement representing the button containing this span that I have found using xpath. How can I retrieve the aria-label value (Unlike) from the element? I tried to do: btn = drive.find_element(By.xpath, "xpath") btn.get_attribute("aria-label") but it returns nothing. How to retrieve the text value of an element with 'aria-label' attribute from the element object?
has comment: http://stackoverflow.com/comment/90970461
has answer: http://stackoverflow.com/a/58086855
downvote count: 0
has answer: http://stackoverflow.com/a/75543814
has comment: http://stackoverflow.com/comment/90970946
favorite count: 0
has answer: http://stackoverflow.com/a/52011539
has answer: http://stackoverflow.com/a/58504219
upvote count: 8
type: Question
has answer: http://stackoverflow.com/a/52010514
has title: How to retrieve the value of the attribute aria-label from element found using xpath as per the html using Selenium
tagged with: python
tagged with: getattribute
tagged with: selenium-webdriver

http://stackoverflow.com/q/52060954
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/52061095
type: UnansweredQuestion
tagged with: datetime
tagged with: python
score: 1
upvote count: 1
type: Question
tagged with: date-formatting
has body: I am trying to convert a column which has different date formats. For example: month 2018-01-01 float64 2018-02-01 float64 2018-03-01 float64 2018-03-01 00:00:00 float64 2018-04-01 01:00:00 float64 2018-05-01 01:00:00 float64 2018-06-01 01:00:00 float64 2018-07-01 01:00:00 float64 I want to convert everything in the column to just month and year. For example I would like Jan-18, Feb-18, Mar-18, etc. I have tried using this code to first convert my column to datetime: df['month'] = pd.to_datetime(df['month'], format='%Y-%m-%d') But it returns a float64: Out month 2018-01-01 00:00:00 float64 2018-02-01 00:00:00 float64 2018-03-01 00:00:00 float64 2018-04-01 01:00:00 float64 2018-05-01 01:00:00 float64 2018-06-01 01:00:00 float64 2018-07-01 01:00:00 float64 In my output to CSV the month format has been changed to 01/05/2016 00:00:00. Can you please help me covert to just month and year e.g. Aug-18. Thank you
has title: Python to convert different date formats in a column
tagged with: pandas
answer count: 1

http://stackoverflow.com/q/52097861
has title: How to perform a quasirandom shuffle on Python?
favorite count: 0
answer count: 0
type: UnansweredQuestion
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/91146448
linked to: http://stackoverflow.com/q/24433891
has comment: http://stackoverflow.com/comment/91146376
has comment: http://stackoverflow.com/comment/91146101
downvote count: 1
has body: If I have an 2-d numpy array, how can I perform a quasirandom shuffle on it? What I would like to do is have as an input the numpy array, and then have it shuffled in the same way as random.shuffle() would do it, but instead of using pseudorandom approach, use quasirandom approach (for example sobol or halton). It seems there are three parts to this: 1) generating quasirandom sequences (e.g. sobol) 2) mapping the sequence with the data 3) performing the shuffle based on that
type: Question
has comment: http://stackoverflow.com/comment/91146717
score: 0
tagged with: random

http://stackoverflow.com/comment/91003073
type: Comment
has text: @melpomene I'm talking about [the edit you approved](https://stackoverflow.com/review/suggested-edits/20689060).
score: 0
comment on: http://stackoverflow.com/q/52026382
type: QuestionComment

http://stackoverflow.com/comment/90951553
comment on: http://stackoverflow.com/q/51992631
has text: @NChauhan: As currently written, it cannot be more than a comment. But if you elaborate it, it would would probably be the best answer...
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52060332
linked to: http://stackoverflow.com/q/70275565
type: Question
has comment: http://stackoverflow.com/comment/91072068
tagged with: google-colaboratory
has body: I am trying to run some notebooks that make use of gdal library. I have followed instructions to install it, sometimes the step 5 works well and other does not, showing this error message: ModuleNotFoundError: No module named 'gdal' Step 1 $ apt update Step 2 $ apt install libgdal-dev -y Step 3 $ apt install python-gdal -y Step 4 $ apt install python-numpy python-scipy -y Step 5 import gdal # fingers crossed! I have installed gdal library working well on my machine, but I understand, under colaboratory, it install gdal on the server. Any suggestions?
has comment: http://stackoverflow.com/comment/91076041
has comment: http://stackoverflow.com/comment/91076171
has title: GDAL module not found
has comment: http://stackoverflow.com/comment/91085511
upvote count: 2
has comment: http://stackoverflow.com/comment/91087506
has comment: http://stackoverflow.com/comment/91143921
tagged with: jupyter-notebook
favorite count: 0
has comment: http://stackoverflow.com/comment/91071406
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91071908
tagged with: python
score: 2
has comment: http://stackoverflow.com/comment/126703024
answer count: 0
downvote count: 0

http://stackoverflow.com/comment/90978134
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52013760
has text: Does this need to be a list comprehension, or just a one-liner? This is pretty readable and avoids exceedingly fancy moves (and is very similar to your example): `years = [start_year] if start_year == end_year else [start_year, end_year]`
score: 0

http://stackoverflow.com/comment/91048996
type: QuestionComment
has text: I tested that last line can work on my Python 3.6.6 on Windows 10. What's your error message?
type: Comment
comment on: http://stackoverflow.com/q/52049128
score: 0

http://stackoverflow.com/q/52065226
score: 0
type: Question
has title: No axis named 1 for object type <class 'pandas.core.series.Series'>
has comment: http://stackoverflow.com/comment/91081151
has body: I am creating a portfolio that consists of investing 100 000 USD every time I generate my purchase signals. This is my code: initial_capital= float(100000.0) positions = pd.DataFrame(index=signals.index).fillna(0.0) No_acciones = (initial_capital / GFG['Close']).astype(int) positions['GFG'] = No_acciones*signals['signal'] portfolio = positions.multiply(GFG['Close'], axis=0) portfolio['holdings'] =(positions.multiply(GFG['Close'],axis=0)).sum(axis=1) portfolio['cash'] = initial_capital - (positions['GFG'].multiply(GFG['Close'], axis=0)).sum(axis=1).cumsum() portfolio['total'] = portfolio['cash'] + portfolio['holdings'] portfolio['returns'] = portfolio['total'].pct_change() print(portfolio.head()) I get this error and I do not understand why: File "C:\Users\Usuario\Anaconda3\lib\site-packages\pandas\core\generic.py", line 357, in _get_axis_number .format(axis, type(self))) ValueError: No axis named 1 for object type
tagged with: numpy
has comment: http://stackoverflow.com/comment/91081177
tagged with: pandas
tagged with: python
answer count: 0
type: UnansweredQuestion

http://stackoverflow.com/a/51971878
score: 1
upvote count: 1
type: Answer
answers question: http://stackoverflow.com/q/51971502
downvote count: 0
has body: .combine_first is a good way to update values in a DataFrame import pandas as pd # Make datetime df_ETH_price['date'] = pd.to_datetime(df_ETH_price.date) # Find the last valid row + tidy up naming for the join. df_last = (df_ETH_price.locdf_ETH_price.date.idxmax() .add_prefix('last_') .assign(token='ETH') .set_index('token')) df_portfolio = df_last.combine_first(df_portfolio.set_index('token')).reset_index() Output: token amount timestamp exch last_date last_price 0 BTC 3 2013-01-02 e1 NaT NaN 1 ETH 6 2013-01-02 e1 2018-08-13 286.5 2 ETH 4 2013-01-02 e2 2018-08-13 286.5 3 LTC 8 2013-01-02 e2 NaT NaN If you have multiple DataFrames you need to do this for, I'd consider something like: def update_price(df_port, df, token): df_last = (df.locdf.date.idxmax() .add_prefix('last_') .assign(token=token) .set_index('token')) return df_last.combine_first(df_port.set_index('token')).reset_index() then you can simply do something like: df_LTC_price = pd.DataFrame({ 'date': ('2018-08-11','2018-08-12','2018-08-13'), 'price' : (322.11,319.57,280.50) }) df_portfolio = update_price(df_portfolio, df_ETH_price, 'ETH') df_portfolio = update_price(df_portfolio, df_LTC_price, 'LTC') Output: token amount exch last_date last_price timestamp 0 BTC 6.0 e1 NaT NaN 2013-01-02 1 ETH 1.0 e1 2018-08-13 286.5 2013-01-02 2 ETH 3.0 e2 2018-08-13 286.5 2013-01-02 3 LTC 3.0 e2 2018-08-13 280.5 2013-01-02 Because .combine_first gives priority to df_last you can even use it to update df_portfolio with new data for the same token if you receive more data tomorrow for instance.

directed-acyclic-graphs
type: Tag
tags question: http://stackoverflow.com/q/52053980
tag name: directed-acyclic-graphs

http://stackoverflow.com/comment/91040372
type: AnswerComment
has text: I just get a 1 symbol in each line. Actually, tag.text gives me a full text but with no spaces, I must have missed that
comment on: http://stackoverflow.com/a/52044676
type: Comment
score: 0

http://stackoverflow.com/q/51980776
has comment: http://stackoverflow.com/comment/90911591
type: Question
has body: novice here. I am trying to read lines from a file, however a single line in a .txt file has a \n in the middle somewhere and while trying to read that line with .readline python cuts it in the middle and outputs as two lines. when I copy and past the line to this window, it shows up as two lines. So i uploaded the file here: https://ufile.io/npt3n also added screenshot of the file as it shows in txt file. this is group chat history exported from Whatsup..if you are wondering. Please help me to read one line completely as shown in txt file. . f= open("f.txt",mode='r',encoding='utf8') for i in range(4): lineText=f.readline() print(lineText) f.close()
has comment: http://stackoverflow.com/comment/90912066
has comment: http://stackoverflow.com/comment/90911489
has comment: http://stackoverflow.com/comment/90911712
has comment: http://stackoverflow.com/comment/90911897
downvote count: 2
answer count: 2
has comment: http://stackoverflow.com/comment/122580967
possible better answer: http://stackoverflow.com/a/51981112
linked to: http://stackoverflow.com/q/47927039
favorite count: 0
tagged with: end-of-line
upvote count: 18
linked to: http://stackoverflow.com/q/45304492
tagged with: python
has title: Python readline with custom delimiter
tagged with: readline
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/5850986
has answer: http://stackoverflow.com/a/51981112
score: 16
has answer: http://stackoverflow.com/a/51981438
accepted answer: http://stackoverflow.com/a/51981438

http://stackoverflow.com/comment/90958092
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/52004145
has text: please ignore that. I have misunderstood your question.
score: 0

http://stackoverflow.com/q/52060301
type: Question
upvote count: 1
answer count: 1
has comment: http://stackoverflow.com/comment/91149817
tagged with: button
favorite count: 0
has title: Entry box and label not aligned correctly Python 2.7 Tkinter
has comment: http://stackoverflow.com/comment/91071794
has comment: http://stackoverflow.com/comment/91071074
tagged with: python
has body: I have the following Tkinter application which basically helps you to configure a new network just by inserting in the entry box a new value. This value entered by the user it is saved somewhere in a file using the template. This script runs well, but problem is that I am seeing the Tenant entry box upper than Network name entry box. The same is happening with their labels. Then, when we click on the Add network and getting another 2 entry box, are displayed very strange way. How can I align the labels + entry boxes and how can I have them displayed each group of label+entry box one bellow the other? Something like: Tenant [entrybox] Network [entrybox] Tenant [entrybox] Network [entrybox] .................................... import Tkinter as tk class SampleApp(tk.Tk): def __init__(self): tk.Tk.__init__(self) self._frame = None self.networks = [] self.switch_frame(StartPage) def switch_frame(self, frame_class): """Destroys current frame and replaces it with a new one.""" new_frame = frame_class(self) if self._frame is not None: self._frame.destroy() self._frame = new_frame self._frame.pack() class StartPage(tk.Frame): def __init__(self, master): tk.Frame.__init__(self, master) start_label = tk.Label(self, text="This is the start page") network_button = tk.Button(self, text="Create the networks", command=lambda: master.switch_frame(Networks)) start_label.pack(side="top", fill="x", pady=10) deployment_button.pack() network_button.pack() subnet_button.pack() neutronports_button.pack() script_button.pack() class Networks(tk.Frame): def __init__(self, master): tk.Frame.__init__(self, master) self.entries=[] self.create_widgets(master) def create_widgets(self, master): label = tk.Label(self, text="Insert the name of the networks") start_button = tk.Button(self, text="Return to start page", command=lambda: master.switch_frame(StartPage)) new_network_button = tk.Button(self, text="Add network", command=self.add_network) new_network_button.bind("&lt;Return&gt;", self.add_net…
has comment: http://stackoverflow.com/comment/91149779
tagged with: tkinter
downvote count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91071570
has answer: http://stackoverflow.com/a/52092635
score: 1

http://stackoverflow.com/comment/117302219
has text: @Cat you may observe a minimap speedup, but nowhere close to 3x because this is just one layer, and the rest of the network remains the same.
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/54777347
type: Comment

http://stackoverflow.com/comment/91010205
comment on: http://stackoverflow.com/a/52029443
score: 0
type: AnswerComment
has text: It could be different things depending on your encoding, you can try `data = json.dumps(your_list_of_dict).replace(/&quot;/ig,'"');`
type: Comment

http://stackoverflow.com/comment/90875914
comment on: http://stackoverflow.com/q/51962820
score: 1
has text: You *are* doing `number+=number`, which, yes, will concatenate it to itself…
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51962516
linked to: http://stackoverflow.com/q/46894174
has answer: http://stackoverflow.com/a/51962612
favorite count: 0
upvote count: 2
type: UnansweredQuestion
has title: How do I fix my 'Jump'?
tagged with: python
tagged with: pygame
has body: I am new to this website and pygame so bear with me. I am experimenting with pygame and made a simple platformer. However, whenever I 'Jump', the block jumps frame by frame, so I have to hold down the spacebar. Any help would be greatly appreciated! here is my code: import pygame pygame.init() win = pygame.display.set_mode((500, 500)) x = 0 y = 490 width = 10 height = 10 vel = 5 pygame.key.set_repeat(1) isjump = False jumpcount = 10 while True: pygame.time.delay(30) for event in pygame.event.get(): if event.type == pygame.QUIT: break keys = pygame.key.get_pressed() if keys[pygame.K_a] and x&gt;vel-5: x -= vel if keys[pygame.K_d] and x &lt; 500 - width: x += vel if not(isjump): if keys[pygame.K_SPACE]: isjump = True else: if jumpcount &gt;= -10: neg = 1 if jumpcount &lt; 0: neg = -1 y -= (jumpcount ** 2) /2 * neg jumpcount -= 1 else: isjump = False jumpcount = 10 win.fill((0, 0, 0)) pygame.draw.rect(win, (255, 255, 255), (x, y, width, height)) pygame.display.update() pygame.quit()
has comment: http://stackoverflow.com/comment/90875234
score: 2
type: Question
answer count: 2
downvote count: 0
has answer: http://stackoverflow.com/a/51963253

http://stackoverflow.com/a/52026772
upvote count: 3
answers question: http://stackoverflow.com/q/52026060
has comment: http://stackoverflow.com/comment/91009885
has comment: http://stackoverflow.com/comment/91007763
type: AcceptedAnswer
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/91004073
has body: Rather than using self.get_children().type(Event), use Event.objects.child_of(self). This is necessary because get_children returns objects of type Page, the basic record common to all page types. The type(Event) clause will limit that queryset to just Event pages, but will still leave them as Page objects, where the date field isn't available. By using Event.objects.child_of(self), you ensure that you're using the full Event model all the way through the query. Also, make sure that your filter clause refers to a field that's defined on your model; rather than date_range, it should probably be start_range or end_range. Or, if you want it to return events that are happening at some point in the next 7 days, you're really looking for ones that start before [today + 7 days] and end after today, which would make the filter: .filter(start__lte='2018-08-31', end__gte='2018-08-25') To limit the query to a maximum of 10 items, use Python array slicing notation: [:10] This makes the final events line as follows: events = Event.objects.child_of(self).filter(start__lte='2018-08-31', end__gte='2018-08-25').live().order_by('start')[:10]
score: 3
accepted answer of: http://stackoverflow.com/q/52026060

http://stackoverflow.com/a/51960210
downvote count: 1
type: Answer
answers question: http://stackoverflow.com/q/51960151
has body: You might consider using re.search (which scans) instead of re.match, which only looks at the beginning of the string. You could instead add a .* to the start.
has comment: http://stackoverflow.com/comment/90892157
score: 0
upvote count: 1

http://stackoverflow.com/q/52018663
accepted answer: http://stackoverflow.com/a/52018799
favorite count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/90993793
has body: &gt;&gt;&gt; image = np.arange(20).reshape((4, 5)) &gt;&gt;&gt; image array([[ 0, 1, 2, 3, 4], [ 5, 6, 7, 8, 9], [10, 11, 12, 13, 14], [15, 16, 17, 18, 19]]) &gt;&gt;&gt; idx = [[2, 1], [2, 3], [3, 4]] How do I get the values from the image array which coordinate is specified in idx? From the above code, I want to get the values 11 (image[2, 1]), 13 (image[2, 3]), and 19 (image[3, 4]). Thank you.
type: AnsweredQuestion
score: 1
has answer: http://stackoverflow.com/a/52020438
type: Question
tagged with: numpy
answer count: 2
downvote count: 0
has title: How to get 2D array values based on 1D array values?
possible better answer: http://stackoverflow.com/a/52020438
has answer: http://stackoverflow.com/a/52018799
tagged with: python

http://stackoverflow.com/comment/91150826
has text: @Keselme, are you sure you typed `datetime.datetime.now().tzinfo` and not `datetime.datetime.now().tz_info`?
type: Comment
comment on: http://stackoverflow.com/q/52099464
type: QuestionComment
score: 0

http://stackoverflow.com/q/51970871
has body: Hi can anyone covert the following code to an nd array. I have imported panda as pd. This is python. def predict(self): ohlcv_candles = pd.DataFrame(self.client.Trade.Trade_getBucketed( binSize=self.timeframe, symbol='XBTUSD', count=100, reverse=True ).result()[0])
has comment: http://stackoverflow.com/comment/90892851
upvote count: 1
type: Question
score: 1
has comment: http://stackoverflow.com/comment/90892158
has comment: http://stackoverflow.com/comment/90895965
downvote count: 0
tagged with: algorithmic-trading
has comment: http://stackoverflow.com/comment/90892428
favorite count: 0
has title: BitMEX panda dataframe to nd array
tagged with: python
has comment: http://stackoverflow.com/comment/90892837
answer count: 0
type: UnansweredQuestion

http://stackoverflow.com/comment/91151111
has text: can you write it as an answer not a comment? I corrected it and it works but I didn't understand why it should be indexed by field name, not column number (even though I took a look at structured arrays in numpy documentation.
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/52093890
type: Comment

http://stackoverflow.com/q/52014762
tagged with: editor
type: AnsweredQuestion
upvote count: 0
has body: I'm trying to remove stopwords using a text file that includes my own stop words and trying to make a new list without stopwords in them. However, the new list does not remove the stopwords. def remove_stopwords(parametera): stopwords = open('myownstopwords.txt') stopwords_list = stopwords.readlines() new_list = [] for parametera in stopwords_list: if parametera not in stop_list: new_list.append(parametera) stopwords.close() new_list.close() print(new_list) Any ideas on fixing it? Do I have to list out all the stopwords from the text file or can I just import it?
has comment: http://stackoverflow.com/comment/90979944
type: Question
has comment: http://stackoverflow.com/comment/90979863
has comment: http://stackoverflow.com/comment/90982170
downvote count: 3
has comment: http://stackoverflow.com/comment/90980518
answer count: 1
accepted answer: http://stackoverflow.com/a/52015032
favorite count: 0
has title: How do I remove stopwords from a list using a text file
score: -3
has answer: http://stackoverflow.com/a/52015032
has comment: http://stackoverflow.com/comment/90979965
has comment: http://stackoverflow.com/comment/90979889
tagged with: python
has comment: http://stackoverflow.com/comment/90980214

http://stackoverflow.com/q/52014588
linked to: http://stackoverflow.com/q/3249524
has title: python replace linebreaks with string while reading from file
has body: I have a file named "test.txt" which contains the below content: hello hi bye for now I am using the below code to replace the linebreaks with comma (,) in the file: with open("test.txt", "r") as data: for each_line in data: try: name = each_line.replace("\n", ",").strip() print(name) except ValueError: pass This shows the result: hello, hi, bye for now But my desired result should be: hello,hi,bye for now How can i achieve this?
upvote count: 1
tagged with: string
favorite count: 0
type: UnansweredQuestion
tagged with: python
duplicate of: http://stackoverflow.com/q/3249524
answer count: 0
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/90979529
has comment: http://stackoverflow.com/comment/90979506
type: Question

http://stackoverflow.com/q/52055842
has comment: http://stackoverflow.com/comment/91062190
tagged with: devops
tagged with: shell
has comment: http://stackoverflow.com/comment/91062813
has comment: http://stackoverflow.com/comment/91061908
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91062153
upvote count: 1
tagged with: python
linked to: http://stackoverflow.com/q/46244850
score: 1
has comment: http://stackoverflow.com/comment/103740434
has title: How to send data stored in a variable to HDFS in python
type: Question
has answer: http://stackoverflow.com/a/52056180
answer count: 1
downvote count: 0
tagged with: hdfs
has body: Example: data = "my first program" How can I write the data of this variable in hdfs file using python? I have tried using: command = 'echo $data | hdfs dfs -put - /user/test/abc.txt' os.system(command)`
has comment: http://stackoverflow.com/comment/91062367
favorite count: 0
has comment: http://stackoverflow.com/comment/91062611
has comment: http://stackoverflow.com/comment/91063920

http://stackoverflow.com/q/52084458
upvote count: 5
has title: Selenium error message "selenium.webdriver has no attribute execute script"
has answer: http://stackoverflow.com/a/74187081
possible better answer: http://stackoverflow.com/a/52084638
answer count: 4
accepted answer: http://stackoverflow.com/a/52088244
linked to: http://stackoverflow.com/q/42524114
downvote count: 0
linked to: http://stackoverflow.com/q/17436598
type: AnsweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/91125154
favorite count: 0
tagged with: driver
tagged with: selenium-webdriver
has body: I am using selenium to scrape an infinite scrolling page. I am trying to use this code: import time import pandas as np import numpy as np from selenium import webdriver from selenium.webdriver.common.keys import Keys from selenium.webdriver.common.by import By browser = webdriver.Chrome() url = 'https://twitter.com/search?f=tweets&amp;q=csubwaystats%20since%3A2018-05-28%20until%3A2018-08-28' browser.get(url) time.sleep(1) SCROLL_PAUSE_TIME = 0.5 # Get scroll height last_height = webdriver.execute_script("return document.body.scrollHeight") while True: # Scroll down to bottom webdriver.execute_script("window.scrollTo(0,document.body.scrollHeight);") # Wait to load page time.sleep(SCROLL_PAUSE_TIME) # Calculate new scroll height and compare with last scroll height new_height = webdriver.execute_script("return document.body.scrollHeight") if new_height == last_height: break last_height = new_height I obtained this code from multiple sources, the most recent being: How can I scroll a web page using selenium webdriver in python? I updated it to include "webdriver" instead of "driver" because I import selenium as webdriver. It doesn't work otherwise. My issue is that when I run the code I get: AttributeError: module 'selenium.webdriver' has no attribute 'execute_script' I don't really understand what this means and how to fix it? I haven't been able to find information on this. I am new to python and so am probably missing something obvious but any advice would be appreciated.
linked to: http://stackoverflow.com/q/20986631
has answer: http://stackoverflow.com/a/52084933
type: Question
score: 5
tagged with: selenium
has answer: http://stackoverflow.com/a/52088244
has comment: http://stackoverflow.com/comment/91124912
has answer: http://stackoverflow.com/a/52084638

http://stackoverflow.com/q/51969283
tagged with: export-to-csv
has answer: http://stackoverflow.com/a/51969551
tagged with: pandas
answer count: 1
downvote count: 0
favorite count: 0
tagged with: python-3.x
has title: Exporting List column to csv from Pandas dataframe drops commas
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/48553303
tagged with: python
score: 2
tagged with: list
upvote count: 2
type: Question
has body: My pandas dataframe has a column with list values ("indices"): When I export this to as df.to_csv(fileout, quotechar='"', encoding='ascii'), values in the exported file drop the commas embedded in the list: I'm using jupyter/Python 3.x What am I doing wrong?
duplicate of: http://stackoverflow.com/q/48553303

http://stackoverflow.com/comment/90939758
type: QuestionComment
comment on: http://stackoverflow.com/q/51995053
score: 0
has text: Don't you actually want `value.split("-")`?
type: Comment

http://stackoverflow.com/comment/91097395
comment on: http://stackoverflow.com/q/52073181
type: QuestionComment
score: 1
has text: @Rajagopalan , Yep. of course. That was hasty decision :)
type: Comment

http://stackoverflow.com/a/52002840
answers question: http://stackoverflow.com/q/52002733
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/90954769
has comment: http://stackoverflow.com/comment/90954908
type: Answer
has comment: http://stackoverflow.com/comment/90954873
score: 2
upvote count: 2
has body: The problem is that add_subplot has three mandatory arguments, not two. The arguments are M = "number of rows", N = "number of columns", and P = "item selection". The last one (P) is the linear index in the MxN grid, going across. Additionally, the axis_bg and axis_bgcolor arguments were deprecated in matplotlib 2.0.0 and removed in matplotlib 2.2.0. Instead, use facecolor or fc for short. You probably wanted to do graph1 = fig.add_subplot(1, 1, 1, fc="black") That being said, if you want to create a single set of axes on a figure, I have generally found it easier to use plt.subplots to make the figure and axes in one shot: fig, graph1 = plt.subplots(subplot_kw={'facecolor': 'black'}, facecolor='green') For convenience, it is most common to import pyplot as plt, either with import matplotlib.pyplot as plt or with from matplotlib import pyplot as plt All combined, your code could end up looking like this: from matplotlib import pyplot as plt fig, graph1 = plt.subplots(subplot_kw={'facecolor': 'black'}, facecolor='green') x = [3, 7, 8, 12] y = [5, 13, 2, 8] graph1.plot(x, y, "red", linewidth=4.0) plt.show()
accepted answer of: http://stackoverflow.com/q/52002733

http://stackoverflow.com/q/51961892
type: Question
score: 0
accepted answer: http://stackoverflow.com/a/51962392
answer count: 1
tagged with: python
type: AnsweredQuestion
tagged with: list
has comment: http://stackoverflow.com/comment/90874632
has title: checking the index of a list according to similar items within the list and then append into another list based on the dimension of the list
has body: [Updated] Recently, I am trying to find the index of a 2D list. For example, I have an input as below: a = [["text", "man","chest","funny"],["cruel", "jut","for","teting"],["I", "take","this","for"],["learning", "purpose","only","please"] ] b = [["text", "funny"], ["cruel"],["I", "take", "for"],["learning", "purpose"]] I tried to find the index that have the similar items for both a and b by using the code below(The indent might be wrong due to copy and paste, please adjust accordingly): store = [] for i in a: for u in i: for ii in b: for uu in b: for iu in uu: if iu in u: store.append(i.index(iu)) Somehow, my output became something like this: Output now: store = [0, 0, 0, 0, 3, 3, 3, 3, 0, 0, 0, 0, 2, 2, 2, 2, 0, 0, 0, 0, 1, 1, 1, 1, 3, 3, 3, 3, 0, 0, 0, 0, 1, 1, 1, 1] I dont get how come it has so many of the similar index appearing. Since it was supposed to be a 2D. May I know whether is there a way to make it be like this: Expected output: store = [[0,3],[0],[0,1,3],[0,1]] Please assist me in solving this issue. Thank you
has answer: http://stackoverflow.com/a/51962392

http://stackoverflow.com/a/52057276
has body: Supposing you get a response that you want as proper xml object: rt = resp.text.encode('utf-8') # printed rt is something like: '&lt;soap:Envelope xmlns:soap="http://..."&gt; &lt;soap:Envelope &lt;AirShoppingRS xmlns="http://www.iata.org/IATA/EDIST" Version="16.1"&gt; &lt;Document&gt;...&lt;/soap:Envelope&lt;/soap:Envelope&gt;' # striping soapEnv startTag = '&lt;AirShoppingRS ' endTag = '&lt;/AirShoppingRS&gt;' trimmed = rt[rt.find(startTag): rt.find(endTag) + len(endTag)] # parsing from lxml import etree as et root = et.fromstring(trimmed) With this root element you can use find method, xpath or whatever you prefer. Obviously you need to change the start and endtags to extract the correct element from the response but you get the idea, right?
type: Answer
has comment: http://stackoverflow.com/comment/91066492
accepted answer of: http://stackoverflow.com/q/52056032
has comment: http://stackoverflow.com/comment/91066403
answers question: http://stackoverflow.com/q/52056032
score: 0
type: AcceptedAnswer

http://stackoverflow.com/a/55841769
upvote count: 2
downvote count: 0
answers question: http://stackoverflow.com/q/52085191
type: Answer
score: 2
has body: It seems you have already installed the pyodbc module, but are trying to reference it from another environment. Some Steps: In the Solution Explorer window right-click Python Environments select add/remove choose your desired python interpreter. Refer: How to switch your project python environment to the one which includes pyodbc

http://stackoverflow.com/comment/91154608
has text: I've updated my answer to make use of the `pattern` list.
comment on: http://stackoverflow.com/a/52101599
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/q/52046102
tagged with: performance
possible better answer: http://stackoverflow.com/a/52051085
upvote count: 3
has answer: http://stackoverflow.com/a/52051085
has body: Notable details Large datasets (10 million x 5), (200 x 10 million x 5) Numpy mostly Takes longer after every run Using Spyder3 Windows 10 First thing is attempting to use guvectorize with the following function. I am passing in a bunch of numpy arrays and attempting to use them to multiply across two of the arrays. This works if run with a target other than cuda. However, when switched to cuda it results in an unknown error being: File "C:\ProgramData\Anaconda3\lib\site-packages\numba\cuda\decorators.py", >line 82, in jitwrapper debug=debug) TypeError: init() got an unexpected keyword argument 'debug' After following all that I could find from this error, I hit nothing but dead ends. I'm guessing it's a really simple fix that I'm completely missing but oh well. It should also be said that this error only occurs after running it once and having it crash due to memory overload. os.environ["NUMBA_ENABLE_CUDASIM"] = "1" os.environ["CUDA_VISIBLE_DEVICES"] = "10DE 1B06 63933842" ... All of the arrays are numpy @guvectorize(['void(int64, float64[:,:], float64[:,:], float64[:,:,:], int64, int64, float64[:,:,:])'], '(),(m,o),(m,o),(n,m,o),(),() -&gt; (n,m,o)', target='cuda', nopython=True) def cVestDiscount (ed, orCV, vals, discount, n, rowCount, cv): for as_of_date in range(0,ed): for ID in range(0,rowCount): for num in range(0,n): cv[as_of_date][ID][num] = orCV[ID][num] * discount[as_of_date][ID][num] Attempting to run the code with nvprofiler in command line results in the following error: Warning: Unified Memory Profiling is not supported on the current configuration because a pair of devices without peer-to-peer support is detected on this ?multi-GPU setup. When peer mappings are not available, system falls back to using zero-copy memory. It can cause kernels, which access unified memory, to run slower. More details can be found at: http://docs.nvidia.com/cuda/cuda-c-programming-guide/index.html#um-managed-memory I realized that I am using SLI enabled graphics cards (b…
tagged with: nvprof
downvote count: 0
type: Question
has answer: http://stackoverflow.com/a/52132523
type: AnsweredQuestion
score: 3
tagged with: python
has comment: http://stackoverflow.com/comment/91043828
has comment: http://stackoverflow.com/comment/91043644
favorite count: 0
linked to: http://stackoverflow.com/q/49646182
answer count: 2
tagged with: numba
has title: Numba and guvectorize for CUDA target: Code running slower than expected
has comment: http://stackoverflow.com/comment/91070982
tagged with: cuda
accepted answer: http://stackoverflow.com/a/52132523

http://stackoverflow.com/q/52068525
answer count: 1
downvote count: 0
tagged with: pandas
accepted answer: http://stackoverflow.com/a/52068579
tagged with: recommendation-engine
favorite count: 0
upvote count: 2
tagged with: machine-learning
tagged with: python
type: AnsweredQuestion
has body: I have a pandas dataframe (Interactions dataframe) with columns as User, Item, Rating. Ratings ItemID UserID 1 1172952 A74 1 1178735 176 4 341785 70C 3 136771 67E 2 1178883 383 Let's say I have two more dataframes with 200 users and 1000 ietms respectively. The problem is that in interactions dataframe, i need ratings for each user and each item combination. 0 rating for user/item combination if there is no interaction available for that user and item in interactions dataframe. I have tried using a loop like this: item_ids = np.repeat(item_data.id.values, len(user_data.id.values)) user_ids = np.tile(user_data.id.values, len(item_data.id.values)) ratings = np.empty([len(item_ids)]) for i in range(len(ratings)): inter = interactions.loc[(interactions['UserID'] == user_ids[i]) &amp; (interactions["ItemID"] == item_ids[i]), "Ratings"] if not inter.empty: ratings[i] = inter.values[0] else: ratings[i] = 0 interactions = np.stack((ratings, item_ids, user_ids), axis=-1) But it takes 40 seconds to complete for a ratings array of just 30,000 rows. Is there a quick way of doing this? Thanks for help.
type: Question
tagged with: numpy
has answer: http://stackoverflow.com/a/52068579
has title: Generating User / Item interactions
score: 2

http://stackoverflow.com/comment/90964863
score: 0
has text: See the response below.
comment on: http://stackoverflow.com/q/52004980
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51972734
tagged with: django
tagged with: python
has title: Default list of dicts using JSONField in Django
has answer: http://stackoverflow.com/a/51973312
type: Question
has body: Django 2.0, Django-Rest-Framework 3.8, Python 3.6 I'm using a Postgres database and am trying to set up the following as a default value for the JSONField: from django.db import models from django.contrib.postgres.fields import JSONField class TrainerProfile(models.Model): """data required to pull up trainer profile""" specific_workouts = JSONField(default=[{"specific": "standard session", "price": 100.00, "units": 1, "hours_per_unit": 1}, {"specific": "standard session", "price": 250.00, "units": 3, "hours_per_unit": 1}, {"specific": "standard session", "price": 300.00, "units": 5, "hours_per_unit": 1}]) def __str__(self): return str(self.specific_workouts) From the Django docs, it reads: If you give the field a default, ensure it’s a callable such as dict (for an empty default) or a callable that returns a dict (such as a function). Incorrectly using default={} creates a mutable default that is shared between all instances of JSONField. I want to provide a list containing dicts as the default. I'm allowed to post a list of dicts through raw data or the browsable api in Django Rest Framework, but I need to know how to set this up by default. I want it to post this as the default: "specific_workouts": [ { "price": 100.0, "units": 1, "specific": "standard session", "hours_per_unit": 1 }, { "price": 250.0, "units": 3, "specific": "standard session", "hours_per_unit": 1 }, { "price": 300.0, "units": 5, "specific": "standard session", "hours_per_unit": 1 } ] I'm guessing I have to override save() to do this, but I'm not sure how to actually implement that. Any help is greatly appreciated. Update I've tried implementing the following and am still being returned a null value as the default. from django.db import models from django.contrib.postgres.fields import JSONField def default_specific_workouts(): return [ { "price": 100.0, "units": 1, "specific": "standard session", "hours_per_unit": 1 }, { "price": 250.0, "units": 3, "specific": "standard session", "hours_per_unit…
score: 9
upvote count: 9
tagged with: django-rest-framework
answer count: 1
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/115347077
type: UnansweredQuestion

http://stackoverflow.com/a/51979178
upvote count: 7
answers question: http://stackoverflow.com/q/51978816
type: Answer
has body: Both environments are based on python's virtualenv, you can use them independently and configure (or install) packages inside it as you need, without the worry of conflicts. This is the essence of virtualenv. Anaconda is a python distribution (just like linux distros) it by default add other packages based of it's opinion of what developers need. Hence, the installation is larger than if you install plain vanilla python. This is also why it's virtual environment is quite large. Pycharm is an IDE, which happens to support the virtualenv feature of python. So it can create it for you, if you wish. It can use plain python distro to create it, so this will have a smaller size than if it uses a distro like Anaconda, as you have noticed. The size issue is not specific to Anaconda, if you list all packages installed for you by anaconda conda list and install it manually yourself in the "lightweight" virtualenv you will see the size go up too. I believe you get my point.
downvote count: 2
score: 5

http://stackoverflow.com/comment/91084375
comment on: http://stackoverflow.com/a/52047706
type: AnswerComment
has text: Cool. tf.contrib.learn.Estimator and tf.estimator.Estimator are different. you can not mix and match.
type: Comment
score: 0

http://stackoverflow.com/q/51995696
favorite count: 0
upvote count: 2
has comment: http://stackoverflow.com/comment/90954269
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51996045
has answer: http://stackoverflow.com/a/51995804
tagged with: python
score: 2
has body: I know how to debug a flask application in Pycharm. The question is whether this is also possible in IntelliJ. I have my flask application debugging in Pycharm but one thing I could do in IntelliJ was evaluate expressions inline by pressing the alt + left mouse click. This isn't available in Pycharm so I wanted to run my Flask application in IntelliJ but there isn't a Flask template. Is it possible to add a Flask template to the Run/Debug configuration? I tried looking for a plugin but couldn't find that either.
type: Question
tagged with: intellij-idea
duplicate of: http://stackoverflow.com/q/51669527
linked to: http://stackoverflow.com/q/17309889
tagged with: flask
answer count: 2
duplicate of: http://stackoverflow.com/q/17309889
has title: Can I debug Flask applications in IntelliJ?
downvote count: 0

http://stackoverflow.com/comment/91030350
type: Comment
has text: Yes. It should be. Honestly though I didn't notice your Numpy answer until just a moment ago. I'm going to delete this and leave a comment on yours.
comment on: http://stackoverflow.com/a/52039942
score: 0
type: AnswerComment

http://stackoverflow.com/q/52071480
score: 2
type: AnsweredQuestion
downvote count: 0
type: Question
tagged with: matching
has body: I am trying to understand why the in operator below does not also match and print (4, 'foobar'), and ('foobar', 5) (it matches the rest). Trying to nail down my understanding of the in with tuples. I was trying to match all tuples that had "foo" or "bar", or "foobar" in any part of the tuple. ls = [(1, 'foo'), ('bar2'), ('foo', 'bar', 3), (4, 'foobar'), ('foobar', 5), ('foobar')] print [x for x in ls if 'foo' in x or 'bar' in x] [(1, 'foo'), 'bar2', ('foo', 'bar', 3), 'foobar']
has title: Using in operator to match items in a tuple
has answer: http://stackoverflow.com/a/52071552
upvote count: 2
answer count: 2
accepted answer: http://stackoverflow.com/a/52071595
favorite count: 0
tagged with: tuples
has answer: http://stackoverflow.com/a/52071595
tagged with: python
has comment: http://stackoverflow.com/comment/91092730
possible better answer: http://stackoverflow.com/a/52071552

http://stackoverflow.com/comment/90945687
has text: I have handled it. I will post it as an answer
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51997925

http://stackoverflow.com/a/52043356
upvote count: 7
answers question: http://stackoverflow.com/q/52043311
score: 7
has body: The problem is that you did not understand python classes, you are referring to a global scoped name feed_pet but you meant to call the function within the class, for that you need to use self, check the changes below: class Animal: def __init__(self): self.action = {'feed':self.feed_pet} def do_action(self, a): self.action[a]() //use self also for access instance attributes def feed_pet(self): print('Gives some food') # main.py from animal import * my_pet = Animal() my_pet.do_action('feed') For making it clear, Does Python support forward declaration in class? There is no need for forward declarations in python, unlike C you can redefine any object as many times as you want, python will keep the last one of them as the live ones. Also, as it does not have static typing at compile time, you can use any variable as any type, hence you don't need to declare anything to use it, just at runtime have to be in the same scope.
type: AcceptedAnswer
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/52043311

http://stackoverflow.com/a/52040735
type: AcceptedAnswer
has body: As alluded to in the comments, this turned out to be a Canopy problem. Specifically, when it uses tk for the Pylab backend (option in Preferences/Python). Switching it from tk eliminated the problem.
type: Answer
answers question: http://stackoverflow.com/q/52007906
accepted answer of: http://stackoverflow.com/q/52007906
score: 0

http://stackoverflow.com/a/72740411
has body: writer = pd.ExcelWriter(excel_file_name, engine='xlsxwriter') worksheet = writer.sheets[sheet_name] worksheet.add_table(start_row,start_col,end_row,end_col,{'style':'Table style light 16','header_row': False}) start_row is where your starting row of excel from where your table starts, start_col is the same as start_row, and end_row is start_row+(len(data frame)) and end_col is start_col + len(data frame.columns)
type: Answer
answers question: http://stackoverflow.com/q/52052184
downvote count: 0
score: 1
upvote count: 1

http://stackoverflow.com/q/51958293
has comment: http://stackoverflow.com/comment/90867087
has answer: http://stackoverflow.com/a/51958421
score: 0
has comment: http://stackoverflow.com/comment/90867104
answer count: 1
has title: Between last line of a while loop and the first line of re-entry of a while loop, variable seems to change/disappear
has comment: http://stackoverflow.com/comment/90867198
type: UnansweredQuestion
tagged with: python
has body: Stuck on LeetCode problem 94. Binary Tree Inorder Traversal (Python). Here is the problem https://leetcode.com/problems/binary-tree-inorder-traversal/description/ My issue is, at the last line inside a while loop, there is clearly a node assigned to variable 'node'. But on the very first line, it says nothing is assigned to variable 'node'. Also, this only seems to happen after a few loops through the while loop. What could be happening between the first line and the last line? For the first few loops, the value of 'node' is exactly the same between the first line and last line of the while loop. On the 3rd time, a change occurs. Here is the solution I can up so far # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def inorderTraversal(self, root): """ :type root: TreeNode :rtype: List[int] """ res = [] rootTrack = [] rootCovered = [] rootTrack.append(root) i=0 while rootTrack: print('right after while loop re-enter', root.val) while root.left and root.left not in rootCovered: root = root.left print('left value ', root.val) rootTrack.append(root) if len(rootTrack) &gt; 0: root = rootTrack.pop() res.append(root.val) rootCovered.append(root) print('pop value ', root.val) if root.right and root.right not in rootCovered: root = root.right print('right value ', root.val) rootTrack.append(root) print('final before while loop re-enter ', root.val) return res Here is the error message it gives me Line 23: AttributeError: 'NoneType' object has no attribute 'val' which refers to this line of code print('right after while loop re-enter', root.val) Here is the stdout right after while loop re-enter 1 pop value 1 right value 2 final before while loop re-enter 2 right after while loop re-enter 2 left value 3 pop value 3 final before while loop re-enter 3 right after while loop re-enter 3 pop value 2 final before while loop re-enter 2 From the print statements, you can tell that the…
type: Question
has comment: http://stackoverflow.com/comment/90867154

http://stackoverflow.com/comment/91081544
type: Comment
has text: Ah I see, I misunderstood what the keys lining up meant then. Thanks for clarifying. Best to delete this answer?
comment on: http://stackoverflow.com/a/52065406
type: AnswerComment
score: 0

http://stackoverflow.com/q/51989857
answer count: 2
tagged with: django-rest-framework
has comment: http://stackoverflow.com/comment/90931527
accepted answer: http://stackoverflow.com/a/51991054
tagged with: django
tagged with: python
has title: Put request 403 error django restframework
has comment: http://stackoverflow.com/comment/90933257
has answer: http://stackoverflow.com/a/57049453
type: AnsweredQuestion
has body: I am creating a web application with react-js using redux and back-end with python django with django rest framework. for authentication I am using JWT. The problem I am facing is when sending request from front-end getting error as 403. I have checked the backend side all the configuration are set but still getting this error. Please check the below code. Model: class StatusQuerySet(models.QuerySet): pass class StatusManager(models.Manager): def get_queryset(self): return StatusQuerySet(self.model,using=self._db) class Apptype(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) appType = models.CharField(max_length=50) objects = StatusManager() def __str__(self): return self.appType Serializer: class AppTypeSeriializer(serializers.ModelSerializer): class Meta: model = Apptype fields = [ 'user', 'id', 'appType' ] read_only_fields = ['user','id'] views class AppTypeStatusAPIDetailView( mixins.UpdateModelMixin, mixins.DestroyModelMixin, generics.RetrieveAPIView): lookup_field = 'id' permission_classes = [permissions.IsAuthenticatedOrReadOnly] serializer_class = AppTypeSeriializer queryset = Apptype.objects.all() def put(self,request, *args, **kwargs): print("Value of = ",request.data.get("appType")) return self.update(request, *args, **kwargs) def patch(self,request, *args, **kwargs): return self.update(request, *args, **kwargs) def delete(self,request, *args, **kwargs): return self.destroy(request, *args, **kwargs) URL urlpatterns = [ url(r'^appType/$',AppTypeStatusView.as_view()), url(r'^appType/(?P&lt;id&gt;\d+)/$',AppTypeStatusAPIDetailView.as_view()), ] Permissions REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.SessionAuthentication', 'rest_framework_jwt.authentication.JSONWebTokenAuthentication', ), 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ) } JWT_AUTH = { 'JWT_ENCODE_HANDLER': 'rest_framework_jwt.utils.jwt_encode_handler', 'JWT_DECODE_HANDLER': 'r…
has answer: http://stackoverflow.com/a/51991054
type: Question
tagged with: reactjs
tagged with: django-models
has comment: http://stackoverflow.com/comment/90931813
score: 0
possible better answer: http://stackoverflow.com/a/57049453

http://stackoverflow.com/comment/90974170
has text: There was a typo in my answer (`df.series`). Try this one.
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/51997518
type: Comment

http://stackoverflow.com/q/52064496
has answer: http://stackoverflow.com/a/52064722
tagged with: python-3.x
has title: Not able to successfully parse python regex from reading the contents of a file
possible better answer: http://stackoverflow.com/a/52064636
has answer: http://stackoverflow.com/a/52064636
downvote count: 3
has comment: http://stackoverflow.com/comment/91079946
type: Question
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91079653
accepted answer: http://stackoverflow.com/a/52064722
score: -3
has body: I've got an issue where my regex isn't parsing the output of a file I created: #!/usr/bin/env python3 import wget, re url='' filename=wget.download(url) with open ('Output.txt', "r") as f: readlines=f.read() ret=re.sub("^.*\^", "", readlines) print(ret) According to this site, the regex I'm using "^.*\^" is valid for my output. Sample output I'm feeding it is something like this: 1212-2010^readthispart Where it has a carot for a delimiter. I tried double and single quotes to no avail and I'm not sure if it's an issue elsewhere in my code or what, but the printout does not match what I'm looking for. Ideas?
answer count: 2
upvote count: 0
has comment: http://stackoverflow.com/comment/91079931
has comment: http://stackoverflow.com/comment/91080824
favorite count: 0
tagged with: python
tagged with: regex
has comment: http://stackoverflow.com/comment/91079874

http://stackoverflow.com/comment/91137248
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/52093555
has text: The first related question on the right side: https://stackoverflow.com/q/123559/8881141

http://stackoverflow.com/q/51971756
has answer: http://stackoverflow.com/a/51972135
accepted answer: http://stackoverflow.com/a/51972135
has title: Is it possible to return both a dictionary or series as well as a dataframe from a function?
favorite count: 0
possible better answer: http://stackoverflow.com/a/51972408
tagged with: pandas
has answer: http://stackoverflow.com/a/51972408
tagged with: python
has body: I have a function that takes data and does calculations and appends them to a data frame. At the end, I make a dictionary that returns averages/max/mins etc from several of the columns. It'll essentially be a summary of the final data frame. I would like to have the function return both the summary as well as the data frame so i can use each in a different subsequent function. Is this doable?
tagged with: python-3.x
downvote count: 0
has comment: http://stackoverflow.com/comment/90894039
type: Question
type: AnsweredQuestion
score: 1
tagged with: dataframe
tagged with: numpy
answer count: 2
upvote count: 1

http://stackoverflow.com/comment/91035796
has text: Have a look at https://stackoverflow.com/questions/44204937/is-there-any-way-to-override-pythons-built-in-class
type: QuestionComment
comment on: http://stackoverflow.com/q/52042234
type: Comment
score: 1

http://stackoverflow.com/comment/91147590
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52072814
has text: Did you remove the "Apps" filter?

http://stackoverflow.com/q/52062368
has title: tf.boolean_mask got Number of mask dimensions must be specified
tagged with: tensorflow
type: Question
upvote count: 4
downvote count: 0
answer count: 1
has answer: http://stackoverflow.com/a/71215335
has body: Tensor shape become (?,) after >= 80. Which caused error on boolean_mask. Following code are to filter out those accuracy above 80%. outputs, final_state = tf.contrib.rnn.static_rnn(cell, lstm_in, dtype=tf.float32, initial_state = initial_state) logits = tf.layers.dense(outputs[-1], n_classes, name='logits') np_logits_b = tf.reduce_max(outputs[-1], axis=1) &gt;= 80 labels_filtered = tf.boolean_mask(labels_, np_logits_b) &lt;ipython-input-13-2615e31971df&gt; in &lt;module&gt;() 23 # Accuracy on &gt;80% 24 np_logits_b = tf.reduce_max(logits, axis=1) &gt;= 80 ---&gt; 25 labels_filtered = tf.boolean_mask(labels_, np_logits_b) 26 correct_pred_filtered = tf.equal(tf.argmax(logits_filtered, 1), tf.argmax(labels_filtered, 1)) 27 accuracy_filtered = tf.reduce_mean(tf.cast(correct_pred_filtered, tf.float32), name='accuracy_filtered') ~\Anaconda3\lib\site-packages\tensorflow\python\ops\array_ops.py in boolean_mask(tensor, mask, name) 1119 if ndims_mask is None: 1120 raise ValueError( -&gt; 1121 "Number of mask dimensions must be specified, even if some dimensions" 1122 " are None. E.g. shape=[None] is ok, but shape=None is not.") 1123 shape_tensor[:ndims_mask].assert_is_compatible_with(shape_mask) ValueError: Number of mask dimensions must be specified, even if some dimensions are None. E.g. shape=[None] is ok, but shape=None is not. print(tf.shape(np_logits_b)) Tensor("Shape_4:0", shape=(?,), dtype=int32)
favorite count: 0
type: UnansweredQuestion
tagged with: python
score: 4

http://stackoverflow.com/comment/90961982
has text: @gogaz i'm just verifying wether i got user or not with the provided credentials. Yes its returning only one user at a time as username is unique in my case it returning properly.
comment on: http://stackoverflow.com/q/52005877
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/90883295
comment on: http://stackoverflow.com/a/51966592
type: AnswerComment
has text: First regex does not seem to work. See here: https://regex101.com/r/VbE8RY/2/. Second regex could match things like `foobar ((1,2,3)(3))` instead of just `vertices ((1,2,3)(3))`. See: https://regex101.com/r/VbE8RY/3. Not sure if that could be a problem for OP, although
score: 0
type: Comment

http://stackoverflow.com/comment/91027440
type: QuestionComment
type: Comment
score: 1
comment on: http://stackoverflow.com/q/52038566
has text: Waht happen if value not match?

http://stackoverflow.com/q/51963134
has comment: http://stackoverflow.com/comment/90876914
type: Question
tagged with: for-loop
has title: How do I check membership of items in a dict and list, within nested for loops?
score: 3
has comment: http://stackoverflow.com/comment/90876673
accepted answer: http://stackoverflow.com/a/51963233
answer count: 1
downvote count: 0
tagged with: nested
favorite count: 0
tagged with: python
tagged with: dictionary
type: AnsweredQuestion
has body: Trying to make this work is making my head spin: I have an ordered dict: OrderedDict([('key', {'keyword': {'blue', 'yellow'}), ('key1', {'keyword': {'lock', 'door'})]) I have a list of potential_matches: [red, blue, one] I want to order these potential matches into one of two lists: correct = [] or incorrect = [] If the potential match is a keyword of one of the keys in the dict, then it goes in correct, else it goes in incorrect. Result of this example should be: correct = [blue], incorrect = [red, one] Here is what I tried: correct = [] incorrect = [] for word in potential_matches: for key, value in ordered_dict.items(): if word in value["keyword"] and word not in correct: correct.append(word) elif word not in value["keyword"] and word not in correct and word not in incorrect: incorrect.append(word) the lists cannot have overlap and must have unique items, that's why there are so many checks in the elif. It's close, but what ends up happening is that the incorrect list will still have items from the correct list. How can I solve this as efficiently as possible? I made it sound a bit complicated, but essentially, all remaining words that are not a match should simply go to the other list. This would require one full run through the potential_match list &amp; dict, though, I think..
upvote count: 3
has answer: http://stackoverflow.com/a/51963233

google-oauth
type: Tag
tags question: http://stackoverflow.com/q/52057302
tags question: http://stackoverflow.com/q/52011285
tags question: http://stackoverflow.com/q/52085054
tags question: http://stackoverflow.com/q/52111792
tag name: google-oauth

http://stackoverflow.com/q/52038209
has comment: http://stackoverflow.com/comment/91027149
tagged with: nested-loops
has comment: http://stackoverflow.com/comment/91028417
has comment: http://stackoverflow.com/comment/91026970
answer count: 3
has comment: http://stackoverflow.com/comment/91026836
favorite count: 0
has comment: http://stackoverflow.com/comment/91026856
upvote count: 2
tagged with: python
has comment: http://stackoverflow.com/comment/91026876
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52038354
has title: python nested reverse loop
score: 0
has answer: http://stackoverflow.com/a/52039393
downvote count: 2
possible better answer: http://stackoverflow.com/a/52038349
has answer: http://stackoverflow.com/a/52038349
type: Question
has body: I'm trying to create a reverse loop nested with a for loop, once the for loop meets a certain criterion then the reverse loop kicks in to obtain the required information I'm searching for based off of a second, consistent, criterion that I know. Normally one would do the for loop to look for the required information; however, I only know the criterions and I don't know the required information other than it's listed prior to the criterions and can be in one of three different formats. I'm using Python 3.6. EDIT: It looks like what's throwing me off is the different formatting of 'what I'm looking for'. To simplify it lets just go with 1 specific format, the information I want can be grouped with information I don't want. searchList = [['apple'], ['a criterion for'], ['what Im looking for'], ['a criterion for what Im looking for not what Im looking for'], ['fish'], ['coffee'], ['oil']] saveInformation = [] for n in range(len(searchList)): if 'coffee' in searchList[n]: for x in range(n, 0, -1): if 'a criterion for' in searchList[x]: #this part just takes out the stuff I don't want saveInformation.append(searchList[x]) break else: # the reason for x+1 here is that if the above if statement is not met, #then the information I am looking for is in the next row. #For example indices 1 and 2 would cause this statement to execute if index #3 was not there saveInformation.append(searchList[x+1]) break Expected output saveInforation = ['what Im looking for'] Instead the output I'm getting is saveInforation = ['oil']
accepted answer: http://stackoverflow.com/a/52039393

http://stackoverflow.com/q/51987725
downvote count: 0
has title: PySpark reduceByKey by only one key
favorite count: 0
tagged with: python-3.x
tagged with: python
accepted answer: http://stackoverflow.com/a/51988020
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51989439
possible better answer: http://stackoverflow.com/a/51990621
upvote count: 1
has answer: http://stackoverflow.com/a/51990621
type: Question
score: 1
tagged with: pyspark
linked to: http://stackoverflow.com/q/31508083
linked to: http://stackoverflow.com/q/48829993
has body: I have a rdd like this // Structure List[Tuple(x1, x2, value), Tuple(x1, x2, value)] data = [('23', '98', 34), ('23', '89', 39), ('23', '12', 30), ('24', '12', 34), ('24', '14', 37), ('24', '16', 30)] I am looking for the end result to be max value of score for x1 with x2 value associated with it. Like this data = [('23', '89', 39), ('24', '14', 37)] I tried reduceByKey but it is giving me max of each combinations which is not what I am looking for. From comment: This is what I tried: max_by_group = ( data.map(lambda x: (x[0], x)) .reduceByKey(lambda x1, x2: max(x1, x2, key=lambda x: x[-1])) .values() )
tagged with: apache-spark
answer count: 3
has answer: http://stackoverflow.com/a/51988020
has comment: http://stackoverflow.com/comment/90934629

http://stackoverflow.com/comment/90977473
comment on: http://stackoverflow.com/q/52013266
has text: got it nevermind thank you. I had to use `for i in range(1, maximum + 1):`
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/52001922
possible better answer: http://stackoverflow.com/a/52002374
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52002374
has title: LinearConstraint in scipy.optimize
has answer: http://stackoverflow.com/a/69492274
has answer: http://stackoverflow.com/a/52003654
upvote count: 10
tagged with: scipy
type: Question
score: 9
answer count: 3
favorite count: 0
accepted answer: http://stackoverflow.com/a/52003654
tagged with: python
linked to: http://stackoverflow.com/q/233673
has body: I would like to use scipy.optimize to minimize a function (eventually non-linear) over a large set of linear inequalities. As a warm-up, I'm trying to minimize x+y over the box 0&lt;=x&lt;=1, 0&lt;=y&lt;=1. Following the suggestion of Johnny Drama below, I am currently using a dict-comprehesion to produce the dictionary of inequalities, but am not getting the expected answer (min value=0, min at (0,0)). New section of code (currently relevant): import numpy as np from scipy.optimize import minimize #Create initial point. x0=[.1,.1] #Create function to be minimized def obj(x): return x[0]+x[1] #Create linear constraints lbnd&lt;= A*(x,y)^T&lt;= upbnd A=np.array([[1,0],[0,1]]) b1=np.array([0,0]) b2=np.array([1,1]) cons=[{"type": "ineq", "fun": lambda x: np.matmul(A[i, :],x) -b1[i]} for i in range(A.shape[0])] cons2=[{"type": "ineq", "fun": lambda x: b2[i]-np.matmul(A[i, :], x) } for i in range(A.shape[0])] cons.extend(cons2) sol=minimize(obj,x0,constraints=cons) print(sol) Original version of question: I would like to use the LinearConstraint object in scipy.optimize, as described in the tutorial here: "Defining linear constraints" I've tried to do a simpler example, where it's obvious what the answer should be: minimize x+y over the square 0&lt;=x&lt;=1, 0&lt;=y&lt;=1. Below is my code, which returns the error "'LinearConstraint' object is not iterable", but I don't see how I'm trying to iterate. EDIT 1: The example is deliberately over simple. Ultimately, I want to minimize a non-linear function over a large number of linear constraints. I know that I can use dictionary comprehension to turn my matrix of constraints into a list of dictionaries, but I'd like to know if "LinearConstraints" can be used as an off-the-shelf way to turn matrices into constraints. EDIT 2: As pointed out by Johnny Drama, LinearConstraint is for a particular method. So above I've tried to use instead his suggestion for a dict-comprehension to produce the linear constraints, but am still not …
downvote count: 1

http://stackoverflow.com/q/52010970
score: 0
has comment: http://stackoverflow.com/comment/90972976
tagged with: python
tagged with: python-3.x
type: UnansweredQuestion
has title: When I print my list instead of using the names in the list the output shows the index numbers. Python 2D-Lists
has answer: http://stackoverflow.com/a/52013312
type: Question
has body: Here is my code the lists are where Im having issues. Im new to python and I do not understand how 2D-lists work but I need to add then in to the program for a grade. Any help will be appreciated. #Define Vars import locale locale.setlocale( locale.LC_ALL, '') order_total = 0.0 price = 3.5 fmt_price = locale.currency(price, grouping=True) qty = int(0) #cookie list cookie_list = list() cookie_list = "Savannah Thin-Mints Tag-a-longs Peanut-Butter Sandwich".split() order_list = list() #cookie choices def disp_items(): print("Please choose one of our flavours. Enter the item number to choose") for c in range(len(cookie_list)): print("{}. \t{}".format(c+1, cookie_list[c])) print() #Menu Choices def disp_menu(): choice_list = ["a", "d", "m", "q"] while True: print("\nWhat would you like to do?") print("a = add an item") print("d = delete an item") print("m = display the meal so far") print("q = quit") choice = input("\nmake a selection: ") if choice in choice_list: return choice else: print("I dont't understand that entry. Please Try again.") # Math Function********************** def calc_tot(qty): #this function is qty * price return qty * 3.5 def disp_order(): print("\nGirl Scout Cookie Order for", cust) print() print("Itm\tName\tQty\tPrice") print("---\t----\t----\t----") order_total_items = 0 #accumulator order_price = 0 for c in range(len(order_list)): detail_list = [" ", 0] detail_list.append(order_list) print("{}.\t{}\t{}\t{}".format(c+1, order_list[c][0], order_list[c][1], price)) order_total_items += order_list[c][1] order_price += price print("\nYour Order Contains {} items for total of {} \n".format(order_total_items, order_price)) print("-" * 30) #ADD Process def add_process(): valid_data = False while not valid_data: disp_items() try: item = int(input("Enter item number: ")) if 1 &lt;= item &lt;= len(cookie_list): valid_data = True else: print("\nThat was not a vaild choice, please try again.") except Exception as detail: print("error: ", detail) #Valid Qty v…
answer count: 1

http://stackoverflow.com/comment/91030666
has text: Well, does the file actually exist in this path?
type: Comment
type: QuestionComment
score: 2
comment on: http://stackoverflow.com/q/52040017

http://stackoverflow.com/comment/91115507
score: 0
has text: You are correct.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52082342

http://stackoverflow.com/a/67947327
type: Answer
answers question: http://stackoverflow.com/q/52108019
score: 0
has body: I know it's a bit late but faced a similar issue with heroku (they also use linux environments). What you have to do is check the version of your local/dev environment and use that specific versions while deploying, even the python version. import scipy import sklearn import numpy print(scipy.__version__) print(sklearn.__version__) print(numpy.__version__) Add this versions specifically to requirements.txt scipy==1.4.1 scikit-learn==0.22.2.post1 numpy==1.19.5 In heroku to set the Python runtime, add a runtime.txt file to your app’s root directory that declares the exact version number to use: python-3.7.10

http://stackoverflow.com/comment/91112644
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/52080926
type: Comment
has text: @Jakob Please [edit] code into your question; don’t paste it in a comment.

http://stackoverflow.com/comment/91141704
comment on: http://stackoverflow.com/q/52092917
has text: @WillemVanOnsem once I delete the `class B(models.Model):` and the file from the migrations folder and re-migrate then it works.
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/91025054
type: QuestionComment
comment on: http://stackoverflow.com/q/52037352
has text: @sacul i was hoping that by doing some operation on the array it would result in `0,2,4,10,12`, is there something fundamental im missing here?
score: 0
type: Comment

http://stackoverflow.com/q/52041914
tagged with: python
tagged with: list
score: 0
has answer: http://stackoverflow.com/a/52042052
tagged with: coordinates
answer count: 1
tagged with: sorting
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/52042052
linked to: http://stackoverflow.com/q/3121979
has body: I have a program where I want to sort by an x coordinate. My list looks like this: [('Name1', (449, 923, 634, 737)), ('Name2', (390, 1356, 613, 1133)), ('Name3', (1062, 1749, 1216, 1594))] Each element of the original list has a name, and then a set of x1, y1, x2, y2 coordinates. If I want to sort my list by the x2 coordinate, how would I do that? I've searched around and found that you can use "itemgetter" to do something like this: preds = sorted(preds, key=itemgetter(1)) But that is getting the whole set of coordinates. How would I sort by say, the third coordinate, specifically?
has comment: http://stackoverflow.com/comment/91034599
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/91035109
type: Question
has comment: http://stackoverflow.com/comment/91035260
has title: Sort by coordinates inside of a list, inside of a list
linked to: http://stackoverflow.com/q/41736425
duplicate of: http://stackoverflow.com/q/3121979

http://stackoverflow.com/q/51959686
downvote count: 0
score: 1
has body: As the title states, I am attempting to match cell data from column 1 of worksheet 0 and compare it to cell data from column 3 of worksheet 1. If a match occurs, write the matching cell data from worksheet 2's column 1. I can print the desired data to console but I cannot get it to write the values into cells on worksheet 3. I have pasted working code but I am unsure how to create the logic for my desired results. Any assistance is appreciated. import openpyxl wb = openpyxl.load_workbook(r'C:\project.xlsx') ws1 = wb['Partial'] ws2 = wb['Complete'] ws3 = wb.create_sheet(title='Results') ws3 = wb.active for x in ws1['A1:A53']: for y in ws2['C1:C1118']: if x == y: ws3.append(ws2.cell(row = y, column = 1).value) wb.save('project.xlsx') modified
has comment: http://stackoverflow.com/comment/90872149
favorite count: 0
has comment: http://stackoverflow.com/comment/90895859
type: Question
upvote count: 1
tagged with: python
tagged with: excel
has comment: http://stackoverflow.com/comment/90895254
tagged with: openpyxl
has title: Compare two Excel worksheets and copy cell data onto a third sheet when a match is found via Python and Openpyxl
has comment: http://stackoverflow.com/comment/90894909
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90873639

download
tags question: http://stackoverflow.com/q/52084472
tags question: http://stackoverflow.com/q/52095282
type: Tag
tags question: http://stackoverflow.com/q/51991089
tags question: http://stackoverflow.com/q/52083522
tag name: download
tags question: http://stackoverflow.com/q/52000950
tags question: http://stackoverflow.com/q/51964400

http://stackoverflow.com/q/51970542
score: 1
tagged with: flask
tagged with: flask-sqlalchemy
favorite count: 0
type: Question
tagged with: python
has comment: http://stackoverflow.com/comment/90907459
upvote count: 1
answer count: 1
has answer: http://stackoverflow.com/a/51973900
has comment: http://stackoverflow.com/comment/90938471
has body: So In my flask project I've used Flask-Login to implement a login/registration system. However that is for my Users table. I also have a "Booster" table which has almost the same properties, but a little more. For example, the booster will login to a different part of the website. I have it separated by the routes. So my routes I have are /login, /register and /booster_login and /booster_register. I tried to use the login_user method on my login method under booster_login, but I'm getting a object has no is_active attribute when I submit the booster_login form. I can not just use roles since boosters will have many more attributes than users. My models.py is here from flask_login import UserMixin from flask_sqlalchemy import SQLAlchemy from flask_admin import Admin from flask_socketio import SocketIO, join_room import datetime db = SQLAlchemy() socketio = SocketIO() class User(UserMixin, db.Model): __tablename__ = 'users' id = db.Column(db.Integer, primary_key=True) username = db.Column(db.String(20), unique=True) email = db.Column(db.String(50), unique=True) password = db.Column(db.String(80)) role = db.Column(db.String(80)) class Booster(db.Model): id = db.Column(db.Integer, primary_key=True) booster_name = db.Column(db.String(20), nullable=False) password = db.Column(db.String(20), nullable=False) email = db.Column(db.String(50), nullable=False) join_date = db.Column(db.DateTime(timezone=True)) current_order = db.Column(db.Integer, db.ForeignKey('orders.id')) current_balance = db.Column(db.Float) def __init__(self, booster_name, email, password, join_date): self.booster_name = booster_name self.password = password self.email = email self.join_date = join_date https://github.com/bshelton/flask-boost/blob/master/views.py from flask import Flask, render_template, redirect, url_for, Blueprint, request from flask_login import LoginManager, UserMixin, login_user, login_required, logout_user, current_user from flask_sqlalchemy import SQLAlchemy, functools from sqlalchem…
type: UnansweredQuestion
has title: Flask-Login with Multiple User Classes
downvote count: 0

http://stackoverflow.com/q/52031664
tagged with: grep
score: -3
tagged with: python
tagged with: regex
downvote count: 3
type: Question
has comment: http://stackoverflow.com/comment/91013974
answer count: 2
upvote count: 0
has answer: http://stackoverflow.com/a/52031751
has body: I am a student working on a small research project where I need to scrape web pages which match the following requirement :- If word X say "abc" is found anywhere in the text, look for pattern Y say "pqr" if it occurs within a 25 character window on either side of the occurrence of X. Eg. pqrxyz is valid. xyz is invalid. xyzpqr is valid. pqr123456789123456789123456789xyz is invalid. I can't figure this out. Any help will be greatly appreciated. ((?=pqr).{20,}abc) | (pqr{20,}(?!abc)) This is my attempt so far. I don't know how to incorporate the 20 character window constraint.
favorite count: 0
has title: Creating a regex to match the following scenario
has comment: http://stackoverflow.com/comment/91013697
has answer: http://stackoverflow.com/a/52031790
type: UnansweredQuestion

http://stackoverflow.com/q/51973570
has comment: http://stackoverflow.com/comment/90897990
has title: Read different .csv files into different dataframes with a loop with Python Pandas
linked to: http://stackoverflow.com/q/46502943
answer count: 2
has comment: http://stackoverflow.com/comment/90897652
favorite count: 0
has comment: http://stackoverflow.com/comment/90897678
has answer: http://stackoverflow.com/a/51973644
tagged with: pandas
tagged with: http://stackoverflow.com/tag/csv
has comment: http://stackoverflow.com/comment/90995750
tagged with: python
has comment: http://stackoverflow.com/comment/90899065
has comment: http://stackoverflow.com/comment/90897636
has answer: http://stackoverflow.com/a/51973637
has body: Please, before marking this question as duplicated read the whole post. I know that this post has a similar question but what I'm looking for is somehow different. I have a list of file names: files = ['first.csv', 'second.csv', 'third.csv'] And I want to read them inside a loop with pandas. What I expect is to create for each iteration inside the loop a different dataframe: first = pd.read_csv('first.csv') second = pd.read_csv('second.csv') third = pd.read_csv('third.csv') But inside a loop. Something like: for i in range(len(files)): csv = re.split('.', files[i])[0] csv = pd.read_csv(files[i]) IMPORTANT: Each csv has different rows and columns. So what I want is not to read the three csv to combine them into one with pd.concat. I want to read them separately. I tried to read them into a list with: dataframe_list = [pd.read_csv(file_name) for file_name in files] But that raises the next error: UnicodeDecodeError: 'utf-8' codec can't decode byte 0x85 in position 59: invalid start byte
upvote count: 2
duplicate of: http://stackoverflow.com/q/46502943
type: UnansweredQuestion
score: 1
tagged with: loops
has comment: http://stackoverflow.com/comment/90974022
downvote count: 1
has comment: http://stackoverflow.com/comment/90897586
type: Question
has comment: http://stackoverflow.com/comment/90898505
has comment: http://stackoverflow.com/comment/90897674

http://stackoverflow.com/comment/91822463
has text: @ev-br Then input values for `x` and `y` will be duplicated.
score: 0
comment on: http://stackoverflow.com/q/52102065
type: QuestionComment
type: Comment

http://stackoverflow.com/a/52029596
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/91009903
type: Answer
has comment: http://stackoverflow.com/comment/91009728
has body: You can use collections.Counter with list comprehension to get sublists whose first item appears only once: from collections import Counter c = Counter(n for n, _ in a) b = [[x, y] for x, y in a if c[x] == 1]
answers question: http://stackoverflow.com/q/52029529
has comment: http://stackoverflow.com/comment/91009649
accepted answer of: http://stackoverflow.com/q/52029529
score: 5
upvote count: 5
downvote count: 0
has comment: http://stackoverflow.com/comment/91009919
has comment: http://stackoverflow.com/comment/91009695

http://stackoverflow.com/a/52083839
type: Answer
score: 2
downvote count: 0
upvote count: 2
has comment: http://stackoverflow.com/comment/91119166
has body: Hash mark (#) delimiters are only required for date literals in the SQL command text itself. They are not required (and are in fact invalid) in a parameterized query. This works, verified with pyodbc 4.0.24: sql = "UPDATE [Status Scorecard] SET [IN:Start Execute] = ? WHERE [IN:ID] = ?" params = (datetime.date(2015, 9, 14), '47977') crsr.execute(sql, params) cnxn.commit() result: IN:ID IN:Start Execute ----- ---------------- 47977 2015-09-14 To "blank out" the date, use None params = (None, '47977')
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/52081829
answers question: http://stackoverflow.com/q/52081829

http://stackoverflow.com/comment/91013133
comment on: http://stackoverflow.com/a/52031298
type: Comment
has text: Okay, but can directly do `end=' '` instead of adding `' '` then `end=''`, as in my answer
score: 0
type: AnswerComment

http://stackoverflow.com/comment/91171655
has text: No. I am using Python3.7 and Django 2.1
comment on: http://stackoverflow.com/q/52110485
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/52038362
has body: Maybe: txt = 'baby' res = [[i, len(txt) - txt[::-1].find(i) - 1] for i in set(txt)] res # [['a', 1], ['b', 2], ['y', 3]]
score: 0
type: Answer
answers question: http://stackoverflow.com/q/52038053

http://stackoverflow.com/q/52105173
linked to: http://stackoverflow.com/q/7049252
type: Question
has body: I need to run 20 experiments in parallel. For each, I am loading a new unix screen, then within that loading an anaconda environment, and then running a python script with an argument for that experiment. The workflow looks like: &gt; screen -S exp01 &gt; source activate myenv (myenv) &gt; python process_experiment 01 &gt; screen -S exp02 &gt; source activate myenv (myenv) &gt; python process_experiment 02 Is there a way to write a script to automate it?
has answer: http://stackoverflow.com/a/52106094
answer count: 1
downvote count: 0
tagged with: unix
favorite count: 0
type: UnansweredQuestion
upvote count: 1
tagged with: python
has title: Automate loading of multiple unix screens with commands
score: 1
tagged with: gnu-screen

http://stackoverflow.com/comment/90937539
comment on: http://stackoverflow.com/q/51993631
has text: Can you add the `reviews.urls` module ?
type: Comment
type: QuestionComment
score: 1

http://stackoverflow.com/a/52015041
upvote count: 1
has body: If you look at your gradient accumulation code here, weights_gradient_output += neural_input * output_delta #bias_output += output_delta You are adding your gradients directly to the bias instead of to bias_gradient_output. Consequently, your bias updates use a learning rate of 1, which is probably higher than you intended. (Similar problem with bias_11, etc).
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52014867
answers question: http://stackoverflow.com/q/52014867
type: Answer
score: 1

http://stackoverflow.com/q/52094012
has title: Pointer Unboxing in Python
type: Question
tagged with: c#
tagged with: .net
tagged with: pointers
tagged with: python.net
downvote count: 0
favorite count: 0
upvote count: 2
type: UnansweredQuestion
has body: Good Afternoon, I have a class from a third party DLL with the following Buffer.Attach method: public void Attach( byte* aBuffer, uint aSize) The method can be called from C# using: aBuffer.Attach( (byte*) arrPointer , nBytes) where arrPointer is a System.Reflection.Pointer How can I call the method using Python.Net. If I pass only the arrPointer to the method I receive a TypeError: No method matches given arguments. In other word, how can I perform the pointer unboxing in python? Thank you in advance for any help. Best Regards, Brice
tagged with: python
score: 2
answer count: 0

http://stackoverflow.com/q/52094131
has body: how can i make pip work. ive been trying to get pip to work for a long time on this particular laptop. ive had it working on a bunch of others. but never this laptop for some reason. in an attempt to get pip to work i deleted everything python on this laptop and started fresh (deleted python 3.6, 3.7, anaconda and all of my environment variables) and reinstalled 3.7 telling the python installer to install pip for me. it added the environment variables itself but pip still wont work. a screenshot showing the situation
tagged with: python
favorite count: 0
type: UnansweredQuestion
downvote count: 2
tagged with: pip
type: Question
has title: pip wont work on this particular computer
upvote count: 0
score: -2
answer count: 1
has answer: http://stackoverflow.com/a/52094151

http://stackoverflow.com/a/51971533
has body: What you input to your program is always of type str. if you want Python to deduce the type of the input itself, use data = eval(input()) or, for more safety: import ast data = ast.literal_eval(input())
has comment: http://stackoverflow.com/comment/90893908
downvote count: 0
has comment: http://stackoverflow.com/comment/90893865
type: Answer
score: 3
upvote count: 3
answers question: http://stackoverflow.com/q/51971456

http://stackoverflow.com/comment/91058068
type: Comment
type: QuestionComment
has text: My data has 5 rows and 2 columns, but the for loop read 10 values. How can I make it read 5 rows only? {0 1a3 1 2a4 2 3a5 3 4a6 4 5a7 dtype: object 0 1a3 1 2a4 2 3a5 3 4a6 4 5a7 dtype: object}
score: 0
comment on: http://stackoverflow.com/q/52050623

pycharm
tags question: http://stackoverflow.com/q/52027323
tags question: http://stackoverflow.com/q/52030954
tags question: http://stackoverflow.com/q/51978816
tags question: http://stackoverflow.com/q/51958877
tag name: pycharm
tags question: http://stackoverflow.com/q/52056470
tags question: http://stackoverflow.com/q/51973396
tags question: http://stackoverflow.com/q/51968505
tags question: http://stackoverflow.com/q/52074241
tags question: http://stackoverflow.com/q/51983684
tags question: http://stackoverflow.com/q/52093988
tags question: http://stackoverflow.com/q/52006634
tags question: http://stackoverflow.com/q/52061978
tags question: http://stackoverflow.com/q/51994754
tags question: http://stackoverflow.com/q/52017357
tags question: http://stackoverflow.com/q/51982735
tags question: http://stackoverflow.com/q/51989813
tags question: http://stackoverflow.com/q/52025453
tags question: http://stackoverflow.com/q/51990919
tags question: http://stackoverflow.com/q/52108100
tags question: http://stackoverflow.com/q/51982200
tags question: http://stackoverflow.com/q/52013452
tags question: http://stackoverflow.com/q/52037480
tags question: http://stackoverflow.com/q/52018260
tags question: http://stackoverflow.com/q/51975503
tags question: http://stackoverflow.com/q/52018196
tags question: http://stackoverflow.com/q/51959179
tags question: http://stackoverflow.com/q/52018430
tags question: http://stackoverflow.com/q/52087285
tags question: http://stackoverflow.com/q/52049163
tags question: http://stackoverflow.com/q/52105383
tags question: http://stackoverflow.com/q/52081316
tags question: http://stackoverflow.com/q/52049366
tags question: http://stackoverflow.com/q/52076262
tags question: http://stackoverflow.com/q/52047387
type: Tag
tags question: http://stackoverflow.com/q/52013220
tags question: http://stackoverflow.com/q/51989012
tags question: http://stackoverflow.com/q/52094226
tags question: http://stackoverflow.com/q/51968012
tags question: http://stackoverflow.com/q/52049202
tags question: http://stackoverflow.com/q/52024210
tags question: http://stackoverflow.com/q/52030496
tags question: http://stackoverflow.com/q/52111339
tags question: http://stackoverflow.com/q/52094951
tags question: http://stackoverflow.com/q/52036374

http://stackoverflow.com/comment/91002978
type: Comment
score: 1
has text: Thank you! So much more elegant than my attempts at using loops etc. Thanks
type: AnswerComment
comment on: http://stackoverflow.com/a/52025914

http://stackoverflow.com/q/52085511
type: Question
tagged with: flask
score: 0
answer count: 1
linked to: http://stackoverflow.com/q/32076750
tagged with: flask-wtforms
has title: Flask-WTF validate() method shouldn't override other validations?
has body: I'm busy with a plurasight course where I suppose to handle errors in Flask-wtf. The only problem is the course is a 'bit outdated. It's been made in 2014. In the video the teacher showed how you can define a validate() method in a class to use it first when I call form.validate_on_submit(). Here is the code: from flask_wtf import FlaskForm from wtforms.fields import StringField from wtforms.fields.html5 import URLField from wtforms.validators import DataRequired, url class BookmarkForm(FlaskForm): url = URLField('url', validators=[DataRequired(), url()]) description = StringField('description') def validate(self): if not self.url.data.startswith("http://") or self.url.data.startswith("https://"): self.url.data = "http://" + self.url.data if not FlaskForm.validate(self): return False if not self.description.data: self.description.data = self.url.data return True And here is my view: @app.route('/add', methods=['GET', 'POST']) def add(): form = BookmarkForm(request.form) if form.validate_on_submit(): url = form.url.data description = form.description.data store_bookmark(url, description) flash('Stored bookmark {}'.format(description)) return redirect(url_for('index')) return render_template('add.html', form=form) The problem is, Flask-wtf don't let me submit a url like google.com. Only in this form: http://www.google.com. Based on this description It should work like this: validate_on_submit() Call validate() only if the form is submitted. This is a shortcut for form.is_submitted() and form.validate() But it doesn't. It still don't let me type a URL in without http://. I didn't find any solution in the documentation and here is a stackoverflow question, but there is no answer and it's also 3 years old. Please help me find out what I've done wrong!
linked to: http://stackoverflow.com/q/17946960
tagged with: python
accepted answer: http://stackoverflow.com/a/52089354
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52089354

http://stackoverflow.com/comment/91111530
has text: I have run your code and works perfectly (fixing the identation errors)
comment on: http://stackoverflow.com/q/51983352
score: 0
type: Comment
type: QuestionComment

relative-path
type: Tag
tag name: relative-path
tags question: http://stackoverflow.com/q/51968012

http://stackoverflow.com/comment/90923770
comment on: http://stackoverflow.com/q/51986961
has text: Can the program not just append rather than overwrite?
type: Comment
type: QuestionComment
score: 5

http://stackoverflow.com/q/52026659
tagged with: python-3.x
has answer: http://stackoverflow.com/a/52027194
tagged with: python
tagged with: dictionary
has comment: http://stackoverflow.com/comment/91003474
type: AnsweredQuestion
score: 3
downvote count: 0
tagged with: http://stackoverflow.com/tag/json
has answer: http://stackoverflow.com/a/52026947
accepted answer: http://stackoverflow.com/a/52026947
type: Question
possible better answer: http://stackoverflow.com/a/52027194
has body: I was wondering if there was a way to use json.loads in order to automatically convert an empty string in something else, such as None. For example, given: data = json.loads('{"foo":"5", "bar":""}') I would like to have: data = {"foo":"5", "bar":None} Instead of: data = {"foo":"5", "bar":""}
has title: parse empty string using json
upvote count: 3
has comment: http://stackoverflow.com/comment/91003792
answer count: 3
has answer: http://stackoverflow.com/a/52026837
tagged with: string
favorite count: 0

http://stackoverflow.com/comment/91024752
has text: @DeepSpace is right - you should just convert to str before printing the output - it should fix "extra b problem" for you
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52037166
score: 0

ssl
tags question: http://stackoverflow.com/q/51991891
tags question: http://stackoverflow.com/q/52005888
tags question: http://stackoverflow.com/q/52030010
type: Tag
tags question: http://stackoverflow.com/q/52042226
tag name: ssl
tags question: http://stackoverflow.com/q/52078629
tags question: http://stackoverflow.com/q/52074590
tags question: http://stackoverflow.com/q/51959205
tags question: http://stackoverflow.com/q/52029939
tags question: http://stackoverflow.com/q/52065588
tags question: http://stackoverflow.com/q/52012488
tags question: http://stackoverflow.com/q/52078346
tags question: http://stackoverflow.com/q/52012055

http://stackoverflow.com/comment/91027344
comment on: http://stackoverflow.com/q/52037480
score: 0
has text: I've tried `from utils import lib` and it seemed to be working well. Did you mark either `game` or `utils` in any way? (by marking I mean f.e. Sources Root)
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/90995536
has text: That's one way to do it, but i would like to check if the user already exists before updating the users dictionary in the main file, so im thinking i would have to add a list to the new_user() function within the CreateCustomer class and check to see if the user inputted name already has been used '
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52011445
type: Comment

sklearn-pandas
tags question: http://stackoverflow.com/q/52107909
tags question: http://stackoverflow.com/q/52055658
tag name: sklearn-pandas
tags question: http://stackoverflow.com/q/51976394
tags question: http://stackoverflow.com/q/51977643
tags question: http://stackoverflow.com/q/52024880
type: Tag

http://stackoverflow.com/comment/91052973
type: Comment
comment on: http://stackoverflow.com/a/52051278
has text: So, now can I subtract the number of days from a number. Like `{{ 10 -leave_object.date_diff }} ` ?
score: 0
type: AnswerComment

http://stackoverflow.com/comment/90970860
has text: Please provide more data in your question, what do these arrays contain? Provide full code sample if you can, so that we can try to re-create the error
type: Comment
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/52009339

http://stackoverflow.com/q/52011846
type: Question
has comment: http://stackoverflow.com/comment/90974883
has comment: http://stackoverflow.com/comment/90974723
answer count: 1
tagged with: python-3.x
has body: I have a csv file with details of faculty members.Several members have the same last name.I am trying to create a dictionary with the lastnames as keys and the other details as the values.The data kind of looks as follows: name,degree,title S.li,phd,Associate Professor of Biostats d.Chiou,MD, Professor ofABC F.Li,MPH Professor of DCD I am trying to get a dictionary as follows; mydict={"Li":[[' phd.', 'Associate Professor of Biostats'], ['MPH','Professor of DCD']] 'Chiou': ' MD', 'Professor of ABC'} I have used the following code, its not working. reader = csv.reader(open('faculty.csv')) mydict = {} for rows in reader: k = rows[0] v = rows[1:] mydict[k] = v print (mydict) I also tried this code: reader = csv.reader(open('faculty.csv')) mydict = {rows[0]:rows[1:] for rows in reader} print (mydict)
type: UnansweredQuestion
tagged with: python
tagged with: dictionary
has answer: http://stackoverflow.com/a/52015205
has title: Creating a dictionary from csv file with specific keys
score: 0
has comment: http://stackoverflow.com/comment/90974784

http://stackoverflow.com/comment/91040336
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52039621
has text: @Mike-SMT Thanks.

http://stackoverflow.com/a/71453373
has body: lol im a bit late on this but I want to answer in case anyone else will encounter the issue. for me the issue was that os didn't find the path to the XML files, so I put the whole file directory in the part: "image_path = os.path.join( etc. etc..)"
type: Answer
answers question: http://stackoverflow.com/q/52047920
score: 0

http://stackoverflow.com/q/52085986
tagged with: python
tagged with: autoencoder
has comment: http://stackoverflow.com/comment/91187494
has comment: http://stackoverflow.com/comment/91137783
type: Question
has body: i am working on program that make a vectorization for gray scale images not RGB that taken bottleneck layer from autoencoder but i have the following error, any suggestion: Root: image at /path/to/images is not RGB , therefore not using it
has comment: http://stackoverflow.com/comment/91137796
score: 0
has title: Trying to vectorizaion of gray scale image from bottelneck layer
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91122908

http://stackoverflow.com/q/52106943
has body: I want to get the output of a keras layer which is a tensor of images, convert it to numpy arrays and apply a custom function on them without using backend functions, and return the output to the model. So it would be something like this: def sum(args): # convert args to numpy arrays ??? #calculating sum of all the elements s=np.sum(args) return s Thank you very much for your help.
has title: How to write a custom function in keras without using backend functions?
type: UnansweredQuestion
upvote count: 1
has answer: http://stackoverflow.com/a/52107084
type: Question
score: 1
answer count: 1
downvote count: 0
tagged with: keras
favorite count: 0
tagged with: python

http://stackoverflow.com/comment/91281017
type: Comment
score: 1
has text: Hey! Alarm is created but this alarm is still under "Insufficient Data State"...any solution for this?
comment on: http://stackoverflow.com/a/52114068
type: AnswerComment

http://stackoverflow.com/a/52043689
has comment: http://stackoverflow.com/comment/91038393
has body: Try using startswith: df[df.Code.str.startswith('GWA')]
answers question: http://stackoverflow.com/q/52043677
has comment: http://stackoverflow.com/comment/91038431
has comment: http://stackoverflow.com/comment/91038403
type: Answer
score: 3
accepted answer of: http://stackoverflow.com/q/52043677
upvote count: 3
has comment: http://stackoverflow.com/comment/91038297
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/91038418

http://stackoverflow.com/comment/91105386
score: 0
type: AnswerComment
type: Comment
has text: Thanks for the information. The document you provided explain very well the problem. Today I learned something :-)
comment on: http://stackoverflow.com/a/52077106

http://stackoverflow.com/comment/91143206
type: QuestionComment
has text: is `output_file` the path to a file (I don't think that will work) or a file-like object (like what you get from using the `open(output_file, 'w')` method?
comment on: http://stackoverflow.com/q/52095801
score: 0
type: Comment

http://stackoverflow.com/comment/91057579
type: QuestionComment
comment on: http://stackoverflow.com/q/52053222
score: 0
has text: Yes, the same error will come up but it should also have printed a list of the frame columns just before the error
type: Comment

http://stackoverflow.com/comment/91123641
has text: Simple assignment, `x = <something>` **never copies** and simply says "the name `x` now refers to <some-object>". Read https://nedbatchelder.com/text/names.html
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52086420
score: 1

http://stackoverflow.com/comment/91170993
type: QuestionComment
has text: V1 and V2 are user A and user B
score: 0
comment on: http://stackoverflow.com/q/52082895
type: Comment

http://stackoverflow.com/comment/91126201
comment on: http://stackoverflow.com/a/52055720
type: AnswerComment
score: 0
type: Comment
has text: That's really useful! Thanks for the extra info @hoefling!!

http://stackoverflow.com/comment/91187317
comment on: http://stackoverflow.com/a/52003019
score: 1
type: AnswerComment
has text: @Madhurjya, just try switch to `offline` mode. This error show you, that plotly tried to connect with plotly servers. I am updated the answer (just replace `plotly.plotly.iplot` to `plotly.offline.plot`) - and this line of code you set plotly to work in offline mode.
type: Comment

http://stackoverflow.com/comment/91167562
type: Comment
has text: I want to group by on the basis of CITY and on the basis of City Shin_roma_1.2 and Jessie_madrid_1.1 is Max. So it should return me the User with Max number on order of City. Are you getting me now ?
comment on: http://stackoverflow.com/a/52070766
score: 0
type: AnswerComment

http://stackoverflow.com/comment/107693074
type: Comment
has text: I don't know about Jupyter version 4.4.0, but in my version 5.7.4 there is an option to add an `Edit Metadata` button to every cell by selecting the following option: View -> Cell Toolbar --> Edit Metadata
score: 0
comment on: http://stackoverflow.com/q/51958728
type: QuestionComment

http://stackoverflow.com/q/52019041
has answer: http://stackoverflow.com/a/52019734
score: 0
answer count: 2
has body: I want to call an object of another class in my class but when i run the code it says: RecursionError: maximum recursion depth exceeded Any ideas of what error im making? This is my code: class Anden(Estacion): def __init__ (self,ID): self.ID=ID self.filas_anden=[0,0,0,0,0,0,0,0,0,0] self.puertas = [] while len(self.puertas) &lt; 10: puerta = Puerta(len(self.puertas)) def asignar_fila(self, pasajero): aux=10000000000 puerta_asignada = min(filas_anden) for i in range(10): if aux &gt; self.puertas[i].total_fila: aux = self.puertas[i].total_fila fila_asignada = i pasajero.fila_actual = i self.filas_anden[i] +=1 self.puertas[i].append(pasajero) class Puerta(Anden): def _init_ (self,ID): self.ID = ID self.lista_pasajeros = [] self.total_fila = 0 def ingresa_pasajero_fila(self, pasajero): self.lista_pasajeros.append(pasajero) self.total_fila = self.total_fila + 1 def remover_pasajero_fila(self, pasajero): self.lista_pasajeros.remove(pasajero) self.total_fila = self.total_fila - 1
has comment: http://stackoverflow.com/comment/90988664
tagged with: python
has title: RecursionError: maximum recursion depth exceeded creating object of a class inside other class
has answer: http://stackoverflow.com/a/52019115
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/45170625
type: Question

http://stackoverflow.com/comment/90887671
has text: Your solution worked. After inspecting the html, I found out that the tags I am looking for aren't even in there. It looks like the html page that is rendered in python is completely different than the page rendered on a browser.
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51960318

http://stackoverflow.com/q/51992263
tagged with: python
has body: I'd like to make the text of let's say input("Name: ") colored in a way like cprint() with the colorama module. Is there any way of doing that? I've tried this: green = '\33[92m' input(green + "Name: " + green) But it doens't show any color. It just tries to print these characters as they are. However with the print() function the output is colored green. print(green + "Hi" + green) Any help?
has title: Colored output of the input() text in the console
score: 1
has comment: http://stackoverflow.com/comment/90935060
tagged with: output
type: Question
has answer: http://stackoverflow.com/a/79015441
has comment: http://stackoverflow.com/comment/90934408
has comment: http://stackoverflow.com/comment/90934985
has comment: http://stackoverflow.com/comment/90935183
upvote count: 1
downvote count: 0
answer count: 1
tagged with: console
favorite count: 0
tagged with: colors
type: UnansweredQuestion

http://stackoverflow.com/a/51996920
upvote count: 2
has comment: http://stackoverflow.com/comment/90944547
type: AcceptedAnswer
type: Answer
score: 2
downvote count: 0
answers question: http://stackoverflow.com/q/51996871
accepted answer of: http://stackoverflow.com/q/51996871
has body: Your original text is in the upper case, but the 's's in the dictionary are in the lower case. 'S' and 's' are two different letters. Add the upper-case versions of the keys to the dictionary: reps3.update({k.upper(): v for k, v in reps3.items()})

http://stackoverflow.com/comment/90970356
comment on: http://stackoverflow.com/q/52009732
score: 0
has text: You shold take a look at the answers [here](https://stackoverflow.com/questions/9470584/python-paramiko-run-command)
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91092498
score: 1
type: Comment
type: QuestionComment
has text: Could you please share the _real_ content/structure of your input? The fact the you create your csv reader without specifying a delimiter somewhat indicates your input has commas as separator instead of whitespace characters as suggested by your example above. Specifically, I'd like to know if there is blank cells when no Date and Page No are given, i.e. the line has two trailing commas.
comment on: http://stackoverflow.com/q/52070106

http://stackoverflow.com/q/52068364
has comment: http://stackoverflow.com/comment/91118687
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/91123204
answer count: 0
has title: Linear Regression Predict next minutes
tagged with: machine-learning
upvote count: 1
downvote count: 1
type: Question
tagged with: linear-regression
has body: I have a linear model already compiled, where I pass to it 3 variables and I have one output: Input: Temperature1, Temperature2 and Level Output: Pressure These data are collected every 1 minute through an equipment. In this case I can predict the next minute, being that I get the last value of each variable and subtracted by the current value and I have a difference. This difference I add with the last value collected, so I move to the model and it gives me the prediction of the variable Pressure. Ex: Time Temperature1 10:00 100 10:01 105 In this case I know that the variation was 5, so I add 105 + 5 = 110 and step as a parameter for the model to predict my pressure. That's what I'm talking about for the next minute. My question is, how would I do this to predict the next 60 minutes of the Pressure, being that I do not have the next 60 minutes of the input variables (actual values). Today I'm doing what I did for every minute and always adding the difference, always taking the last 60 minutes, is that correct? Thank you.
has comment: http://stackoverflow.com/comment/91102261
score: 0
favorite count: 0

http://stackoverflow.com/q/51972893
has answer: http://stackoverflow.com/a/51972929
tagged with: python
answer count: 4
tagged with: isinstance
type: AnsweredQuestion
tagged with: list
possible better answer: http://stackoverflow.com/a/51972929
has answer: http://stackoverflow.com/a/51973071
upvote count: 1
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/90896318
has answer: http://stackoverflow.com/a/51973040
has title: Python isinstance not working with if statement.
has comment: http://stackoverflow.com/comment/90896317
score: 0
has body: I have a list of addresses. Some address have the street, city, state, zip and others just have city, state, and zip. I made a for loop to put each element into a separate variable. The problem is I am not getting the right output so I put an if statement with isinstance(address[3], int], I did this to check if the 4th element is there then execute the code but it's just not working. I'll post below to show what I am doing and let me know where I messed up. The first address has a street and the second doesn't, so I want to substitute the address for "-". address = [['123 street name, New Orleans, LA, 12345'],['New Orleans, LA, 12345']] if isinstance(address[3], int): street = address[0] city = address[1] city = city.lstrip() state = address[2] state = state.lstrip() zip_code = address[3] else: street = "-" city = address[0] city = city.lstrip() state = address[1] state = state.lstrip() zip_code = address[2]
favorite count: 0
accepted answer: http://stackoverflow.com/a/51973040
has answer: http://stackoverflow.com/a/51972991

http://stackoverflow.com/q/51981737
tagged with: python
has comment: http://stackoverflow.com/comment/90915009
tagged with: join
score: 1
has comment: http://stackoverflow.com/comment/90914770
upvote count: 1
has title: How to save very large results of dask merge directly to the file in python?
has body: I have a large file ~1 TB which I have to join with the smaller one ~4 GB. I am trying to use dask package for this dask but result of merge is bigger than machine memory which is 128 GB and ending up with MemoryError. I am trying to keep results of merge as delayed collection but not sure how to save results directly to external file at the end. small_file = dd.read_csv('file1.txt', sep='|', dtype=str) large_file = dd.read_csv('file2.txt', sep='|', dtype=str) merged = dd.merge(large_file, small_file, on='key').to_delayed()
type: Question
answer count: 1
downvote count: 0
favorite count: 0
tagged with: dask
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/52137261

http://stackoverflow.com/q/51996230
score: 0
has body: I'd like to delete email from specific sender with python. Here is my codes to delete all emails from my email account. Question 1) How can I delete specific emails from specific sender? (ex: anyspamsender@gmail.com) Question 2) How can I delete specific emails of which email title contains specific text ? (title : Delivery Status Notification (Failure)) import imaplib box = imaplib.IMAP4_SSL('imap.gmail.com', 993) box.login("emailid","password") box.select('Inbox') typ, data = box.search(None, 'ALL') for num in data[0].split(): box.store(num, '+FLAGS', '\\Deleted') box.expunge() box.close() box.logout()
answer count: 1
tagged with: email
type: UnansweredQuestion
tagged with: python
has title: How to delete emails from specific sender by python
type: Question
has answer: http://stackoverflow.com/a/51996486

http://stackoverflow.com/a/52115824
score: 1
has body: Let show just part of the code as I do class MultiColumn(BaseEstimator, TransformerMixin): def __init__(self,columns = None): self.columns = columns # array of column names to encode def fit(self,X,y=None): return self def transform(self, X): return X[self.columns] NUMERIC = df'var1', 'var2' CATEGORICAL = df'var3', 'var4' class Imputation(BaseEstimator, TransformerMixin): def transform(self, X, y=None, **fit_params): return X.fillna(NUMERIC.median()) def fit_transform(self, X, y=None, **fit_params): self.fit(X, y, **fit_params) return self.transform(X) def fit(self, X, y=None, **fit_params): return self class Cat(BaseEstimator, TransformerMixin): def transform(self, X, y=None, **fit_params): enc = DictVectorizer(sparse = False) encc = enc.fit(CATEGORICAL.T.to_dict().values()) enc_data = encc.transform(X.T.to_dict().values()) enc_data[np.isnan(enc_data)] = 1 return enc_data def fit_transform(self, X, y=None, **fit_params): self.fit(X, y, **fit_params) return self.transform(X) def fit(self, X, y=None, **fit_params): return self And Pipeline pipeline = Pipeline([ # Use FeatureUnion to combine the features ('union', FeatureUnion( transformer_list=[ # numeric ('numeric', Pipeline([ ('selector', MultiColumn(columns=['var1', 'var2'])), ('imp', Imputation()), ('scaling', preprocessing.StandardScaler(with_mean = 0.)) ])), # categorical ('categorical', Pipeline([ ('selector', MultiColumn(columns=['var3', 'var4'])), ('one_hot', Cat()), (CategoricalImputer()) ])), ])), ('model_fitting', xgb.XGBClassifier(max_depth=3)), ])
upvote count: 1
downvote count: 0
answers question: http://stackoverflow.com/q/52055658
type: Answer

http://stackoverflow.com/q/52027891
tagged with: magic-methods
type: AnsweredQuestion
has title: To make objects of a custom class comparable, is it enough to define just a few of the members in `__eq__` and `__lt__` family?
score: 3
upvote count: 3
has answer: http://stackoverflow.com/a/52027974
type: Question
downvote count: 0
accepted answer: http://stackoverflow.com/a/52027974
answer count: 1
has body: Let's say I have a class, members of which I want to compare with the usual operators ==, &lt;, &lt;=, &gt;, and &gt;=. As I understand, this could be accomplished by initializing defining magic method __cmp__(a, b) which returns -1 (a &lt; b), 0 (a == b), or 1 (a &gt; b). It seems like __cmp__ was deprecated since Python 3 in favor of defining __eq__, __lt__, __le__, __gt__, and _ge__ methods separately. I defined __eq__ and __lt__ assuming that the default values for __le__ would look something like return a == b or a &lt; b. It seems to be not the case with the following class: class PQItem: def __init__(self, priority, item): self.priority = priority self.item = item def __eq__(self, other): return isinstance(other, PQItem) and self.priority == other.priority def __lt__(self, other): return isinstance(other, PQItem) and self.priority &lt; other.priority class NotComparable: pass x = NotComparable() y = NotComparable() # x &lt; y gives error And I get this outcome: &gt;&gt;&gt; PQItem(1, x) == PQItem(1, y) True &gt;&gt;&gt; PQItem(1, x) &lt; PQItem(1, y) False &gt;&gt;&gt; PQItem(1, x) &lt;= PQItem(1, y) Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; TypeError: unorderable types: PQItem() &lt;= PQItem() This has left me to conclude that I'll have to define all the comparison magic methods manually to make a class comparable. Is there any better way? Why has __cmp__ been deprecated? That seems like a much nicer way to deal with it
favorite count: 0
tagged with: python-3.x
tagged with: python

http://stackoverflow.com/a/51976485
has comment: http://stackoverflow.com/comment/109724546
has comment: http://stackoverflow.com/comment/90903265
has body: You are right, you can do better by using np.where, the numpy equivalent of if: def sigmoid(x): return np.where(x &gt;= 0, 1 / (1 + np.exp(-x)), np.exp(x) / (1 + np.exp(x))) This function takes a numpy array x and returns a numpy array, too: data = np.arange(-5,5) sigmoid(data) #array([0.00669285, 0.01798621, 0.04742587, 0.11920292, 0.26894142, # 0.5 , 0.73105858, 0.88079708, 0.95257413, 0.98201379])
score: 11
downvote count: 0
has comment: http://stackoverflow.com/comment/111159876
answers question: http://stackoverflow.com/q/51976461
type: Answer
has comment: http://stackoverflow.com/comment/90903274
upvote count: 11
has comment: http://stackoverflow.com/comment/114428943
has comment: http://stackoverflow.com/comment/90903305
has comment: http://stackoverflow.com/comment/90903315

http://stackoverflow.com/a/52015772
has comment: http://stackoverflow.com/comment/90999938
has comment: http://stackoverflow.com/comment/90985055
answers question: http://stackoverflow.com/q/52015536
type: Answer
has comment: http://stackoverflow.com/comment/90999162
has comment: http://stackoverflow.com/comment/90984167
upvote count: 1
has body: regex = r"(Tick2(.*?)TO_BE_MATCHED)" and if you're trying to match everything between TO_BE_MATCHED string and TickN where N is any number greater than 2; then regex = "r(Tick[2-9]{1,}(.*)TO_BE_MATCHED)"
downvote count: 0
score: 1

geotagging
tag name: geotagging
tags question: http://stackoverflow.com/q/52051522
type: Tag

http://stackoverflow.com/a/51990750
score: 1
has comment: http://stackoverflow.com/comment/90931447
has comment: http://stackoverflow.com/comment/90931319
downvote count: 0
has comment: http://stackoverflow.com/comment/90931655
has comment: http://stackoverflow.com/comment/90931210
has comment: http://stackoverflow.com/comment/90931226
has comment: http://stackoverflow.com/comment/90931178
has comment: http://stackoverflow.com/comment/90931354
answers question: http://stackoverflow.com/q/51990546
has comment: http://stackoverflow.com/comment/90931700
type: Answer
upvote count: 1
has comment: http://stackoverflow.com/comment/90931480
has comment: http://stackoverflow.com/comment/90931893
has body: Looks like you want to extend from the AbstractBaseUser (see code below), using this as your UserProfileCreateSerializer: class UserProfileCreateSerializer(serializers.ModelSerializer): """"A serializer for user data request""" location = serializers.CharField(source='profile.location') friends_count = serializers.IntegerField(source='profile.friends_count',read_only=True) profile_pic = serializers.FileField(source='profile.profile_pic',allow_empty_file=True,allow_null=True) class Meta: model = Profile fields = ( 'pk', 'username', 'email', 'password', 'location', 'friends_count', 'profile_pic', ) extra_kwargs = { 'password':{'write_only':True}, 'friends_count':{'read_only':True}, } def create(self, validated_data): """"Create and return a new User""" user = Profile( email = validated_data['email'], username = validated_data['username'] ) user.set_password(validated_data['password']) user.save() return user class ProfileUpdateSerializer(serializers.ModelSerializer): """A serializer for updating user data""" class Meta: model = Profile fields = ('location','profile_pic') Then extend from the AbstractBaseUser in models.py: from __future__ import unicode_literals from django.db import models from django.core.mail import send_mail from django.contrib.auth.models import PermissionsMixin from django.contrib.auth.base_user import AbstractBaseUser from django.utils.translation import ugettext_lazy as _ from .managers import ProfileManager class Profile(AbstractBaseUser, PermissionsMixin): email = models.EmailField(_('email address'), unique=True) username = models.CharField(_('first name'), max_length=30, blank=True) first_name = models.CharField(_('first name'), max_length=30, blank=True) last_name = models.CharField(_('last name'), max_length=30, blank=True) date_joined = models.DateTimeField(_('date joined'), auto_now_add=True) is_active = models.BooleanField(_('active'), default=True) location = models.CharField(max_length=30,blank=True) friends_count = models.PositiveIn…
has comment: http://stackoverflow.com/comment/90931754

http://stackoverflow.com/q/52072537
has comment: http://stackoverflow.com/comment/91099549
has comment: http://stackoverflow.com/comment/91095104
has comment: http://stackoverflow.com/comment/91095738
answer count: 1
has title: BeautifulSoup can't access content of <text> tag
score: 1
tagged with: parsing
favorite count: 0
tagged with: beautifulsoup
has comment: http://stackoverflow.com/comment/91096276
has comment: http://stackoverflow.com/comment/91095998
upvote count: 1
tagged with: python
tagged with: html-parsing
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52073318
tagged with: tags
has body: I'm using BeautifulSoup (version 4.4) to preprocess a Wikipedia textdump from https://dumps.wikimedia.org/enwiki/ for further parsing. The textdump document contains multiple articles, each contained in a &lt;page&gt; tag. Unfortunately, something about the document structure seems incompatible with BeautifulSoup: Within each &lt;page&gt;, the text body of an article is contained in a &lt;text&gt; block: &lt;text xml:space="preserve"&gt;...&lt;/text&gt; Once I've selected a certain &lt;page&gt; block, I should be able to access the content of the text block as page.text.string. In BeautifulSoup, .text used to be reserved for the content of a tag between its brackets. In more recent versions, .string is used for that. Unfortunately, it seems like page.text is still interpreted the same as page.string for backwards compatibility. (Edit: getattr(page, "text") does the same.) Is there any way I can get around this and access an HTML tag named &lt;text&gt;? (Edit: For a syntax example, see https://pastebin.com/WQvJn0gf.)
accepted answer: http://stackoverflow.com/a/52073318
type: Question
has comment: http://stackoverflow.com/comment/91094908
downvote count: 0

http://stackoverflow.com/comment/90927899
has text: Note that `import` will cache the existing module, so it is not costly to reimport an already imported modules. In fact the `try`-`except` block may add more overhead than that...
type: Comment
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/51989110

http://stackoverflow.com/comment/91156512
type: Comment
comment on: http://stackoverflow.com/a/52102683
has text: ...for the question answered here, https://stackoverflow.com/questions/10405515/piping-in-shell-via-python-subprocess-module is a duplicate
type: AnswerComment
score: 0

http://stackoverflow.com/a/51973974
score: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/51973396
answers question: http://stackoverflow.com/q/51973396
type: Answer
has body: Anaconda doesn't include vpython AFAIK. I think you'll need to get it from PyPI. You can do this by calling pip install vpython in your shell (terminal application on Mac). Before that, though, make sure pip is pointing to Anaconda's pip so that the packages are installed in Anaconda's site-packages. You can check this with which pip. If that path isn't the path to your Anaconda install, you'll have to update your PATH environment variable to point to Anaconda's pip. This is system dependent, so we can't really help you much with this step (i.e. we don't know where your Anaconda installation is). On Mac OSX, you can do export PATH="$PATH:/path/to/Anacondas/pip/directory" in order to set your PATH. HTH, let me know if you have any questions by commenting below.

http://stackoverflow.com/comment/91042988
type: Comment
score: 2
has text: If I were you, I would create an abstract `BaseModel` class which inherits from `models.Model` and then use that as parent to `Booking` model or other models I might need in the future. That way the code will be much cleaner and you won't have to repeat similar code all over the code base. Also if you ever need to change things in the future, you won't have to do it from each and every model class. Instead you can do it from a single place
comment on: http://stackoverflow.com/a/52044768
type: AnswerComment

http://stackoverflow.com/comment/91127681
score: 1
has text: Please consider adding a code sample, or revising the one you posted in this question. As it currently stands, its formatting and scope make it hard for us to help you; here is a [great resource](http://stackoverflow.com/help/mcve) to get you started on that. Good luck with your code!
comment on: http://stackoverflow.com/q/52088612
type: Comment
type: QuestionComment

rsa
tags question: http://stackoverflow.com/q/51995403
tag name: rsa
tags question: http://stackoverflow.com/q/51978463
type: Tag

http://stackoverflow.com/comment/90884574
score: 2
comment on: http://stackoverflow.com/a/51967246
has text: Why convert something that is already a string into a string?
type: AnswerComment
type: Comment

http://stackoverflow.com/a/52042233
type: Answer
has comment: http://stackoverflow.com/comment/91039129
score: 0
has body: You can leverage .apply() like so (@Jacco van Dorp made a solid suggestion of storing all of the found skills inside a single column, which I agree is likely the best approach to your problem): df = pd.DataFrame([['Engineer','Firm','AERO1','Work with python and Django'], ['IT','Dell','ITD4','Work with Django and R'], ['Office Assistant','Dental','OAD3','Coordinate schedules'], ['QA Engineer','Factory','QA2','Work with R and python'], ['Mechanic','Autobody','AERO1','Love the movie Django']], columns=['job_title','company','job_label','description']) Which yields: job_title company job_label description 0 Engineer Firm AERO1 Work with python and Django 1 IT Dell ITD4 Work with Django and R 2 Office Assistant Dental OAD3 Coordinate schedules 3 QA Engineer Factory QA2 Work with R and python 4 Mechanic Autobody AERO1 Love the movie Django Then define your skill set and your list comprehension to pass to .apply(): skills = ['python','R','Django'] df['skills'] = df.apply(lambda x: [i for i in skills if i in x['description'].split()], axis=1) Which yields this column: skills 0 [python, Django] 1 [R, Django] 2 [] 3 [python, R] 4 [Django] If you are still interested in having individual columns for each skill, I can edit my answer to provide that as well.
answers question: http://stackoverflow.com/q/52041823

http://stackoverflow.com/comment/91007038
type: AnswerComment
comment on: http://stackoverflow.com/a/52021000
type: Comment
score: 1
has text: Does the shape of the string match what the tokenizer is expecting? Sometimes when putting in a single instance, one forgets to make sure it is shaped correctly.

timeit
tag name: timeit
tags question: http://stackoverflow.com/q/52087546
tags question: http://stackoverflow.com/q/52046777
type: Tag

data-cleaning
tags question: http://stackoverflow.com/q/52005525
type: Tag
tags question: http://stackoverflow.com/q/52053955
tag name: data-cleaning

http://stackoverflow.com/comment/90959991
has text: edited to show full example
comment on: http://stackoverflow.com/q/52004101
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/52081530
tagged with: python
has title: Print Contents of Variables to body of email python 3.7
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/52084979
upvote count: 1
downvote count: 1
tagged with: email-formats
type: Question
tagged with: smtplib
score: 0
has body: trying to send email through python. Can get it to send email with correct text content in the body but it's printing the the actual variable name "New Companies" instead of it's content. here's the code and the resulting email. (not sure why the html tags aren't showing up in my code below, but I used html and body tags before and after the email content) Any and all help is appreciated. import smtplib from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText EMAIL_SERVER = 'blahblah' EMAIL_PORT = 25 f = open('diff.txt', 'r') NEW_COMPANIES = f.read() EMAIL_FROM = 'blabal' RECIPIENT_LIST = ['blahblah'] msg = MIMEMultipart() msg['From'] = EMAIL_FROM msg['To'] = ", ".join(RECIPIENT_LIST) msg['Subject'] = 'North Carolina New Business Registration' body = '''&lt;html&gt; &lt;body&gt; New Business Names:&lt;br&gt;&lt;br&gt; body.format('NEW_COMPANIES') &lt;br&gt;&lt;br&gt; Affiliate: r2thek &lt;br&gt;&lt;br&gt; Website Link: https://www.sosnc.gov/online_services/search/by_title/_Business_Registration &lt;/body&gt; &lt;/html&gt;''' body.format('NEW_COMPANIES') msg.attach(MIMEText(body, 'html')) smtpserver = smtplib.SMTP(EMAIL_SERVER, EMAIL_PORT) smtpserver.sendmail(EMAIL_FROM, RECIPIENT_LIST, msg.as_string()) smtpserver.quit() Email Result: New Business Names: {NEW_COMPANIES} Affiliate: r2thek Website Link: https://www.sosnc.gov/online_services/search/by_title/_Business_Registration
tagged with: http://stackoverflow.com/tag/html
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/52084979

http://stackoverflow.com/comment/90901425
type: Comment
type: QuestionComment
has text: It's not a public url, sorry
comment on: http://stackoverflow.com/q/51967309
score: 0

http://stackoverflow.com/comment/91192025
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/51994671
type: Comment
has text: ^ Got the script to run. It is writing data to the good.csv... The only problem is that it's not actually removing any of the extra characters. :D

enumerate
tags question: http://stackoverflow.com/q/52000651
tag name: enumerate
tags question: http://stackoverflow.com/q/52098874
type: Tag

http://stackoverflow.com/comment/91014973
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52032036
has text: but I think it's a good starting point, I do not see that you've shown that you've tried, and unfortunately I'm thinking that we'll do your job, the previous answer implements the property of having multiple tags based on a model, you have to add it couple of features and it will be what you want, at least try something and I will see if it is necessary to reopen the question.
score: 0

http://stackoverflow.com/comment/91086710
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52068173
has text: Thank you for the help! Perfect explanation which gave perfect results :)
score: 0

http://stackoverflow.com/comment/91091517
score: 0
comment on: http://stackoverflow.com/q/52070869
type: Comment
type: QuestionComment
has text: @CSMaverick I get CSV file as my output. I want to convert that as tuple.

http://stackoverflow.com/a/51970635
has body: I hope it will be helpful. I think it isn't pythonic, but it works: def outlier_detection(points, limit): outliers_index = list() k=0 for i in range(0,len(points)-1): if abs(points[i-k] - points[i+1]) &gt;= limit: k+=1 outliers_index.append(i+1) else: k=0 return outliers_index outlier_detection(df['small_changing'].values, 0.15) OUT: [7, 8, 9, 10, 11, 12, 21, 22, 23, 24, 25, 26, 27, 28, 29]
accepted answer of: http://stackoverflow.com/q/51968951
downvote count: 0
answers question: http://stackoverflow.com/q/51968951
type: AcceptedAnswer
upvote count: 3
type: Answer
score: 3

http://stackoverflow.com/q/52042758
tagged with: python
has title: Append elements in the value field of a dictionary using comprehensions
type: Question
has comment: http://stackoverflow.com/comment/91036427
has comment: http://stackoverflow.com/comment/91036336
tagged with: list-comprehension
has answer: http://stackoverflow.com/a/52042866
has comment: http://stackoverflow.com/comment/91036376
upvote count: 2
score: 0
has body: I have a list of elements, lets say: y = [1, 3, 1, 5, 1] And I would like to create a dictionary where: Keys: are the elements in y Values: is a list of the elements that appear before the Key in y I attempted the following comprehension. a={elem:y[i] for i, elem in enumerate(y[1:])} However, since the value field in the dictionary is not a list, it only keeps the previous element in the last occurrence of the key. In other words, for this example I get the following: {3: 1, 1: 5, 5: 3} Is there a way to do so using comprehensions ? Note: I forgot to add the desired result. {3: [1], 1: [3,5], 5: [1]}
downvote count: 2
answer count: 3
tagged with: dictionary-comprehension
has answer: http://stackoverflow.com/a/52042879
has answer: http://stackoverflow.com/a/52043100
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/91036420
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91036469

http://stackoverflow.com/q/52083327
accepted answer: http://stackoverflow.com/a/52801679
tagged with: amazon-ec2
has answer: http://stackoverflow.com/a/52801679
has comment: http://stackoverflow.com/comment/91118097
tagged with: python
has body: I am running a python3 script on a Amazon EC2 t2.micro instance (Ubuntu 16.04 LTS). Strangely, the CPU usage drops to baseline performance after some time although I still have enough CPU credits available to make the CPU burst. What causes this behavior and how can I avoid it? Edit 1 Output of df -h: Filesystem Size Used Avail Use% Mounted on udev 488M 0 488M 0% /dev tmpfs 100M 11M 89M 11% /run /dev/xvda1 7.7G 3.0G 4.8G 39% / tmpfs 496M 0 496M 0% /dev/shm tmpfs 5.0M 0 5.0M 0% /run/lock tmpfs 496M 0 496M 0% /sys/fs/cgroup /dev/loop1 13M 13M 0 100% /snap/amazon-ssm-agent/295 /dev/loop2 87M 87M 0 100% /snap/core/4917 /dev/loop3 87M 87M 0 100% /snap/core/5145 /dev/loop4 13M 13M 0 100% /snap/amazon-ssm-agent/495 tmpfs 100M 0 100M 0% /run/user/1000 /dev/loop5 88M 88M 0 100% /snap/core/5328
has title: Amazon EC2 t2.micro instance stops bursting although CPU credit balance is positive
type: AnsweredQuestion
type: Question
has comment: http://stackoverflow.com/comment/91117516
score: 0
answer count: 1

http://stackoverflow.com/q/52044489
favorite count: 0
has answer: http://stackoverflow.com/a/52044629
tagged with: python-3.x
tagged with: python
accepted answer: http://stackoverflow.com/a/52044629
linked to: http://stackoverflow.com/q/38511444
downvote count: 2
tagged with: python-requests
type: Question
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91039841
score: 3
upvote count: 5
answer count: 1
has title: How to get content length for google drive download ?
has body: Using requests module to download a file from google drive how to get the content length?

http://stackoverflow.com/comment/90890676
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51969930
has text: yes, its the simple regex `including = re.findall('\((.*?)\)',s)`

http://stackoverflow.com/a/52054142
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52053955
type: Answer
upvote count: 1
has body: I a bit changed MaxU answer: df = pd.DataFrame({'Year_Q': ['2010 Q1', '2015 Q2']}) df['Dates'] = pd.PeriodIndex(df['Year_Q'].str.replace(' ', ''), freq='Q').to_timestamp() print (df) Year_Q Dates 0 2010 Q1 2010-01-01 1 2015 Q2 2015-04-01 EDIT: df['Dates'] = pd.PeriodIndex(df['Year_Q'].str.replace(' ', ''), freq='Q').to_timestamp(how='e') print (df) Year_Q Dates 0 2010 Q1 2010-03-31 1 2015 Q2 2015-06-30
has comment: http://stackoverflow.com/comment/91058796
score: 1
has comment: http://stackoverflow.com/comment/91059054
answers question: http://stackoverflow.com/q/52053955

http://stackoverflow.com/comment/91015136
has text: Why don't you precompute the random number necessary to have the pretendangle within your limit. Then use random number within that range.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52031687

http://stackoverflow.com/comment/91025651
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52036176
score: 0
has text: The strangeness is that it completely doesn't reflect what is drawn in the scene. The scene is "full" (triangles are drawn all over the image, with no "blank" spaces). Also - The values that are not 255, are very close to it

http://stackoverflow.com/comment/91130010
has text: Could you put the output example?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52090045
score: 0

http://stackoverflow.com/a/52394254
type: Answer
has body: The hexEncode function is taking a string and converting to a series of hex representations of the constituent bytes of it's UTF8 encoded representataion. The equivalent in Python would be to encode an input unicode string in UTF-8 and then re-encode the result of that in hex, e.g. &gt;&gt;&gt; import binascii &gt;&gt;&gt; binascii.hexlify('d'.encode('utf-8')) b'64' &gt;&gt;&gt; binascii.hexlify('¡¢£¤¥'.encode('utf-8')) b'c2a1c2a2c2a3c2a4c2a5' Note: in Python 2.7 this would be — &gt;&gt;&gt; 'd'.encode('utf-8').encode('hex') '64' &gt;&gt;&gt; u'¡¢£¤¥'.encode('utf-8').encode('hex') 'c2a1c2a2c2a3c2a4c2a5' If you test that with your example password, it should produce the same output as for the website, with one caveat. hexEncode('d') "64000000" Notice that the Javascript adds a number of trailing 0's, making the length of the string a multiple of 8. We need to pad the result we have to get the same output. &gt;&gt;&gt; s = binascii.hexlify('d'.encode('utf-8')) &gt;&gt;&gt; n = len(s) &gt;&gt;&gt; from math import ceil &gt;&gt;&gt; next_8_multiple = int(ceil(n/8.0) * 8) &gt;&gt;&gt; s.ljust(next_8_multiple, b'0') b'6400000000' We can wrap that up in a complete function: from math import ceil import binascii def hex_encode_and_pad(s): hex = binascii.hexlify(s.encode('utf-8')) n = len(hex) next_8_multiple = int(ceil(n/8.0) * 8) zeros_to_append = next_8_multiple - n return hex.ljust(next_8_multiple, b'0') This now gives the same result as for the Javascript function: &gt;&gt;&gt; hex_encode_and_pad('d') '64000000' The next step would be to wrap it in a string representation of the JSON. You can either do that by hand-coding the string + just interpolating the token, e.g. value = '{"TokenId":"%s","Password":""}' % token Or by creating the JSON string from a Python dictionary — import json data = {'TokenId': token, 'Password': ''} value = json.dumps(data) The complete code based on the example request shown above would be: import binascii import json from math import ceil f…
has comment: http://stackoverflow.com/comment/91839741
has comment: http://stackoverflow.com/comment/91856206
has comment: http://stackoverflow.com/comment/97125337
has comment: http://stackoverflow.com/comment/91835542
accepted answer of: http://stackoverflow.com/q/52107447
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/52107447
has comment: http://stackoverflow.com/comment/91835276
downvote count: 0
has comment: http://stackoverflow.com/comment/91854430
has comment: http://stackoverflow.com/comment/91921569
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/91840148

http://stackoverflow.com/q/52034239
tagged with: python-itertools
has comment: http://stackoverflow.com/comment/91019004
has comment: http://stackoverflow.com/comment/91018430
score: -1
has comment: http://stackoverflow.com/comment/91018379
has comment: http://stackoverflow.com/comment/91018579
answer count: 1
has answer: http://stackoverflow.com/a/52070884
favorite count: 0
has body: How can I get, with python, all alphanumeric combinations with N digits in the combinations for 5 positions. The characters can repeat themselves. The rest (5-N) characters should be letters. Examples for what I mean: Number of digits = 1 should generate: aygd3 2afvd jde6a Number of digits = 2 should generate: ay5d3 2af8d jde64 Number of digits = 3 should generate: a15d3 26f8d jd464 Number of digits = 4 should generate: 315d3 26f87 9d464
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/52070884
downvote count: 2
upvote count: 1
has title: How to get all alphanumeric combinations with N digits on 5 positions
type: Question
tagged with: combinations

http://stackoverflow.com/comment/91017529
has text: I think pd.melt can help you out here.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52033359

http://stackoverflow.com/q/52066863
tagged with: anytree
upvote count: 2
type: UnansweredQuestion
has body: I have a dataframe like this: Genome Evolved_from 3435XY 233Z 5662YY 1099N 1099N 234YY 234YY 22QQ 43543Z 232XX 4566Y 1099N 213TY 15Q 234YY 12Q 7968ZT 2132X 77792 213TY 2455Z 12Q First I want to determine the generation of genome, so resulting output should be something like this: Genome Evolved_from generation 3435XY 233Z 1 5662YY 1099N 1 1099N 234YY 3 2212QQ 234YY 3 43543Z 232XX 1 4566Y 1099N 1 213TY 15Q 1 234YY 12Q 2 7968ZT 2132X 1 77792 213TY 2 2455Z 12Q 2 How could I achieve this? and how could I represent this relationship on the graph, let's say for one particular chain
tagged with: python
has comment: http://stackoverflow.com/comment/91103694
answer count: 0
score: 1
tagged with: matplotlib
downvote count: 1
type: Question
has title: Creating an inheritance tree from pandas dataframe
has comment: http://stackoverflow.com/comment/91103888
tagged with: pandas
favorite count: 0

http://stackoverflow.com/q/52067427
upvote count: 4
has answer: http://stackoverflow.com/a/54672736
downvote count: 0
has answer: http://stackoverflow.com/a/56177674
tagged with: ubuntu-16.04
tagged with: tensorflow
type: Question
answer count: 2
score: 4
has body: I tried installing Tensorflow object detection API from this guide: https://github.com/tensorflow/models/blob/master/research/object_detection/g3doc/installation.md I have installed all the dependencies and when I try to test the run the .py file it throws the "got an unexpected keyword argument 'serialized_options' " as mentioned in the title. As mentioned by most of the people regarding the downgrading of protobuf protoc version to 3.4, I have tried doing that and my version is 3.4, but still it throws the same error. Please help.
favorite count: 0
tagged with: object-detection-api
tagged with: protocol-buffers
has title: Tensorflow: __new__() got an unexpected keyword argument 'serialized_options' in Object Detection API
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/q/51994344
has comment: http://stackoverflow.com/comment/90951566
has comment: http://stackoverflow.com/comment/134030475
tagged with: python
has answer: http://stackoverflow.com/a/52110912
type: AnsweredQuestion
tagged with: machine-learning
has comment: http://stackoverflow.com/comment/90939192
possible better answer: http://stackoverflow.com/a/52001520
downvote count: 1
tagged with: tensorflow
has body: I have a task to classify seeds depending on the defect. I have around 14k images in 7 classes (they are not equal size, some classes have more photos, some have less). I tried to train Inception V3 from scratch and I've got around 90% accuracy. Then I tried transfer learning using pre-trained model with ImageNet weights. I imported inception_v3 from applications without top fc layers, then added my own like in documentation. I ended with the following code: # Setting dimensions img_width = 454 img_height = 227 ########################### # PART 1 - Creating Model # ########################### # Creating InceptionV3 model without Fully-Connected layers base_model = InceptionV3(weights='imagenet', include_top=False, input_shape = (img_height, img_width, 3)) # Adding layers which will be fine-tunned x = base_model.output x = GlobalAveragePooling2D()(x) x = Dense(1024, activation='relu')(x) predictions = Dense(7, activation='softmax')(x) # Creating final model model = Model(inputs=base_model.input, outputs=predictions) # Plotting model plot_model(model, to_file='inceptionV3.png') # Freezing Convolutional layers for layer in base_model.layers: layer.trainable = False # Summarizing layers print(model.summary()) # Compiling the CNN model.compile(optimizer = 'adam', loss = 'categorical_crossentropy', metrics = ['accuracy']) ############################################## # PART 2 - Images Preproccessing and Fitting # ############################################## # Fitting the CNN to the images train_datagen = ImageDataGenerator(rescale = 1./255, rotation_range=30, width_shift_range=0.2, height_shift_range=0.2, shear_range = 0.2, zoom_range = 0.2, horizontal_flip = True, preprocessing_function=preprocess_input,) valid_datagen = ImageDataGenerator(rescale = 1./255, preprocessing_function=preprocess_input,) train_generator = train_datagen.flow_from_directory("dataset/training_set", target_size=(img_height, img_width), batch_size = 4, class_mode = "categorical", shuffle = True…
type: Question
has answer: http://stackoverflow.com/a/52001520
upvote count: 5
has title: Transfer learning bad accuracy
score: 4
accepted answer: http://stackoverflow.com/a/52110912
answer count: 2
has comment: http://stackoverflow.com/comment/90953499
has comment: http://stackoverflow.com/comment/90951619
tagged with: keras
tagged with: transfer-learning
favorite count: 0

http://stackoverflow.com/comment/91022250
comment on: http://stackoverflow.com/q/52036014
has text: @Ev.Kounis no, same problem
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/114483925
has text: You *must disclose affiliation in the post* when linking to something you're affiliated with. If you don't disclose affiliation, it's considered spam. See: [What signifies "Good" self promotion?](https://meta.stackexchange.com/q/182212), [some tips and advice about self-promotion](https://stackoverflow.com/help/promotion), [What is the exact definition of "spam" for Stack Overflow?](https://meta.stackoverflow.com/q/260638), and [What makes something spam](https://meta.stackexchange.com/a/58035)
type: Comment
comment on: http://stackoverflow.com/a/64749594
score: 0
type: AnswerComment

http://stackoverflow.com/comment/90900401
type: QuestionComment
type: Comment
has text: @KRKirov I scratched my head and re-wrote it all completely, I hope it's better to understand, but it still does not work :(... Maybe you'll be able to spot a mistake/mistakes
comment on: http://stackoverflow.com/q/51966502
score: 0

http://stackoverflow.com/q/51993114
has body: I know that my question sounds desperate and also it is not a short reproducible example. However I am writing my thesis and I tried a test print. I couldnt print the document, written in TeX and viewed in pdf, because of one plot that is based on python (all other ones are created in R). I would be so gratefull to someone how could have a quick look at it. I'm really desperate right now because I don't want to take this graphic out of my work. I am not really familiar with python as I am using R, but just wanted to generate this plot for my thesis. the Code. I am referring to the figure in the section "Lasso coordinate descent Vary parameter l (lamda) for different results" (field [20]). I am trying to save it as follows: %matplotlib inline fig = plt.figure(figsize = (16,8)) #Surface plot ax = fig.add_subplot(1, 2, 1, projection='3d') ax.plot_surface(T1, T2, Z, rstride = 5, cstride = 5, cmap = 'jet', alpha=0.5) ax.plot(theta_0,theta_1,J_history_lasso, marker = '*', color = 'r', alpha = .4, label = 'Gradient descent') ax.set_xlabel('theta 1') ax.set_ylabel('theta 2') ax.set_zlabel('error') ax.set_title('RSS gradient descent: Root at {}'.format(theta_result_lasso.ravel())) ax.view_init(25, -40) #Contour plot ax = fig.add_subplot(1, 2, 2) ax.contour(T1, T2, Z, 100, cmap = 'jet') ax.quiver(theta_0[:-1], theta_1[:-1], anglesx, anglesy, scale_units = 'xy', angles = 'xy', scale = 1, color = 'r', alpha = .9) ax.set_xlabel(r'$\beta_1$', fontsize=20, labelpad = 10) ax.set_ylabel(r'$\beta_2$', fontsize=20, labelpad = 10) ax.set_zlabel(r'$\mathcal{L}(\beta)$', fontsize=20, labelpad = 10) ax.tick_params(labelsize=16) ax.set_title(r'Globales Minimum $\hat \beta$ = [{:0.0f}, {:0.2f}]'.format(roundi[0],roundi[1]), fontsize=20, pad=40) plt.show() fig.savefig("l18.pdf", bbox_inches='tight') but I cant print out the regarding pdf. I also tried different types of printers. So it should be problem with the regarding figure.
has comment: http://stackoverflow.com/comment/90936664
score: 0
answer count: 2
has comment: http://stackoverflow.com/comment/90936047
accepted answer: http://stackoverflow.com/a/51994405
tagged with: python
has comment: http://stackoverflow.com/comment/90935993
has answer: http://stackoverflow.com/a/51993666
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90936022
has comment: http://stackoverflow.com/comment/90936116
has comment: http://stackoverflow.com/comment/90936588
has comment: http://stackoverflow.com/comment/90935790
tagged with: matplotlib
possible better answer: http://stackoverflow.com/a/51993666
type: Question
has comment: http://stackoverflow.com/comment/90936448
has comment: http://stackoverflow.com/comment/90936071
has comment: http://stackoverflow.com/comment/90937518
linked to: http://stackoverflow.com/q/21875356
has comment: http://stackoverflow.com/comment/90936389
has answer: http://stackoverflow.com/a/51994405
has comment: http://stackoverflow.com/comment/90935980
has title: Cant plot an Python matplotlib figure in pdf

http://stackoverflow.com/q/52034983
type: Question
has body: Let's say I have network with following params: fully convolutional network for semantic segmentation loss = weighted binary cross entropy (but it could be any loss function, doesn't matter) 5 classes - inputs are images and ground truths are binary masks Batch size = 16 Now, I know that the loss is calculated in the following manner: binary cross entropy is applied to each pixel in the image with regards to each class. So essentially, each pixel will have 5 loss values What happens after this step? When I train my network, it prints only a single loss value for an epoch. There are many levels of loss accumulation that need to happen to produce a single value and how it happens is not clear at all in the docs/code. What gets combined first - (1) the loss values of the class(for instance 5 values(one for each class) get combined per pixel) and then all the pixels in the image or (2)all the pixels in the image for each individual class, then all the class losses are combined? How exactly are these different pixel combinations happening - where is it being summed / where is it being averaged? Keras's binary_crossentropy averages over axis=-1. So is this an average of all the pixels per class or average of all the classes or is it both?? To state it in a different way: how are the losses for different classes combined to produce a single loss value for an image? This is not explained in the docs at all and would be very helpful for people doing multi-class predictions on keras, regardless of the type of network. Here is the link to the start of keras code where one first passes in the loss function. The closest thing I could find to an explanation is loss: String (name of objective function) or objective function. See losses. If the model has multiple outputs, you can use a different loss on each output by passing a dictionary or a list of losses. The loss value that will be minimized by the model will then be the sum of all individual losses from keras. So does this me…
tagged with: python
has comment: http://stackoverflow.com/comment/91021457
accepted answer: http://stackoverflow.com/a/52210610
has comment: http://stackoverflow.com/comment/91020645
answer count: 2
tagged with: machine-learning
tagged with: tensorflow
upvote count: 16
has title: how is total loss calculated over multiple classes in Keras?
has comment: http://stackoverflow.com/comment/91021209
has comment: http://stackoverflow.com/comment/91021360
has comment: http://stackoverflow.com/comment/91021772
linked to: http://stackoverflow.com/q/52172859
possible better answer: http://stackoverflow.com/a/52105974
has comment: http://stackoverflow.com/comment/91021289
has answer: http://stackoverflow.com/a/52105974
tagged with: deep-learning
has comment: http://stackoverflow.com/comment/91021898
has comment: http://stackoverflow.com/comment/91021656
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52210610
downvote count: 0
tagged with: keras
score: 16
favorite count: 0

http://stackoverflow.com/comment/91044563
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52027382
has text: If you feel like adding the make and model of your camera to your question (click `edit` just above this comment) that may help other folk find it.

http://stackoverflow.com/comment/90895644
score: 0
has text: No there isn't. I will my attempt in the code, but it is not working.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51958138

http://stackoverflow.com/comment/90938012
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51993871
type: Comment
has text: Glad I could help!

http://stackoverflow.com/comment/90995994
type: QuestionComment
has text: I'd recommend seeing this previous SO question: https://stackoverflow.com/questions/4325733/save-a-subplot-in-matplotlib
comment on: http://stackoverflow.com/q/52017297
score: 0
type: Comment

http://stackoverflow.com/a/52095126
type: Answer
answers question: http://stackoverflow.com/q/52052558
has body: Looks like the + button where you need to click to get the window (shown in second figure) is ownerdrawn. So, there is only one way to bring up the "Add folder to search" window: use click_input method by passing coordinates. Once the window comes up, you can use the below code to set the value: app.DuplicatePhotoCleaner.child_window(title="Folder:", auto_id="1152", control_type="Edit").set_text('Hello world') #or app.DuplicatePhotoCleaner['Folder:Edit'].set_text('Hello world') Application().connect(title='Add folder to search')... Please go though pywinauto docs for further info.
score: 0

http://stackoverflow.com/comment/91079823
score: 0
type: Comment
comment on: http://stackoverflow.com/q/52064613
type: QuestionComment
has text: As a module, I would accept it. My primary goal is to flag cases when a function or class is imported rather than the package that contains it. Unfortunately I don't see a way to use `ModuleSpec` to identify it as a module vs. something else (class/function/other?).

http://stackoverflow.com/comment/90869349
score: 1
comment on: http://stackoverflow.com/a/51959147
has text: I'm using windows system. Is there any method to inspect .img file on Win system? Btw the .img file is automatically generated by Charge Coupled Device System. I can use winRAR and 7zip to open the .img file. But I need to read it in python script. Thanks for all your help.
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/90929935
score: 0
comment on: http://stackoverflow.com/q/51986528
type: Comment
type: QuestionComment
has text: non monochrome colormaps have the same issue, since the coloring is done in a linear fashion

http://stackoverflow.com/comment/90995167
type: Comment
has text: `%s` is for string fomatting
type: QuestionComment
comment on: http://stackoverflow.com/q/52022242
score: 0

http://stackoverflow.com/comment/91138286
score: 0
type: Comment
type: QuestionComment
has text: Thanks for uploading that image. It seems the data is smoothed and also enhanced, but I don't think I can help you with this. This might be something where you need the actual data and then try several different things, like thresholding or other methods (maybe even specific to the field you're working in.) sorry...
comment on: http://stackoverflow.com/q/52053761

http://stackoverflow.com/q/52022712
upvote count: 1
answer count: 1
has comment: http://stackoverflow.com/comment/90995955
has title: Python shell 3.7 restarting program without displaying output or errors
favorite count: 0
tagged with: python-3.x
tagged with: python
has comment: http://stackoverflow.com/comment/90995810
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90995977
has comment: http://stackoverflow.com/comment/90995714
downvote count: 1
type: Question
has answer: http://stackoverflow.com/a/52022751
accepted answer: http://stackoverflow.com/a/52022751
has body: Note that I am an absolute newbie with very little coding experience. I am teaching myself from the ground up and trying my best to google every question I have and comb through my code before asking. I'd like to continue learning as quickly as possible but I'm getting stuck on very simple things. I'm working on creating classes in Python 3 for the first time and upon trying to run, my program restarts with no error message or output. My operating system is Windows 10. I've seen answers to questions similar to mine that say it could be an OS problem but I doubt that because this is a very new computer. https://i.sstatic.net/vFW3B.png https://i.sstatic.net/bmB1B.png
score: 0

http://stackoverflow.com/comment/91098524
comment on: http://stackoverflow.com/q/52073875
type: Comment
type: QuestionComment
has text: code formatting
score: 0

http://stackoverflow.com/q/52104043
has comment: http://stackoverflow.com/comment/91170953
has answer: http://stackoverflow.com/a/52113220
favorite count: 0
linked to: http://stackoverflow.com/q/32432887
tagged with: cx-freeze
has title: Cannot compile with cx_Freeze
has answer: http://stackoverflow.com/a/52235200
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/39000452
linked to: http://stackoverflow.com/q/47359439
tagged with: python
linked to: http://stackoverflow.com/q/39007134
downvote count: 0
score: 1
tagged with: executable
type: Question
has body: I made a program which worked fine and now I tried to compile it with cx_Freeze but got TypeError: can only concatenate list (not "NoneType") to list error. So how can I fix this problem so that I can compile my program correctly to .exe My configuration: python 2.7, cx_Freeze 5.1.1 My program contains following modules: os, time, string, random, smtplib, _winreg, requests, pyautogui, subprocess, email, SimpleCV My setup file code: import sys from cx_Freeze import setup, Executable company_name = 'My own company' product_name = 'Program' sys.setrecursionlimit(5000) bdist_msi_options = { 'add_to_path': False, 'initial_target_dir': r'[C:\Program Files (x86)]\%s\%s' % (company_name, product_name), } path = sys.path build_exe_options = { "path": path, "icon": "myicon.ico"} base = None if sys.platform == "win32": base = "Win32GUI" exe = Executable(script='My_program.py', base=base, icon='myicon.ico', ) setup(name = "My program", version = "1.1", description = "This is my first program", executables = [exe], options = {'bdist_msi': bdist_msi_options}) Error: Traceback (most recent call last): File "setup.py", line 33, in &lt;module&gt; options = {'bdist_msi': bdist_msi_options}) File "C:\Python27\lib\site-packages\cx_Freeze\dist.py", line 349, in setup distutils.core.setup(**attrs) File "C:\Python27\lib\distutils\core.py", line 151, in setup dist.run_commands() File "C:\Python27\lib\distutils\dist.py", line 953, in run_commands self.run_command(cmd) File "C:\Python27\lib\distutils\dist.py", line 972, in run_command cmd_obj.run() File "C:\Python27\lib\distutils\command\build.py", line 127, in run self.run_command(cmd_name) File "C:\Python27\lib\distutils\cmd.py", line 326, in run_command self.distribution.run_command(command) File "C:\Python27\lib\distutils\dist.py", line 972, in run_command cmd_obj.run() File "C:\Python27\lib\site-packages\cx_Freeze\dist.py", line 219, in run freezer.Freeze() File "C:\Python27\lib\site-packages\cx_Freeze\freezer.py", line 623, in Freeze s…
answer count: 2
upvote count: 1
tagged with: windows
has comment: http://stackoverflow.com/comment/91174963

http://stackoverflow.com/a/52093955
has comment: http://stackoverflow.com/comment/91143945
has comment: http://stackoverflow.com/comment/91144001
accepted answer of: http://stackoverflow.com/q/52093875
has comment: http://stackoverflow.com/comment/91138973
type: Answer
upvote count: 6
has comment: http://stackoverflow.com/comment/91138014
score: 6
answers question: http://stackoverflow.com/q/52093875
has body: They are very similar: .get_text is a function that returns the text of a tag as a string .text is a property that calls get_text (so it's identical, except you don't use parantheses) .getText is an alias of get_text I would use .text whenever possible, and .get_text(...) when you need to pass custom arguments (e.g. foo.get_text(strip=True, seperator='\n')).
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/91095606
comment on: http://stackoverflow.com/q/52072770
has text: This is much better. Please edit your attempt into the question and explain how the result differs from the desired.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52084719
has comment: http://stackoverflow.com/comment/91119957
type: AnsweredQuestion
type: Question
has title: Index error list page out of range on danbooru twitter bot
has comment: http://stackoverflow.com/comment/91120418
score: 0
has answer: http://stackoverflow.com/a/52085104
accepted answer: http://stackoverflow.com/a/52085104
answer count: 1
tagged with: python
has body: i am using a code that i found in github, i had to modify somethings, it works, but sometimes (even when working) it gives Index error page out of range and then stop working. File "bot.py", line 36, in module imageSource = pageTable[arrayNum]["file_url"] IndexError: list index out of range Here is my code import time import requests import tweepy import urllib import os import random page = 1 url = 'https://danbooru.donmai.us/posts.json?tags=shimakaze_(kantai_collection) rating:s&amp;limit=1000&amp;page=' consumer_key = '' consumer_secret = '' access_key = '' access_secret = '' auth = tweepy.OAuthHandler(consumer_key, consumer_secret) auth.set_access_token(access_key, access_secret) api = tweepy.API(auth) while True: try: random.seed() jsURL = url + str(random.randint(1,1000)) response = requests.get(jsURL) pageTable = response.json() arrayNum = random.randint(0,5) print arrayNum imageSource = pageTable[arrayNum]["file_url"] imageURL = imageSource print imageURL sourceURL = "http://danbooru.donmai.us/posts/" + str(pageTable[arrayNum]["id"]) print sourceURL urllib.urlretrieve(imageURL, 'image.jpg') . tweetString = sourceURL + " " api.update_with_media('image.jpg', status=tweetString) os.remove('image.jpg') post. Limited to 500 requests/hour. time.sleep(600) except tweepy.error.TweepError: print "Image too large, finding a different image.." arrayNum = random.randint(0,5) line gives the error, that code generates a 0 - 5 numbers, and use as danbooru page, so i don't know why it gives an IndexError

http://stackoverflow.com/comment/90975567
type: AnswerComment
type: Comment
has text: It's not here because it's not important. The issue is with this recursive function
comment on: http://stackoverflow.com/a/52011856
score: 0

http://stackoverflow.com/a/51979258
score: 4
type: Answer
has body: You could try using re.findall with the following pattern, for Ph.D. s = 'Richard Feynman had a Ph.D. and Albert Einstein also had a phd' print(len(re.findall('\\b(?i)ph\.?d\.?\\b', s))) 2 Demo If you wanted to count all degree types together, then you could still use a single call to re.findall using a regex pattern with an alternation: (?i)ph\.?d\.?|md|jd If you needed separate counts, then you could make separate calls to re.findall.
upvote count: 4
answers question: http://stackoverflow.com/q/51979193
downvote count: 0

http://stackoverflow.com/a/72339816
downvote count: 2
score: -2
answers question: http://stackoverflow.com/q/52030496
type: Answer
upvote count: 0
has body: add this in you python file if __name__ == '__main__': app.run(debug=True)

http://stackoverflow.com/a/52016344
score: 2
answers question: http://stackoverflow.com/q/52015991
has body: In the 1st code sample, the Entry widgets are created by the __init__ function (when the instance is created), through the userEntryFunc function, then packed. In the 2nd sample, however, the Temp class creates nothing on when created, its getValue function must be called externally. The error you are facing happens because clientName and clientName2 are actually assigned to the return value of getValue, not the Temp instance. To fix this, you need to assign the instances to variables, then call the getValue function, like so: clientName = Temp(root, "Client Name") clientName.getValue() clientName2 = Temp(root, "Client Name2") clientName2.getValue() Also note that the line: lister = [clientName, clientName2] In example 1 will create an error, instead use: lister = [Name, Name2] Edit: Above problem has now been fixed
type: AcceptedAnswer
downvote count: 0
type: Answer
upvote count: 2
accepted answer of: http://stackoverflow.com/q/52015991

django-apps
tag name: django-apps
tags question: http://stackoverflow.com/q/52014962
type: Tag

http://stackoverflow.com/q/52100442
type: Question
duplicate of: http://stackoverflow.com/q/38987
answer count: 1
has body: I am curious why this works m1, m2 = {'a': 1, 'b': 2}, {'a1': 11, 'b': 2} {**m1, **m2} while this does not: {**m for m in (m1, m2)} Wouldn't it make sense for dict comprehension to 'understand' the new syntax? Edit (hopefully, temporary): in response to 'possible duplicate' flag. I am aware of that other question. I hope it is clear that I am not asking how to merge dictionaries.
score: 0
tagged with: python-3.x
linked to: http://stackoverflow.com/q/38987
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/52100933
has comment: http://stackoverflow.com/comment/91151985
has title: Syntax for merging dictionaries?

http://stackoverflow.com/comment/91026758
score: 0
comment on: http://stackoverflow.com/q/52035463
type: Comment
type: QuestionComment
has text: the output to that particular audio file is: *what if somebody decides to break it be careful that you keep adequate coverage but look for places to save money baby it's taking longer to get things squared away than the bankers expected during the wife or ones company may win her tax hated retirement income to boost is helpful to saving Rags are hers Lee tossed on the two naked bones* which is about the first 22 seconds of the 52s audio file :(

http://stackoverflow.com/q/52020648
tagged with: python
answer count: 1
downvote count: 1
has body: I would like to get a numeric or alphanumeric character from a table-like structure This table-like structure may contain some rubbish data or unorganized data For Example, ''' 5. Item | 6.Marks and 7. Numberand kind of packages; 8. Ori 9. Quantity (Gross weight or 10. Invoice number ` numbers on description of goods including Conferring other measurement), and number(s) packages HS Code (6 digits) and brand Criterion (see value (FOB) where RVC is and date of cnaommep(ainyf apipslsiucianbglet)h.irNdapmaertoyf Overleaf Notes) appppilied (see.Overilseaaff NoNtoteess)), minvvooice(s) invoice UF applicable) 91501937''' The goal is to get the numeric number under the field invoice which is 91501937 Here this is an output from an OCR and I have the locations This is how it looks like in the Searchable PDF formate. The Problem here that Regex was not valid I tried tabula but this structure is considered rubbish for tabula Tried some Regex Like re.search(r'(invvooice(s)).*(\d+)',first_string,re.DOTALL) but is very with regex and can get anything.
has comment: http://stackoverflow.com/comment/90991724
has title: Extract data from a table-like structure using python
upvote count: 0
has comment: http://stackoverflow.com/comment/90991871
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/52021143
type: Question
favorite count: 0
score: -1

http://stackoverflow.com/a/52005502
accepted answer of: http://stackoverflow.com/q/52001891
answers question: http://stackoverflow.com/q/52001891
upvote count: 4
type: AcceptedAnswer
downvote count: 0
has body: Following https://stackoverflow.com/a/50630390/1021819 and building (but not very much) on the comment by Dan Masek, the required extra step is simply to use im_buffer.tobytes(), which returns a bytestring that can be sent through a stream. Python OpenCV images do seem to be represented as pure numpy arrays. As pointed out by Dan Masek, the arrays can be transformed using cv2.imencode() into TIFF, PNG, BMP, JPG etc. There is obviously some debate around choice of formats and compression. In the case above there was a preference for lossless compression, implying TIFF, BMP or PNG (still there will be debate). The python bindings to OpenCV have no tunable parameters for TIFF compression (unlike(?) the C++ bindings?), so it's not very easy to discover what is being done there. The compression level could apparently be better using other libraries but my aim was to minimize dependencies (see above). A BMP-encoded image was no smaller than a TIFF one. PNG compression is tunable in python OpenCV, and setting cv2.imencode('.png', nparr, [int(cv2.IMWRITE_PNG_COMPRESSION),1]) has given the best size-speed trade-off so far. Thanks.
type: Answer
score: 4

http://stackoverflow.com/comment/91096119
type: AnswerComment
score: 1
type: Comment
comment on: http://stackoverflow.com/a/52072654
has text: Thanks @ruohola, alas this throws a vast list of `..removing breaks dependency 'python'`.

http://stackoverflow.com/comment/91131424
type: Comment
score: 1
type: QuestionComment
comment on: http://stackoverflow.com/q/52090551
has text: It might be possible, but only with a self written token analyzer/parser and a lot of effort. Can you modify the output, so it prints out real json? Can you confirm this is a php array? You can convert a php array to json with `$json = json_encode($myArray);`

http://stackoverflow.com/q/52030440
has answer: http://stackoverflow.com/a/52030653
tagged with: python
score: 2
type: AnsweredQuestion
upvote count: 2
possible better answer: http://stackoverflow.com/a/52030653
has title: How to convert transform a dataframe in python
type: Question
has body: I have a dataframe with the following values Date, value 2017/1/1, 5 2017/4/1, 6 2017/4/5, 12 2017/7/2, 15 2018/4/1, 50 2018/7/7, 11 2017/1/1, 5 I would like to convert this dataframe to the following format where the columns are the year/month ad the values are in the rows 2017/1 2017/4 2017/7 2018/1 2018/4 2018/7 5 6 15 5 50 11 12 How can I do that?
has comment: http://stackoverflow.com/comment/91011591
has answer: http://stackoverflow.com/a/52030478
answer count: 2
tagged with: pandas
downvote count: 0
has comment: http://stackoverflow.com/comment/91011367
favorite count: 0
accepted answer: http://stackoverflow.com/a/52030478

http://stackoverflow.com/comment/91039043
comment on: http://stackoverflow.com/q/52044065
score: 0
has text: Welcome to Stack Overflow. Can you clarify your question? If `product` has the attributes you want, what's stopping you from using them in your template?
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91143016
comment on: http://stackoverflow.com/a/52096305
score: 1
type: AnswerComment
has text: @SaiKumar `iter()` creates an iterator (read here if you're not familar: https://stackoverflow.com/questions/231767/what-does-the-yield-keyword-do). The iterator is consumed via `next()` calls (unlike say a list), thus `zip()` creates the correct pairs
type: Comment

http://stackoverflow.com/q/52036505
upvote count: 1
type: Question
type: AnsweredQuestion
score: 1
has comment: http://stackoverflow.com/comment/91024565
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/52037317
accepted answer: http://stackoverflow.com/a/52037317
favorite count: 0
has title: Key error adding two Pandas data-frames together
tagged with: pandas
tagged with: python
has body: Frames df1 and df2 that I'd like to add together to make df3. Partial data-frames (as they are quite large) are as follows df1: total_pnl_per_pos invested date 2015-03-17 0.330533 145790.529585 2015-03-18 -0.132040 152116.458134 2015-03-19 0.189508 141114.361229 2015-03-20 0.346906 323712.355051 2015-03-21 -0.004500 149999.909424 df2: total_pnl_per_pos invested date 2015-03-16 -0.009346 3843277.00 2015-03-17 -0.025422 4495925.00 2015-03-18 -0.093223 4233412.00 2015-03-19 -0.144945 4340475.00 2015-03-20 -0.030945 6107379.00 I'd like df3 to be df1 + df1 and to look like: total_pnl_per_pos invested date 2015-03-16 -0.009346 3843277 2015-03-17 0.305111 4641715.53 2015-03-18 -0.225263 4385528.458 2015-03-19 0.044563 4481589.361 2015-03-20 0.315961 6431091.355 2015-03-21 -0.0045 149999.9094 Note that df1 and df2 are indexed by date and do not necessarily have the same dates in each data-frame. I have tried to use: df3= df1.set_index('date').add(df2.set_index('date'), fill_value=0).reset_index() and df3= pd.concat([df1, df2]).groupby('date').sum().reset_index() I however get a KeyError: 'date' error when I try the two different solutions. Where have I gone wrong?

http://stackoverflow.com/a/51966616
has comment: http://stackoverflow.com/comment/90884044
has comment: http://stackoverflow.com/comment/90883982
score: 3
has comment: http://stackoverflow.com/comment/90893603
answers question: http://stackoverflow.com/q/51966498
downvote count: 0
has comment: http://stackoverflow.com/comment/90884157
has comment: http://stackoverflow.com/comment/90884182
has comment: http://stackoverflow.com/comment/90893513
has comment: http://stackoverflow.com/comment/90891602
type: Answer
has body: You can use iloc with Boolean indexing, but be careful. It works with Boolean arrays, not Boolean series. For example: b.iloc[(b['A'] == 'a').values, 2:6] = 'someConstantValue' As an aside, chained indexing is explicitly discouraged in the docs. There should never be a need to use chained indexing.
upvote count: 3
has comment: http://stackoverflow.com/comment/90883112

http://stackoverflow.com/comment/91162731
has text: @user2357112: the [support 3.7 milestone](https://twistedmatrix.com/trac/query?group=status&milestone=Python+3.7+support) is still open with more tickets; the most important one that you [can't yet compile twisted on Python 3.7](https://twistedmatrix.com/trac/ticket/9501).
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52105818
type: Comment

http://stackoverflow.com/q/52053491
possible better answer: http://stackoverflow.com/a/52054606
favorite count: 0
has answer: http://stackoverflow.com/a/52054606
answer count: 5
score: 13
tagged with: python
type: AnsweredQuestion
downvote count: 0
linked to: http://stackoverflow.com/q/48619517
has answer: http://stackoverflow.com/a/52069546
accepted answer: http://stackoverflow.com/a/52069546
has body: I want to have a command line tool with a usage like this: $ program &lt;arg&gt; does something, no command name required $ program cut &lt;arg&gt; $ program eat &lt;arg&gt; The Click code would look like this: @click.group() def main() : pass @main.command() @click.argument('arg') def noname(arg) : # does stuff @main.command() @click.argument('arg') def cut(arg) : # cuts stuff @main.command() @click.argument('arg') def eat(arg) : # eats stuff My problem is that with this code, there is always a required command name, ie: I need to run $ program noname arg. But I want to be able to run $ program arg.
type: Question
has title: A command without name, in Click
upvote count: 13
has answer: http://stackoverflow.com/a/76807466
has answer: http://stackoverflow.com/a/67430262
tagged with: python-click
has answer: http://stackoverflow.com/a/73576818

http://stackoverflow.com/comment/91141690
type: Comment
has text: @timmy it iterates over the iterable (e.g. list) `r` and puts the seperator (in this case the whitespace) between each element and the result is one string
type: AnswerComment
comment on: http://stackoverflow.com/a/52095777
score: 0

http://stackoverflow.com/a/59066727
upvote count: 1
has body: You could install PyCharm which has a plugin called 'Multirun'.This allows you to run several python files in parallel. I had the same issue as you and fixed it this way.
score: -3
type: Answer
answers question: http://stackoverflow.com/q/51969662
downvote count: 4

http://stackoverflow.com/a/52015960
answers question: http://stackoverflow.com/q/52015820
score: 1
has comment: http://stackoverflow.com/comment/90982132
has comment: http://stackoverflow.com/comment/90982265
downvote count: 0
has body: Just make check if the item is already in the keys of the dictionary. Insert only if not already there. def add_new_unit(d, name, value): if(name in d.keys()): print("The reactor information for {name} already recorded!".format(name = name)) return d d[name] = Unit(name, value) return d
type: Answer
has comment: http://stackoverflow.com/comment/90982152
upvote count: 1

http://stackoverflow.com/comment/116087958
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52052299
has text: It does not answer your question, but I remark that you used `compare_psnr` from `skimage`, which works on `numpy` arrays. I would recommend using a PyTorch IQA package such as [`piqa`](https://github.com/francois-rozet/piqa) or [`piq`](https://github.com/photosynthesis-team/piq), to leverage GPU capabilities.

http://stackoverflow.com/a/52103514
score: 0
has body: Could you use just string methods like the following? 'feedbackreport' in name.replace('_', '').replace(' ', '').lower() And also name.endswith('.xlsx') Giving you something like: fileList = [ 'ZSS Project_JKIAL-SA_FEEDBACK_REPORT_Jan 29th 2015.xlsx', 'ZL-SA_feedback report_012844.xlsx', 'ASARanem-SA_Feedback Report_012844.xlsx' ] fileNames = [name for name in fileList if ('feedbackreport' in name.replace('_', '').replace(' ', '').lower() and name.endswith('.xlsx'))] If there are more characters that could cause problems such as - then you could also make a quick function to remove bad characters: def remove_bad_chars(string, chars): for char in chars: string = string.replace(char, '') return string Amending the appropriate portion of the if statement to: if 'feedbackreport' in remove_bad_chars(name, '.,?!\'-/:;()"\\~ ').lower() # included a white space in the string of bad characters
type: Answer
has comment: http://stackoverflow.com/comment/91158074
answers question: http://stackoverflow.com/q/52103370

http://stackoverflow.com/a/52085069
upvote count: 1
has comment: http://stackoverflow.com/comment/91120678
has comment: http://stackoverflow.com/comment/91120670
has body: The fundamental problem is that you increment n, even if you already added the element to the dictionary. So if you already added the element, it still counts as one. In case it was not added yet, it counts as two, but there are thus cases possible where Anyway, there is no reason to do this, we can first make a random string by shuffling the characters, and then "stitching" these together, like: The fundamental problem is that you increment n, even if you already added the element to the dictionary. So if you already added the element, it still counts as one. In case it was not added yet, it counts as two, but there are thus cases possible where Anyway, there is no reason to do this, we can first make a random string by shuffling the characters, and then "stitching" these together, like: from string import ascii_uppercase from random import shuffle dt = list(ascii_uppercase) shuffle(dt) dt = iter(dt) result = {k: v for a, b in zip(dt, dt) for k, v in ((a,b), (b, a))} Or in case a character can "pair" together with itself, we can implement it like: from string import ascii_uppercase from random import shuffle, randint dt = list(ascii_uppercase) shuffle(dt) result = {} i = 0 while i &lt; len(dt): d = randint(0,len(dt)-i-1 &gt; 0) k = dt[i] v = dt[i+d] result.update({k: v, v: k}) i += 1 + d assert len(result) == len(ascii_uppercase) assert len(set(result.values())) == len(ascii_uppercase) Both algorithms work in linear time, since they make a single pass over a list of random characters, and each time link the previous with the next character (or the current character with itself).
score: 1
accepted answer of: http://stackoverflow.com/q/52084899
has comment: http://stackoverflow.com/comment/91120780
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/52084899
has comment: http://stackoverflow.com/comment/91120682
type: Answer
has comment: http://stackoverflow.com/comment/91120801

http://stackoverflow.com/a/52096316
has comment: http://stackoverflow.com/comment/91142688
has body: myDict = {key : 1.0 for key in myDict}
type: AcceptedAnswer
upvote count: 5
accepted answer of: http://stackoverflow.com/q/52096279
type: Answer
answers question: http://stackoverflow.com/q/52096279
has comment: http://stackoverflow.com/comment/91142976
downvote count: 0
score: 5

http://stackoverflow.com/a/52020100
score: 0
has comment: http://stackoverflow.com/comment/90991790
type: Answer
answers question: http://stackoverflow.com/q/52014207
has body: No - there is no way to make a prepared statement in MySQLdb. You won't find any mysql_stmt_init(), mysql_stmt_prepare() or mysql_stmt_execute() in the MySQL API binding in _mysql.c. For whatever reason, the author of MySQLdb chose to simulate parameters instead of using real server-side prepared statements. To protect against SQL injection, the MySQLdb package uses Python string-format syntax. It interpolates dynamic values into SQL queries and applies correct escaping, i.e. adding \ before quote characters to make sure dynamic values don't contain string delimiters. See my answer to How do PyMySQL prevent user from sql injection attack? for a demonstration. However, escaping doesn't help if you need to use dynamic values for numeric constants.
has comment: http://stackoverflow.com/comment/90992176

http://stackoverflow.com/comment/91140260
score: 0
type: Comment
type: QuestionComment
has text: Maybe see https://stackoverflow.com/questions/6234252/how-to-embed-lua-inside-python ?
comment on: http://stackoverflow.com/q/52095146

http://stackoverflow.com/comment/90898023
comment on: http://stackoverflow.com/q/51973055
score: 0
type: Comment
type: QuestionComment
has text: That is correct

http://stackoverflow.com/comment/91018340
score: 0
type: AnswerComment
has text: @ThatBird updated
type: Comment
comment on: http://stackoverflow.com/a/52034040

http://stackoverflow.com/q/51972573
downvote count: 0
tagged with: string
favorite count: 0
has body: I have a list of 400,000 file names (column in excel) of the format xxx.Number.Date.zzz.txt and I want to extract the Number from the string Normally I would just set it to take the 5th through 9th character in that string, but the numbers vary in length (2 - 4 digits) and I am not sure how to design an algorithm that can tell how long the number is. Using python3 if anyone is interested, but really I just need help with the pseudocode I looked at this previous question, but it did not really answer the question in terms that I can use since it seems like it is using bash functions or I did not understand the explanation: Extract number of variable length from string
has title: Algorithm to extract number of varying length from title of file
tagged with: python
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/51972614
linked to: http://stackoverflow.com/q/16015590
has answer: http://stackoverflow.com/a/51972654
has answer: http://stackoverflow.com/a/51972614
upvote count: 1
type: Question
tagged with: algorithm
score: 1
tagged with: pseudocode
accepted answer: http://stackoverflow.com/a/51972654
answer count: 2

http://stackoverflow.com/q/52009704
has comment: http://stackoverflow.com/comment/90970393
type: Question
has comment: http://stackoverflow.com/comment/90970386
tagged with: numpy
answer count: 1
has answer: http://stackoverflow.com/a/52009912
has title: numpy array is immutable after matplotlib.pyplot.imread()
score: 0
accepted answer: http://stackoverflow.com/a/52009912
tagged with: python
has body: Why is the numpy array immutable after being read using matplotlib.pyplot.imread? What is the reasoning behind that? &gt;&gt;&gt; import matplotlib &gt;&gt;&gt; test=matplotlib.pyplot.imread('download.jpeg') &gt;&gt;&gt; test.flags C_CONTIGUOUS : True F_CONTIGUOUS : False OWNDATA : False WRITEABLE : False ALIGNED : True WRITEBACKIFCOPY : False UPDATEIFCOPY : False
type: AnsweredQuestion
tagged with: matplotlib

http://stackoverflow.com/comment/91076420
comment on: http://stackoverflow.com/a/52062771
type: Comment
score: 0
has text: Thank you @jakevdp for your help (and your work on Altair), it is a very effective solution!
type: AnswerComment

http://stackoverflow.com/q/52098561
type: UnansweredQuestion
tagged with: python
tagged with: sqlalchemy
type: Question
has answer: http://stackoverflow.com/a/52104371
tagged with: subquery
tagged with: postgresql
score: 0
tagged with: lateral-join
answer count: 1
has body: I am having difficulty translating a query I created in sql (postgres) into sqlalchemy. In particular, my attempted mapping in sqlalchemy is leading to absurd recursive results that will run far slower than what I originally wrote. Given the following type of table structure: metadata ------------------------------ primary_id - integer secondary_count - integer property - string (many to each primary_id) data ----------------------------- primary_id - integer secondary_id - integer (many to each primary_id) primary_json - json bytes secondary_json - json bytes I am trying to retrieve pairs of primary and secondary data with the such that: we match a given property we return only "some" of the primary data (say 1000) we return the "best" primary data, which is to say the primary data with the most secondary data. we only get "some" (say 10) secondary data per primary entry The first is easy to accomplish with a join between the two tables, however the second is more complicated. The solution I cam to (see here for the explanation that led me to this solution) in raw SQL is: SELECT primary_id, primary_json, secondary_json, secondary_count FROM ( SELECT primary_id, secondary_count FROM metadata WHERE property='whatever I want' -- Get the "best" 1000 results ORDER BY secondary_count DESC LIMIT 1000 ) my_primary_ids LEFT OUTER JOIN LATERAL ( SELECT primary_json, seondary_json FROM data WHERE primary_id = my_primary_ids.primary_id -- Only return 10 pieces of secondary json per primary json LIMIT 10 ) json_content ON true; I have tried my utmost to convert this to sqlalchemy, however I keep having the problem that the resulting query re-writes the subquery in the FROM clause of the lateral join query. For example, the sqlalchemy code (assuming table object definitions which match the above) below is a partial solution. I think I can add the columns that are lacking (as you will see in the sql that is generated): from sqlalchemy import true my_prim_ids_al = ( query(Metadata…
has title: Convert lateral join query to sqlalchemy

http://stackoverflow.com/q/52063586
has body: I have index where data field is keyword type. I store string like this one: [a-zA-Z0-9.]+\@[a-zA-Z0-9]+\.[a-zA-Z]+ but when I return it in Python from Elastic I get string like this one (because it is stored escaped in Elastic): \\[a\\-zA\\-Z0\\-9\\.\\]\\+\\\\\\@\\[a\\-zA\\-Z0\\-9\\]\\+\\\\\\.\\[a\\-zA\\-Z\\]\\+ How I can return it back to original form in Python? I tried to store it as binary type field and use encode/decode but basically I get same escaped string as well.
downvote count: 0
score: 1
has answer: http://stackoverflow.com/a/52080141
type: Question
has comment: http://stackoverflow.com/comment/91080974
has comment: http://stackoverflow.com/comment/91080951
linked to: http://stackoverflow.com/q/14820429
has comment: http://stackoverflow.com/comment/91077755
has comment: http://stackoverflow.com/comment/91084578
upvote count: 1
answer count: 1
has title: How to unescape string in Python which is returned from Elasticsearch?
has comment: http://stackoverflow.com/comment/91077696
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion
tagged with: elasticsearch
tagged with: python

http://stackoverflow.com/q/52036656
favorite count: 0
tagged with: utility
type: UnansweredQuestion
tagged with: python
score: 2
answer count: 0
upvote count: 2
linked to: http://stackoverflow.com/q/51985436
has comment: http://stackoverflow.com/comment/91099170
type: Question
has title: Pyomo Infeasibility-Check Algorithm Error
tagged with: pyomo
linked to: http://stackoverflow.com/q/51044262
tagged with: function
has body: This is my following question (3rd) after the two questions I asked before. You can find them below: 1st Finding out reason of Pyomo model infeasibility 2nd Pyomo Util Module Not Found As you said @Qi Chen (2nd questions answer), I did following: you can simply take the function at https://github.com/Pyomo/pyomo/blob/master/pyomo/util/infeasible.py and place it in your own code (along with the associated required imports) By the way above log_infeasible_constraints function is meant by saying function. But I encounter an error, that I cannot figure out, why. Here are some pre-knowledge about the model: I am not allowed to share some info about the model so I censored them by changing their names to some_vars, or xxx, etc... Gamma is a variable in the model, and also the objective to minimize. So it is normal that it does not have any value on an infeasible model? How do I fix the log_infeasible_constraints function to show me; "this constraint is making your model infeasible, because of this variable value", or something similar? Error: WARNING: Loading a SolverResults object with a warning status into model=xxxxx; message from solver=Model was proven to be infeasible. ERROR: evaluating expression: No value for uninitialized NumericValue object Gamma (expression: some_var[some_index1] + some_var[some_index2] + some_var[some_index3] + some_var[some_index4] + some_var[some_index5] + some_var[some_index6] + some_var[some_index7] + some_var[some_index8] + some_var[some_index9] + some_var[some_index10] - 0.0 - Gamma) ERROR: evaluating object as numeric value: some_var[some_index1] + some_var[some_index2] + some_var[some_index3] + some_var[some_index4] + some_var[some_index5] + some_var[some_index6] + some_var[some_index7] + some_var[some_index8] + some_var[some_index9] + some_var[some_index10] - 0.0 - Gamma (object: &lt;class 'pyomo.core.kernel.expr_coopr3._SumExpression'&gt;) No value for uninitialized NumericValue object Gamma Traceback (most recent call last): File "x…
has comment: http://stackoverflow.com/comment/91084937
has comment: http://stackoverflow.com/comment/91024520
downvote count: 0

http://stackoverflow.com/comment/91007257
comment on: http://stackoverflow.com/a/52027716
has text: You can also (ab)use an OrderedDict to do the dedupe... `[el for el in OrderedDict.fromkeys(df_final) if el not in df1_set]` instead of a 3rd party library (although some of the recipes in the itertools documentation are also v. useful)
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/52056897
tagged with: python
score: 2
answer count: 0
upvote count: 2
type: UnansweredQuestion
tagged with: web-scraping
tagged with: scrapy
type: Question
has title: Scrapy on aws ec2 ubuntu redirect for booking.com
downvote count: 0
tagged with: amazon-ec2
has comment: http://stackoverflow.com/comment/91064694
favorite count: 0
tagged with: python-3.x
has body: com scraper which works locally but on AWS isn't. I'm getting redirect and then spider stops working. Some code: class HotelsCrawler(CrawlSpider): name = "booking_crawler" allowed_domains = ['booking.com'] headers = { "User-Agent": "Mozilla/5.0(Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Mobile Safari/537.36", "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8", "Host": "www.booking.com" } resultHotels = pd.DataFrame(columns=['hotel_id', 'name', 'score', 'price']) fileName = '' startDate = None endDate = None city = '' def start_requests(self): url = "https://www.booking.com/searchresults.pl.html?ss=Berlin&is_ski_area=0&dest_type=city&checkin_monthday=28&checkin_month=8&checkin_year=2018&checkout_monthday=29&checkout_month=8&checkout_year=2018&no_rooms=1&group_adults=2&group_children=0) yield Request(url=url,headers=self.headers, callback=self.parse) And logs: 2018-08-28 11:14:01 [scrapy.core.engine] DEBUG: Crawled (200) <GET https://www.booking.com/robots.txt> (referer: None) 2018-08-28 11:14:01 [scrapy.downloadermiddlewares.redirect] DEBUG: Redirecting (301) to <GET https://www.booking.com/searchresults.pl.html?dest_type=city;ss=Berlin> from <GET https://www.booking.com/searchresults.pl.html?ss=Berlin&is_ski_area=0&dest_type=city&checkin_monthday=28&checkin_month=8&checkin_year=2018&checkout_monthday=29&checkout_month=8&checkout_year=2018&no_rooms=1&group_adults=2&group_children=0> 2018-08-28 11:14:02 [scrapy.core.engine] DEBUG: Crawled (200) <GET https://www.booking.com/searchresults.pl.html?dest_type=city;ss=Berlin> (referer: None) 2018-08-28 11:14:02 [scrapy.spidermiddlewares.offsite] DEBUG: Filtered offsite request to 'www.booking.comhttps': <GET https://www.booking.comhttps//www.booking.com/searchresults.pl.html?dest_id=-1746443&dest_type=city&ss=Berlin&offset=20&pagination_used=1> 2018-08-28 11:14:02 [scrapy.core.engine] INFO: Closing spider (finished) In …
has comment: http://stackoverflow.com/comment/91064768

http://stackoverflow.com/q/51975227
answer count: 2
has answer: http://stackoverflow.com/a/51975343
linked to: http://stackoverflow.com/q/43196550
downvote count: 0
tagged with: sorting
has title: sort column based on specific column | python | pandas
duplicate of: http://stackoverflow.com/q/43196550
has body: I have a dataframe like this: c234 0.4255 0.2348 0.4255 c234 0.876 0.456 0.876 c561 0.9527 0.263 0.9527 c561 0.4111 0.1543 0.4111 c561 0.8231 0.975 0.975 I want to sort 4th column within each 1st column, the output will be like this: c234 0.876 0.456 0.876 c234 0.4255 0.2348 0.4255 c561 0.8231 0.975 0.975 c561 0.9527 0.263 0.9527 c561 0.4111 0.1543 0.4111 Any help please ?
tagged with: pandas
favorite count: 0
accepted answer: http://stackoverflow.com/a/51975343
upvote count: 1
tagged with: python
possible better answer: http://stackoverflow.com/a/51975332
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51975332
tagged with: group-by
score: 1
linked to: http://stackoverflow.com/q/37287938
type: Question

http://stackoverflow.com/q/52029115
answer count: 0
downvote count: 0
score: 1
has title: convert image to colored LBP
has body: I want to convert RGB image to colored local binary pattern. Here is code to convert grayscale image to LBP. import cv2 import os from skimage.feature import local_binary_pattern import scipy.misc im = cv2.imread('images/abc.jpg') im_gray = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY) radius = 3 no_points = 8 * radius lbp = local_binary_pattern(im_gray, no_points, radius, method='uniform') scipy.misc.imsave('lbp_images/abc.jpg', lbp) But i want to convert colored image not grayscale.
linked to: http://stackoverflow.com/q/42322400
type: Question
tagged with: opencv
upvote count: 1
has comment: http://stackoverflow.com/comment/91010915
favorite count: 0
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/comment/91063775
type: QuestionComment
has text: The class `Var` is the table. To create it you just need to import the class to where you're running the `create_all` method.
comment on: http://stackoverflow.com/q/52046077
score: 0
type: Comment

http://stackoverflow.com/q/52002819
tagged with: pandas
answer count: 1
duplicate of: http://stackoverflow.com/q/38309729
accepted answer: http://stackoverflow.com/a/52002898
has title: How many different days customer visits app
tagged with: python
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/52002898
type: Question
has body: I have a dataframe that looks like. Each object_id represents different customer. date objectId 15/07/18 "__gb5c9e15dfc004930b8ac9d5d1df1880e" 16/07/18 "__g0b2abb9da5d646eb930c1ce9bb6df5ef" 16/07/18 "__c5ff64e5448c44fabe26e88bc0e41497" 17/07/18 "__c7b0a5824a914d7198a328cdf35c95bf" 18/07/18 "__8929216e8d534569ae6fd6701c92fc4c" 19/07/18 "__gec079853a06748a79b4d101713c1e21d" 19/07/18 "__d7f24fa5909b43f4a5282877ed4eed3e" 19/07/18 "__ga523090706304454ba581d79f366816a" 19/07/18 "__d409d75e4207409b8ea030f69b70bf83" 19/07/18 "-g940dc0277b7f46c8b7d8de195a8fd975" 20/07/18 "__d7f24fa5909b43f4a5282877ed4eed3e" 20/07/18 "__ga523090706304454ba581d79f366816a" 21/07/18 "__d409d75e4207409b8ea030f69b70bf83" 21/07/18 "-g940dc0277b7f46c8b7d8de195a8fd975" I want to count how many different days does each customer comes. I tried something like df.groupby(['objectId'])['date'].count(). It gives me total number of times customer came to the app not different days that customer came to app.
linked to: http://stackoverflow.com/q/38309729
tagged with: pandas-groupby

http://stackoverflow.com/a/51958321
score: 0
type: Answer
has comment: http://stackoverflow.com/comment/90867184
answers question: http://stackoverflow.com/q/51958143
has body: This will give you a starting point: [List.index(x) for x in set(List)] Now this may have too many elements but "somehow" is totally subjective and not a clear enough definition for what you need to do. As a default you can keep the first and last element, then randomly pick as many as you require from the "middle".

http://stackoverflow.com/q/52050375
upvote count: 1
has title: Extract all link in a json file
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91051359
has answer: http://stackoverflow.com/a/52050484
downvote count: 0
has answer: http://stackoverflow.com/a/52050591
score: 1
has answer: http://stackoverflow.com/a/52050587
favorite count: 0
type: Question
tagged with: python
has comment: http://stackoverflow.com/comment/91051395
has body: I'm trying to learn python at the moment i managed to get a huge json file, i want to extract from it all the links and download them. import json import urllib3 urllib3.disable_warnings() url = 'https://www.reddit.com/r/EarthPorn/top/.json' http = urllib3.PoolManager() suffix = ['.jpg','.png','.gif','.bmp'] while True: response = http.request('GET',url) myData = response.data parsedJson = json.loads(myData) finalUrl = parsedjson[0]['data']['children'][0]['data']['url'] print(finalUrl) at the moment i get an error on the line of finalUrl so i think i'm having an error trying to get each url in the json file. source: https://www.reddit.com/r/earthporn/top/.json
has comment: http://stackoverflow.com/comment/91051052
answer count: 3
has comment: http://stackoverflow.com/comment/91051239

http://stackoverflow.com/q/52025453
has comment: http://stackoverflow.com/comment/91199522
type: Question
score: -2
has body: I have a project in the PyCharm editor in which the base class and the child class are implemented in separate files. In the child class I am accessing a function which is implemented in the base class. Pycharm has got a keyboard shortcut "Ctrl + Alt + B" to go to the implementation of the method that is highlighted when the shortcut is pressed. However, I am not able to navigate to any implementation that is in a different file. I'm able to go only methods that are implemented within the same file. I also tried other options including navigating to the super method or navigating to the declaration just to see if any other command works for navigation into a different file but none of them seem to be effective. Is there anything else that I have to do in order to make this possible apart from including the files within the same project in PyCharm? For example, is there any kind of indexing that I have to do before and so that PyCharm can recognise the implementation across different files? Here are more details after a comment from Dan: The project structure is simple: Project directory Dir1 Dir2 Within Dir1 File1 File2 Withi Dir2 File3 File4 For the purposes of this question, File1 can be considered as base class and file3 as child class. When I am in File3 in pycharm and them at the place where a function implemented in file1 is being invoked, I am unable to navigate to that function in File1. In fact, even if there is no class inheritance relationship, I am unable to navigate to any function which is implemented in a file other than the current file where the cursor is. For example, if I am at the invocation of the function in File3 and the function is in the same directory in File4, I'm unable to navigate to that function. This is kind of surprising because the basic other IDE end possibly there is some issue in my settings but I cannot figure out what to do. Hopefully with this information, someone can at least point me in a direction to investigate further. I'…
downvote count: 2
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/91006385
has title: How to navigate to definitions of the base class in another file in PyCharm?
has answer: http://stackoverflow.com/a/52171635
accepted answer: http://stackoverflow.com/a/52171635
tagged with: python
has comment: http://stackoverflow.com/comment/91002610
has comment: http://stackoverflow.com/comment/91187050
has comment: http://stackoverflow.com/comment/91294007
type: AnsweredQuestion
upvote count: 0
tagged with: pycharm
has comment: http://stackoverflow.com/comment/91206540

dataframe
tags question: http://stackoverflow.com/q/52080799
tags question: http://stackoverflow.com/q/51959497
tags question: http://stackoverflow.com/q/52062893
tags question: http://stackoverflow.com/q/51989388
tags question: http://stackoverflow.com/q/52064521
tags question: http://stackoverflow.com/q/51970065
tags question: http://stackoverflow.com/q/52104544
tags question: http://stackoverflow.com/q/52005592
tags question: http://stackoverflow.com/q/52054719
tags question: http://stackoverflow.com/q/52048914
tags question: http://stackoverflow.com/q/52014156
tags question: http://stackoverflow.com/q/52104682
tags question: http://stackoverflow.com/q/51968264
tags question: http://stackoverflow.com/q/52076956
tags question: http://stackoverflow.com/q/52025769
tags question: http://stackoverflow.com/q/51958885
tags question: http://stackoverflow.com/q/52075715
tags question: http://stackoverflow.com/q/51999736
tags question: http://stackoverflow.com/q/52103441
tags question: http://stackoverflow.com/q/52085323
tags question: http://stackoverflow.com/q/51990983
tags question: http://stackoverflow.com/q/51990946
tags question: http://stackoverflow.com/q/52022211
tags question: http://stackoverflow.com/q/51976930
tags question: http://stackoverflow.com/q/52024175
tags question: http://stackoverflow.com/q/51971096
tags question: http://stackoverflow.com/q/52038461
tags question: http://stackoverflow.com/q/51968951
tags question: http://stackoverflow.com/q/52059309
tags question: http://stackoverflow.com/q/52093046
tags question: http://stackoverflow.com/q/52003960
tags question: http://stackoverflow.com/q/51973991
tags question: http://stackoverflow.com/q/52052060
tags question: http://stackoverflow.com/q/51994481
tags question: http://stackoverflow.com/q/52100488
tags question: http://stackoverflow.com/q/52109791
tags question: http://stackoverflow.com/q/51993289
tags question: http://stackoverflow.com/q/52007418
tags question: http://stackoverflow.com/q/52048854
tags question: http://stackoverflow.com/q/52087845
tags question: http://stackoverflow.com/q/52053496
tags question: http://stackoverflow.com/q/51969376
tags question: http://stackoverflow.com/q/52031829
tags question: http://stackoverflow.com/q/51971384
tags question: http://stackoverflow.com/q/51967711
tags question: http://stackoverflow.com/q/52111466
tags question: http://stackoverflow.com/q/52062580
tags question: http://stackoverflow.com/q/52022570
tags question: http://stackoverflow.com/q/52079804
tags question: http://stackoverflow.com/q/52056393
tags question: http://stackoverflow.com/q/52085070
tags question: http://stackoverflow.com/q/52103935
tags question: http://stackoverflow.com/q/52050924
tags question: http://stackoverflow.com/q/52074171
tags question: http://stackoverflow.com/q/51980503
tags question: http://stackoverflow.com/q/52053698
tags question: http://stackoverflow.com/q/51958973
tags question: http://stackoverflow.com/q/52061708
tags question: http://stackoverflow.com/q/52051014
tags question: http://stackoverflow.com/q/52087195
tags question: http://stackoverflow.com/q/52103193
tags question: http://stackoverflow.com/q/52077487
tags question: http://stackoverflow.com/q/51968542
tags question: http://stackoverflow.com/q/52082342
tags question: http://stackoverflow.com/q/52045556
tags question: http://stackoverflow.com/q/52004437
tags question: http://stackoverflow.com/q/52109361
tags question: http://stackoverflow.com/q/51992344
tags question: http://stackoverflow.com/q/52008668
tags question: http://stackoverflow.com/q/52102125
tags question: http://stackoverflow.com/q/52045848
tags question: http://stackoverflow.com/q/52010551
tags question: http://stackoverflow.com/q/51961579
tags question: http://stackoverflow.com/q/51957186
tags question: http://stackoverflow.com/q/52024271
tags question: http://stackoverflow.com/q/52070949
tags question: http://stackoverflow.com/q/52005525
tags question: http://stackoverflow.com/q/52030631
tags question: http://stackoverflow.com/q/52075442
tags question: http://stackoverflow.com/q/52000891

http://stackoverflow.com/comment/91123060
type: AnswerComment
has text: same problem as with the other modules I've tried. It works on desktop but not ingame :S
type: Comment
comment on: http://stackoverflow.com/a/52086229
score: 0

http://stackoverflow.com/comment/91110607
type: Comment
type: QuestionComment
has text: @E.Serra Actually I do use full email address
score: 0
comment on: http://stackoverflow.com/q/52079297

http://stackoverflow.com/q/52029458
tagged with: python
has body: Hi so I'm new to creating bots with Discord.py. I've gotten along pretty well using the docs although am now stuck. Here's all the code from commands.py. # All commands cmds = { # The 'cmd' variable I'm using in the second code block "ping": { "name": "Ping", "description": "Ping pong", "usage_str": "ping", "rank_needed": 0, "execute": None } } # Define the function def ping(client, message, channel, args): print("SENDING MESSAGE!") client.send_message(channel, "Pong!") # Set the execute index in the dictionary to equal the function cmds["ping"]["execute"] = ping Here's the code from main.py that is calling the ping function. cmd["execute"](client, message, channel, content) When I attempt to execute the function I no message is sent into the channel although 'SENDING MESSAGE' is printed into the console. Why is this? What did I miss?
type: UnansweredQuestion
has title: Why won't the message be sent to the channel?
has answer: http://stackoverflow.com/a/52029522
type: Question
tagged with: discord.py
score: 0
answer count: 1

http://stackoverflow.com/a/51995146
type: Answer
has body: so unfortunately fetchall() doesn't work either. This was finally my solution import sys, os, pyodbc, copy conn_str = ( r'DRIVER={Microsoft Access Driver (*.mdb, *.accdb)};' r'DBQ=C:/Users/vlcek/Desktop/pokusdb.accdb;' ) connection = pyodbc.connect(conn_str) cursor = connection.cursor() sql="Select whole_name from people" cursor.execute(sql) mylist1=list(cursor) mylist2=copy.deepcopy(mylist1) for change in mylist2: devided=change[0].split() print(devided[0]+"--"+devided[1]) sql2="Insert into people (user_id, Name, Surname) values (27, ?,?)" cursor.execute(sql2,(devided[0],devided[1])) connection.commit() connection.close() So I: copied cursor into the list -> mylist1=list(cursor) made deepcopy of the list -> mylist2=copy.deepcopy(mylist1) iterated through that deep copied list I was also missing connection.commit() at the end But thank you for your help anyway. Vaclav
answers question: http://stackoverflow.com/q/51957010
score: 0

http://stackoverflow.com/comment/91137384
score: 0
type: QuestionComment
type: Comment
has text: @Joe it is printing different values because columns positions are different in boths sheets for C1 , Can we select a column by name and then iterate over it searching for the value from Excel 1?
comment on: http://stackoverflow.com/q/52089716

http://stackoverflow.com/a/52010265
downvote count: 3
has comment: http://stackoverflow.com/comment/90971648
type: Answer
has comment: http://stackoverflow.com/comment/90971719
has comment: http://stackoverflow.com/comment/90971927
has comment: http://stackoverflow.com/comment/90971437
has comment: http://stackoverflow.com/comment/90971872
has comment: http://stackoverflow.com/comment/90971590
has comment: http://stackoverflow.com/comment/90971386
upvote count: 2
has body: in does seem to be faster. At a guess, COMPARE_OP is more efficent than CALL_FUNCTION because it knows how many arguments it has. haugh@~$ python3 -m timeit -s "l = {1}" "2 in l" 10000000 loops, best of 3: 0.029 usec per loop haugh@~$ python3 -m timeit -s "l = {1}" "l.__contains__(2)" 10000000 loops, best of 3: 0.0612 usec per loop haugh@~$ python3 -m timeit -s "l = {1}; isin=l.__contains__" "isin(2)" 10000000 loops, best of 3: 0.0301 usec per loop
score: -1
has comment: http://stackoverflow.com/comment/90971459
answers question: http://stackoverflow.com/q/52010120

http://stackoverflow.com/q/52032714
tagged with: dictionary
possible better answer: http://stackoverflow.com/a/52032833
has body: I have a data of follow: d = d = [ { "test" : [ { "win" : { "number" : 0 }, "taken" : [ { "id" : "0", "library" : [ ] } ] }, { "win" : { "number" : 1 }, "taken" : [ { "id" : "1", "library" : [ { "takenid" : "2", "lib" : "man" } ] }, { "id" : "2", } ] }, { "chunk" : { "number" : 2 }, "taken" : [ { "id" : "3", "library" : [ { "takenid" : "0", "lib" : "woman" }, { "takenid" : "1", "lib" : "ghost" }, { "takenid" : "4", "lib" : "monster" } ] }, { "id" : "4" } ] } ] } ] I wanted to print all the values for "lib" dictionary but not the empty list. In my code, I will check the total "id" and compare it with the "takenid" then add new "takenid" based on the missing values. After that, I wish to create a dictionary that have the form of this {id:{takenid:lib}} but excluding the empty list(the newly added "takenid" and "lib"). Below is my script code: acom = [] lemmas = [] ordering = [] sort = [] check = 0 for x in d[0]["test"]: for y in x["taken"]: if "id" in y: check += 1 value = [] #Calculate the number of "takenid" for x in d[0]["test"]: for y in x["taken"]: if "library" in y: for u in y["library"]: value.append(int(u["takenid"])) #Find the difference between the "id" and "takenid" missing = (set(range(check)) - set(value)) missing = list(missing) #print(missing) for x in d[0]["test"]: for y in x["taken"]: if "library" in y: y["library"].append({"takenid": "%s" % missing[0], "lib": []}) break #Create a dictionary for x in d[0]["test"]: for y in x["taken"]: if "library" in y: for u in y["library"]: if "[]" not in u["lib"]: #if "[]" not in uu: ordering.append({y["id"]:{u["takenid"]:u["lib"]}}) #print(ordering) However, my code takes in the empty list and printed this output: Current output: [{'0': {'3': []}}, {'1': {'2': 'man'}}, {'3': {'0': 'woman'}}, {'3': {'1': 'ghost'}}, {'3': {'4': 'monster'}}] I am hoping to create a dictionary without the empty list. Is it possible to do so? Expected output: [ {'1': {'2': 'man'}}, {'3': {'0': 'woman'}}, {'3': {'1': 'ghost'}}, {'3': {'…
has answer: http://stackoverflow.com/a/52032753
has answer: http://stackoverflow.com/a/52032833
type: AnsweredQuestion
has title: print the values in dictionary without the empty list
tagged with: list
type: Question
answer count: 2
accepted answer: http://stackoverflow.com/a/52032753
score: 0
tagged with: python

http://stackoverflow.com/comment/91042853
score: 0
has text: Are you sure you want to remove the new line character with an empty string? I think you might want to try: `whatever.replace("\t", "\n")`
type: Comment
comment on: http://stackoverflow.com/q/52045893
type: QuestionComment

http://stackoverflow.com/q/52110929
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/91172881
tagged with: python
has comment: http://stackoverflow.com/comment/91172420
type: AnsweredQuestion
has body: I try to get the name of subdirectories with Python3 script on Windows10. Thus, I wrote code as follows: from pathlib2 import Path p = "./path/to/target/dir" [str(item) for item in Path(p).rglob(".")] # obtained only subdirectories path names including target directory itself. It is good for me to get this result, but I don't know why the pattern of rglob argument returns this reuslt. Can someone explain this? Thanks.
has comment: http://stackoverflow.com/comment/91173292
type: Question
has title: Python rglob pattern for directory search
upvote count: 12
has answer: http://stackoverflow.com/a/52111877
tagged with: pathlib
score: 12
accepted answer: http://stackoverflow.com/a/52111877
answer count: 1
downvote count: 0

http://stackoverflow.com/comment/91087128
score: 0
type: AnswerComment
type: Comment
has text: I imagine that this is a bug, and only the TAB character should be the one missing, I would think it should still forward all other events - might see if this is actually a bug or an 'intended feature'.
comment on: http://stackoverflow.com/a/52013024

http://stackoverflow.com/q/52055658
downvote count: 0
tagged with: scikit-learn
answer count: 3
has answer: http://stackoverflow.com/a/52090830
has comment: http://stackoverflow.com/comment/91061367
tagged with: sklearn-pandas
favorite count: 0
has answer: http://stackoverflow.com/a/57620518
has title: Sklearn_pandas in a pipeline returns TypeError: 'builtin_function_or_method' object is not iterable
tagged with: machine-learning
tagged with: python
has body: I have a data set with categorical and numerical features on which I want to apply some transformations followed by XGBClassifier. Link to data set: https://www.kaggle.com/blastchar/telco-customer-churn As the transformations are different for the numerical and categorical features, I used sklearn_pandas and its DataFrameMapper. To perform one-hot encoding on the categorical features, I want to use DictVectorizer. But to use DictVectorizer, I first need to convert the dataframe into a dict, which I try to do with a custom transformer Dictifier. When I run the Pipeline I get the error 'builtin_function_or_method' object is not iterable. Does anyone know what might be causing this error? import numpy as np import pandas as pd from sklearn_pandas import DataFrameMapper from sklearn_pandas import CategoricalImputer from sklearn_pandas import cross_val_score from sklearn.preprocessing import LabelEncoder from sklearn.preprocessing import Imputer from sklearn.preprocessing import StandardScaler from sklearn.feature_extraction import DictVectorizer from sklearn.pipeline import Pipeline from sklearn.pipeline import FeatureUnion from sklearn.base import BaseEstimator from sklearn.base import TransformerMixin import xgboost as xgb # Importing the data df = pd.read_csv('../input/WA_Fn-UseC_-Telco-Customer-Churn.csv', na_values=' ') X, y = df.iloc[:,1:-1], df.iloc[:,-1] # Label encoding of the target classes le = LabelEncoder() y = le.fit_transform(y.values.reshape(y.shape[0], )) # Defining the num and cat column names cat_cols = X.columns[X.dtypes == object].tolist() num_cols = X.columns[X.dtypes != object].tolist() # DataFrameMappers for num and cat columns num_transf_mapper = DataFrameMapper([([num_col], [Imputer(strategy="median"), StandardScaler()]) for num_col in num_cols], input_df=True, df_out=True) cat_transf_mapper = DataFrameMapper([(cat_col , [CategoricalImputer()]) for cat_col in cat_cols], input_df=True, df_out=True) # FeatureUnion of num and cat columns num_cat_u…
type: AnsweredQuestion
score: 3
upvote count: 3
accepted answer: http://stackoverflow.com/a/52090830
type: Question
possible better answer: http://stackoverflow.com/a/52115824
tagged with: pipeline
has answer: http://stackoverflow.com/a/52115824

http://stackoverflow.com/a/52014339
has comment: http://stackoverflow.com/comment/90981316
has body: This is how django contrib.auth.logout is supposed to be used (this is from the manual): from django.contrib.auth import logout def logout_view(request): logout(request) # Redirect to a success page. And this is what I mentioned in my comment. When someone logs out you need to redirect to another page that can be any page of your choosing, even the previous page that the user was on def logout_view(request): logout(request) return HttpResponseRedirect("/") Now when the user hits the back button, they go back to the logout page, which will send them onto the home page again ad infinitum, effectively preventing them from seeing the old content.
upvote count: 1
type: Answer
has comment: http://stackoverflow.com/comment/90981618
downvote count: 0
has comment: http://stackoverflow.com/comment/90980616
score: 1
answers question: http://stackoverflow.com/q/52014217

http://stackoverflow.com/q/51986961
has answer: http://stackoverflow.com/a/51987884
has body: I have a software which generates .log files, and the problem is that they are not persistent (each time the programs try to write an event it might rewrite over an past event which is not desirable) Do you know a way in which I can write a python script for detecting when the program is opening a .log file in order to write something and make sure that he is not overwriting? Thanks!
type: Question
has comment: http://stackoverflow.com/comment/90923770
tagged with: python
favorite count: 0
has comment: http://stackoverflow.com/comment/105858933
upvote count: 2
answer count: 3
tagged with: file
tagged with: logging
tagged with: persistent-storage
has answer: http://stackoverflow.com/a/51987980
has answer: http://stackoverflow.com/a/51987669
has title: Making .log files persistent
tagged with: python-watchdog
score: 2
downvote count: 0
type: UnansweredQuestion

http://stackoverflow.com/comment/91020863
type: Comment
score: 0
comment on: http://stackoverflow.com/q/52016217
type: QuestionComment
has text: I declared the dictionary mdict and replaced the parameters as result.params = mdict in above code. I used the same result object of model with updated model to predict new output. Sadly, I dont understand why the model prediction is returning same values

http://stackoverflow.com/comment/91041325
comment on: http://stackoverflow.com/q/52006223
type: QuestionComment
type: Comment
has text: One option is to just loop through angles and radii and round the resulting points to integers, replacing 1 in a mask of zeros at each resultant set of indices.. it won't be fast and it's overkill, but it would work
score: 0

http://stackoverflow.com/comment/91186119
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52102569
type: Comment
has text: this is beautiful, i never thought to create a second variable to use. thanks! helped alot.

http://stackoverflow.com/a/52105828
upvote count: 1
has comment: http://stackoverflow.com/comment/91192280
answers question: http://stackoverflow.com/q/52104686
has body: As @smarx said, INFURA does not supports filters over HTTP. They do have some support over sockets, but I believe it is not yet production ready. It's worth a try, though. Web3.py has a built-in way to connect using websockets that you can initialize like so: from web3 import Web3 w3 = Web3(Web3.WebsocketProvider("wss://mainnet.infura.io/ws"))
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/91192270
has comment: http://stackoverflow.com/comment/91192579
score: 1

http://stackoverflow.com/comment/90926323
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51988215
type: AnswerComment
has text: "if a PID has no parent it is not added to the root node." That's easy enough to deal with. If in the `for d in links:` loop the "PPID" field is "" then convert it to "0", eg `ppid, pid = d["PPID"] or "0", d["Pid"]`

http://stackoverflow.com/q/52027616
duplicate of: http://stackoverflow.com/q/48371856
linked to: http://stackoverflow.com/q/35446015
tagged with: python
tagged with: dictionary
linked to: http://stackoverflow.com/q/48371856
has answer: http://stackoverflow.com/a/52027643
accepted answer: http://stackoverflow.com/a/52027643
downvote count: 0
duplicate of: http://stackoverflow.com/q/47393295
score: 6
type: Question
type: AnsweredQuestion
has body: I have a dict that looks like this: "votes": { "user1": "yes", "user2": "no", "user3": "yes", "user4": "no", "user5": "maybe", "user6": "yes" } What i want to do is, counting the same values so that i know that yes occurred 3 times, no occurred 2 times and maybe occurred 1 time. What i do right now is this: votes = OrderedDict() for key, value in vote_dict["votes"].items(): if value in votes: votes[value] += 1 else: votes[value] = 1 It works fine but there is for sure a better way to do this. What would be a more pythonic way to do this?
has title: How to count the same values in a dict?
duplicate of: http://stackoverflow.com/q/14743454
duplicate of: http://stackoverflow.com/q/2393902
answer count: 1
upvote count: 6
tagged with: counter
favorite count: 0
duplicate of: http://stackoverflow.com/q/13462365

http://stackoverflow.com/comment/91031758
has text: Hi Thanks for the provided solution and was able to get a understanding on how I need to proceed to achieve this. Thanks :)
type: QuestionComment
comment on: http://stackoverflow.com/q/51959989
score: 0
type: Comment

http://stackoverflow.com/comment/124665893
type: Comment
comment on: http://stackoverflow.com/a/61647454
score: 1
has text: that's a very cool tip, thanks.
type: AnswerComment

http://stackoverflow.com/a/52095180
has comment: http://stackoverflow.com/comment/91176043
has comment: http://stackoverflow.com/comment/91180230
answers question: http://stackoverflow.com/q/52094863
score: 2
has comment: http://stackoverflow.com/comment/91172940
accepted answer of: http://stackoverflow.com/q/52094863
has body: It's mentioned here that the form is from typing import Dict class Test(Dict[str, int]): def __init__(self): self.update({'a': 5}) test = Test() print(test) # prints {'a': 5}
type: AcceptedAnswer
downvote count: 0
type: Answer
upvote count: 2

http://stackoverflow.com/q/52064358
has answer: http://stackoverflow.com/a/52067253
accepted answer: http://stackoverflow.com/a/52069213
downvote count: 0
has title: Trying to get my player to transfrom.flip python
possible better answer: http://stackoverflow.com/a/52067253
tagged with: flip
score: 2
type: AnsweredQuestion
has body: I am struggling with pygame. I want my player to move and face right or left when I press the right or left key respectively. Instead it just flips. I don't know how to make it point to the left, or right and then walk. run = True while run: for event in pg.event.get(): if event.type == pg.QUIT: run = False if event.type == pg.KEYDOWN: if event.key == pg.K_RIGHT: swordsman = pg.transform.flip(swordsman, True, False) x += speed if event.key == pg.K_LEFT: swordsman = pg.transform.flip(swordsman, True, False) x -= speed
favorite count: 0
tagged with: python-3.x
type: Question
upvote count: 2
answer count: 2
tagged with: python
tagged with: pygame
has answer: http://stackoverflow.com/a/52069213
tagged with: transform

http://stackoverflow.com/comment/91114602
type: AnswerComment
has text: @mad_ that is still not correct, because, when you create the dict, order is already lost. Converting it to a `OrderedDict` later won't help. Your code will work fine in python 3.7 because dicts are now guaranteed to have same order as created, but only if the dict is created in the code like in your example, otherwise it can fail if more keys are added to the dict out of the normal order.
type: Comment
score: 2
comment on: http://stackoverflow.com/a/52082026

http://stackoverflow.com/q/52098427
downvote count: 1
accepted answer: http://stackoverflow.com/a/52103038
type: Question
possible better answer: http://stackoverflow.com/a/63482705
has answer: http://stackoverflow.com/a/63482705
score: 0
answer count: 2
has comment: http://stackoverflow.com/comment/91148634
has body: In my database is style and I wanna used it in template, but I don't know how. models.py class Post(models.Model): # ... body = models.TextField() # HTML style = models.TextField() # CSS # ... views.py (I don't know Will it is useful) # ... # Context have to be get to every template extends form 'base.html' base_context = { "category": Category.objects.all(), } # ... def detail(request, slug, day, month, year): context = base_context.copy() context['post'] = Post.objects.get(slug=slug, created__day=day, created__month=month, created__year=year) return render(request, 'post/detail.html', context) # ... I tried: {# ... #} &lt;style&gt; {{ post.style }} &lt;/style&gt; {# ... #} (I know how to use styles saved in "static" directory) I'm using django 2.1, and python 3.7.
favorite count: 0
has answer: http://stackoverflow.com/a/52103038
has title: Django, Use style from database
tagged with: django
tagged with: python
tagged with: css
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91147620
has comment: http://stackoverflow.com/comment/91150755
has comment: http://stackoverflow.com/comment/91147268
upvote count: 1

http://stackoverflow.com/comment/90938879
type: QuestionComment
has text: The one exception to that rule is if you pass in a callback function, and I call your callback, and you raise some exception I never heard of, I may or may not pass that through to you. Either way is probably acceptable, but in that case is probably document whichever I chose, by adding something like “and any exceptions raised by the callback argument” to the end of the list.
comment on: http://stackoverflow.com/q/51994464
type: Comment
score: 0

http://stackoverflow.com/comment/91151007
has text: in same enviroement my_env bcz i have only one environment that i created while installing anaconda
score: 0
comment on: http://stackoverflow.com/q/52096590
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/91053185
comment on: http://stackoverflow.com/a/52051226
has text: ValueError("Unknown string format:", timestr) ValueError: ('Unknown string format:', 'nternal Server Err')
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/91037656
has text: @AKX Depends what's meant by "easy", I was talking about ease of reading and writing it.
type: Comment
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/52043345

http://stackoverflow.com/comment/100868073
has text: @gerrit: The answer to your questions is more involved than I want to get into in a comment. If you ask it as a new question I would be happy to answer.
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52006681

http://stackoverflow.com/comment/91136848
score: 0
type: Comment
comment on: http://stackoverflow.com/q/52086264
type: QuestionComment
has text: @DanielF Wildcards can take on any value (and will hence match any value present at the index the wildcard is present). I've used "?" to denote these wildcards, sometimes these get denote them as "*", though.

http://stackoverflow.com/comment/91082622
score: 0
type: AnswerComment
type: Comment
has text: You already have my +1 (this I guess was counter-acted by someone else's downvote...)
comment on: http://stackoverflow.com/a/52065786

http://stackoverflow.com/comment/90959265
has text: It doesn't work that way. It only reads local files. The path is passed to `open()`, which only work with local files. You'll have to download it first. That can be done programmatically, but is a solved problem outside the scope of this question.
comment on: http://stackoverflow.com/q/51994317
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51981095
type: UnansweredQuestion
has body: I'm using keras/tensorflow on google colaboratory and I need to go back to previous versions of them. The problem is when I run !pip install q keras==1.2.2 , the kernel shows keras 1.2.2 installed but when I check it using keras.__version_ it shows 2.1.6 . And same case is with tensorflow. How do I fix this?
tagged with: python
upvote count: 15
downvote count: 0
has title: How to change Keras/tensorflow version in Google colab?
tagged with: tensorflow
type: Question
has answer: http://stackoverflow.com/a/51984336
has answer: http://stackoverflow.com/a/61449122
tagged with: google-colaboratory
score: 15
has answer: http://stackoverflow.com/a/58063570
answer count: 3
tagged with: keras
favorite count: 0

http://stackoverflow.com/comment/90993441
score: 0
has text: The condition `soup.find('li')` never becomes false because the variable `soup` never changes in the loop. Add line `soup = BeautifulSoup(page.text, 'html.parser')` after `count = count+1`.
type: Comment
comment on: http://stackoverflow.com/q/52021506
type: QuestionComment

http://stackoverflow.com/comment/91163810
comment on: http://stackoverflow.com/a/52048738
has text: @camposquinn Are all your files coming by SFTP, or also just plain FTP, http, etc? ie, what's handling that piece?
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/91039842
has text: The 1 `id` is a vertical line?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52044434
score: 0

http://stackoverflow.com/a/52074772
has comment: http://stackoverflow.com/comment/91099626
upvote count: 2
has body: Is selenium necessary? looks like you can use URLs to arrive at what you want: http://www.arohan.in/branch-locator.php?state=Assam&amp;branch=Mirza. Get a list of the state / branch combinations then use the beautiful soup tutorial to get the info from each page.
type: Answer
answers question: http://stackoverflow.com/q/52074680
score: 2
downvote count: 0

http://stackoverflow.com/comment/91094718
has text: If you could run "ls -ld /home/django/media_cdn/" in a shell window it will show the permissions for the folder. Then we can understand whether the permissions need to be modified.
comment on: http://stackoverflow.com/q/52064821
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/91106767
type: Comment
has text: Thanks a lot for the descriptive answer!
comment on: http://stackoverflow.com/a/51987863
score: 0
type: AnswerComment

http://stackoverflow.com/a/51983263
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/90916509
has comment: http://stackoverflow.com/comment/90916374
has body: Use reindex by sorted index and columns names: df = df.reindex(index=sorted(df.index), columns=sorted(df.columns)) print (df) Balneolavulgaris Caldisericumexile \ Balneolavulgaris 0.000000 271.970587 Caldisericumexile 271.970587 0.000000 Chrysiogenesarsenatis 25.298221 271.970587 Chthonomonascalidirosea 271.970587 11.313708 Desulfurispirillumindicum 25.298221 271.970587 Gracilimonastropica 11.313708 271.970587 Haloplasmacontractile 271.970587 11.313708 Chrysiogenesarsenatis Chthonomonascalidirosea \ Balneolavulgaris 25.298221 271.970587 Caldisericumexile 271.970587 11.313708 Chrysiogenesarsenatis 0.000000 271.970587 Chthonomonascalidirosea 271.970587 0.000000 Desulfurispirillumindicum 11.313708 271.970587 Gracilimonastropica 25.298221 271.970587 Haloplasmacontractile 271.970587 11.313708 Desulfurispirillumindicum Gracilimonastropica \ Balneolavulgaris 25.298221 11.313708 Caldisericumexile 271.970587 271.970587 Chrysiogenesarsenatis 11.313708 25.298221 Chthonomonascalidirosea 271.970587 271.970587 Desulfurispirillumindicum 0.000000 25.298221 Gracilimonastropica 25.298221 0.000000 Haloplasmacontractile 271.970587 271.970587 Haloplasmacontractile Balneolavulgaris 271.970587 Caldisericumexile 11.313708 Chrysiogenesarsenatis 271.970587 Chthonomonascalidirosea 11.313708 Desulfurispirillumindicum 271.970587 Gracilimonastropica 271.970587 Haloplasmacontractile 0.000000
has comment: http://stackoverflow.com/comment/90916329
type: Answer
upvote count: 1
accepted answer of: http://stackoverflow.com/q/51983216
answers question: http://stackoverflow.com/q/51983216
type: AcceptedAnswer

http://stackoverflow.com/q/51963659
score: -1
tagged with: sorting
type: Question
answer count: 2
upvote count: 0
has body: I have a list of dictionaries in python. I want to sort it by keys i.e., first by chain_id, then by start.residue_number and then by end.residue_number. In the list below, the 4th and 6th element should be coming the other way around. I could use sorted with from operator import itemgetter, attrgetter to sort on chain_id, but how to do same with a dictionary inside dictionary? "mappings": [ { "entity_id": 1, "end": { "residue_number": 63 }, "start": { "residue_number": 1 }, "chain_id": "A", "struct_asym_id": "A" }, { "entity_id": 1, "end": { "residue_number": 116 }, "start": { "residue_number": 1 }, "chain_id": "A", "struct_asym_id": "A" }, { "entity_id": 1, "end": { "residue_number": 124 }, "start": { "residue_number": 1 }, "chain_id": "A", "struct_asym_id": "A" }, { "entity_id": 1, "end": { "residue_number": 116 }, "start": { "residue_number": 1 }, "chain_id": "B", "struct_asym_id": "B" }, { "entity_id": 1, "end": { "residue_number": 124 }, "start": { "residue_number": 1 }, "chain_id": "B", "struct_asym_id": "B" }, { "entity_id": 1, "end": { "residue_number": 63 }, "start": { "residue_number": 1 }, "chain_id": "B", "struct_asym_id": "B" } ]
favorite count: 0
accepted answer: http://stackoverflow.com/a/51963822
tagged with: python
tagged with: dictionary
downvote count: 1
has title: How to sort a list in Python based on a set of keys in different levels
possible better answer: http://stackoverflow.com/a/51963872
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51963872
has comment: http://stackoverflow.com/comment/90877625
has answer: http://stackoverflow.com/a/51963822

http://stackoverflow.com/comment/91037650
has text: This can be done using Keras Functional API. It offers high flexibility while building models. https://keras.io/getting-started/functional-api-guide/
score: 0
comment on: http://stackoverflow.com/q/52041545
type: QuestionComment
type: Comment

http://stackoverflow.com/a/52024114
has body: The first step is to try to formulate the problem in terms of a graph. In this case, each node (also called vertex) in the graph represents some possible configuration (position or state) of the desert, described by a truck location and the amount of gas in each camp. Since the desert is a fixed line, it makes sense to represent it as an array of gas amounts. With those details set, here's the start node of the graph: truck (gas: 3) v [0, 0, 0, 0, 0] ^ ^ start goal From this position, call it (A), what transitions (edges) to another node are possible? Here they are: (B) (C) (D) truck (gas: 0) truck (gas: 0) truck (gas: 0) v v v [0, 2, 0, 0, 0] [0, 0, 1, 0, 0] [0, 0, 0, 0, 0] Here's how the transitions look in graph form: A /|\ / | \ B C D Nodes (B), (C) and (D) are all of the child nodes of (A), their parent, meaning there is an available transition from the parent to the child. Exploring these children one by one is a BFS, whereas in a DFS, you'd pick the first child, (B), and keep exploring its first child until it reaches a leaf node with no children. Clearly, (D) is a terminal leaf node because it has no children (it's not the goal, the truck has no gas and the camp it's at has no gas, so it's stuck; there are no available transitions to consider). The next step is to inspect all of the possible child states available to nodes (B) and (C). Here are the children of (B): (E) (F) (G) truck (gas: 3) truck (gas: 0) truck (gas: 0) v v v [0, 1, 0, 0, 0] [0, 0, 1, 0, 0] [0, 0, 0, 0, 0] (H) truck (gas: 0) v [0, 1, 0, 0, 0] Now the graph looks like: A / | \ / | \ / | \ B C D /|\ \ / | \ \ E F G H Note that nodes (F) and (G) are identical to (C) and (D) and (E) is clearly the most promising route. In spite of that, (C) will be the next expansion, since this is a BFS rather than a DFS. I'll skip the diagram, but it should be clear that both children of (C) ((I) and (J)) are terminal leaf nodes (the truck will run out of gas whether it moves left or right). At this point, th…
type: Answer
answers question: http://stackoverflow.com/q/52023569
upvote count: 1
accepted answer of: http://stackoverflow.com/q/52023569
score: 1
has comment: http://stackoverflow.com/comment/91090873
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/91021849
type: Comment
comment on: http://stackoverflow.com/a/52035240
has text: Hmm, I responded before you edited your answer. Sorry about that. Let me take a look and try it out! :)
score: 0
type: AnswerComment

http://stackoverflow.com/comment/91150642
type: Comment
comment on: http://stackoverflow.com/q/52099985
type: QuestionComment
has text: Can you provide a range of acceptable and unacceptable inputs? Your prose is a bit obscure.
score: 4

http://stackoverflow.com/comment/91200562
type: QuestionComment
comment on: http://stackoverflow.com/q/52063689
type: Comment
has text: A tip to make your code more readable: `for i in text.text: ... for i in words_list: ... for i in lst: ...` Don't call every loop variable `i`, give them distinct meaningful names. In this case: `for sentence in text.text: ... for word in words_list: ...` and the final loop `for i in lst:` seems unnecessary, just compute the mean sentiment of that sentence once after the `for word in words_list: ...` loop has finished.
score: 0

http://stackoverflow.com/comment/105791241
has text: try setting it to root directory likewise: workingDir './TestProject'
type: Comment
comment on: http://stackoverflow.com/q/51964845
score: 0
type: QuestionComment

http://stackoverflow.com/q/52004234
favorite count: 0
tagged with: pandas
tagged with: aggregate-functions
tagged with: python
score: 2
type: AnsweredQuestion
upvote count: 2
has answer: http://stackoverflow.com/a/52004251
has title: Aggregation sum Pandas
type: Question
accepted answer: http://stackoverflow.com/a/52004251
answer count: 1
downvote count: 0
has body: I have the following dataframe How can I aggregate the number of tickets (summing) for every month? I tried: df_res[df_res["type"]=="other"].groupby(["type","date"])["n_tickets"].sum() date is an object

http://stackoverflow.com/q/52081155
has comment: http://stackoverflow.com/comment/91142200
type: Question
has comment: http://stackoverflow.com/comment/91112424
has title: Matching string for row in csv file
score: 0
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
answer count: 0
has comment: http://stackoverflow.com/comment/91112758
type: UnansweredQuestion
has body: This script almost works. However it never matches, and when it does, the values are incorrect. Example: no match Lower 117, $331.50, F, 8, 193 Upper 218, $155.00, AA, 8, 195 match Floor 6, $273.00, N, 2, 195 SECTION,PRICE,ROW,QTY,DYSLSTED So I'm not sure why it isn't working. After all the values from the html file are loaded in the first time, the program should only output match for even list, since they would all be in the csv. But when I run it in the current configuration, the opposite result is true. HTML FILE eagles.html is here Here is my script: import os import sys from bs4 import BeautifulSoup import lxml.html as lh import csv soup = BeautifulSoup(open("eagles.html"), "lxml") ################################################################### variable = 'test_csv_1' ########DELETE dir_path = os.path.dirname(os.path.realpath(__file__)) file_path = (dir_path+'\Sheets') try: os.makedirs(file_path) except: pass ####################### for mytable in soup.find_all('table'): for trs in mytable.find_all('tr'): tds = trs.find_all('td') row1 = [elem.text.strip() for elem in tds] row = str(row1) cool = row.replace("[", "") coolp = cool.replace("]", "") cool2 = coolp.replace("'", "") cool3 = cool2.replace(" , ", "") row = cool3 rowtest = (row.split(',')) if len(rowtest) != 5: rowtest = ['NULL', 'NULL', 'NULL', 'NULL', 'NULL'] ###TABLE STUFF### rowtest0 = rowtest[:4] # LISTING WITHOUT DAYS LISTED rowtest1 = rowtest[0:1] # SECTION LOCATION rowtest2 = rowtest[1:2] # TICKET PRICE rowtest3 = rowtest[2:3] # ROW rowtest4 = rowtest[3:4] # TICKET QTY rowtest5 = rowtest[4:5] # DAYS LISTED ###TABLE STUFF# ###CREATE CSV HEADER### with open(file_path+'\\'+variable+'.csv', 'a+') as headercsv: if os.stat(file_path+'\\'+variable+'.csv').st_size == 0: writer = csv.writer(headercsv) writer.writerow(["SECTION", "PRICE", "ROW", "QTY", "DYSLSTED"]) print('CREATED HEADERS FOR NEW FILE') else: pass ###WRITE TO CSV### with open(file_path+'\\'+variable+'.csv', 'r') as rowin: if rowtest == …

http://stackoverflow.com/comment/90959711
score: 0
has text: Why are you running multiple threads which dump to the same JSON file? Explain the root problem you're trying to solve. This sounds like an [XY problem](http://xyproblem.info/).
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52004427

http://stackoverflow.com/comment/91064205
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52052408
has text: output ordering is not an issue, but i want expected records in output data frame.

http://stackoverflow.com/q/52048631
possible better answer: http://stackoverflow.com/a/52052837
has body: I'm using both the Scikit-Learn and Seaborn logistic regression functions -- the former for extracting model info (i.e. log-odds, parameters, etc.) and the later for plotting the resulting sigmoidal curve fit to the probability estimations. Maybe my intuition is incorrect for how to interpret this plot, but I don't seem to be getting results as I'd expect: #Build and visualize a simple logistic regression ap_X = ap'TOEFL Score'.values ap_y = ap['Chance of Admit'].values ap_lr = LogisticRegression() ap_lr.fit(ap_X, ap_y) def ap_log_regplot(ap_X, ap_y): plt.figure(figsize=(15,10)) sns.regplot(ap_X, ap_y, logistic=True, color='green') return None ap_log_regplot(ap_X, ap_y) plt.xlabel('TOEFL Score') plt.ylabel('Probability') plt.title('Logistic Regression: Probability of High Chance by TOEFL Score') plt.show Seems alright, but then I attempt to use the predict_proba function in Scikit-Learn to find the probabilities of Chance to Admit given some arbitrary value for TOEFL Score (in this case 108, 104, and 112): eight = ap_lr.predict_proba(108)[:, 1] four = ap_lr.predict_proba(104)[:, 1] twelve = ap_lr.predict_proba(112)[:, 1] print(eight, four, twelve) Where I get: [0.49939019] [0.44665597] [0.55213799] To me, this seems to indicate that a TOEFL Score of 112 gives an individual a 55% chance of being admitted based on this data set. If I were to extend a vertical line from 112 on the x-axis to the sigmoid curve, I'd expect the intersection at around .90. Am I interpreting/modeling this correctly? I realize that I'm using two different packages to calculate the model coefficients but with another model using a different data set, I seem to get correct predictions that fit the logistic curve. Any ideas or am I completely modeling/interpreting this inaccurately?
type: Question
answer count: 2
upvote count: 6
tagged with: scikit-learn
favorite count: 0
has answer: http://stackoverflow.com/a/52052837
tagged with: python
has title: Seaborn Regplot and Scikit-Learn Logistic Models Calculated Differently?
tagged with: seaborn
score: 6
has comment: http://stackoverflow.com/comment/91055708
tagged with: logistic-regression
type: AnsweredQuestion
downvote count: 0
has answer: http://stackoverflow.com/a/52064154
accepted answer: http://stackoverflow.com/a/52064154

http://stackoverflow.com/comment/90954728
type: QuestionComment
comment on: http://stackoverflow.com/q/52002733
has text: Relevant, but not duplicate: https://stackoverflow.com/q/3584805/2988730
score: 0
type: Comment

editor
tags question: http://stackoverflow.com/q/52014762
tags question: http://stackoverflow.com/q/52002973
tag name: editor
type: Tag

http://stackoverflow.com/q/52104544
type: Question
has answer: http://stackoverflow.com/a/52104666
has title: Reorder Multiindex Pandas Dataframe
accepted answer: http://stackoverflow.com/a/52104666
score: 5
has comment: http://stackoverflow.com/comment/91160449
upvote count: 5
tagged with: dataframe
has comment: http://stackoverflow.com/comment/91160374
tagged with: pandas
has comment: http://stackoverflow.com/comment/91160233
has comment: http://stackoverflow.com/comment/91161392
has body: I would like to reorder the columns in a dataframe, and keep the underlying values in the right columns. For example this is the dataframe I have cols = [ ['Three', 'Two'],['A', 'D', 'C', 'B']] header = pd.MultiIndex.from_product(cols) df = pd.DataFrame([[1,4,3,2,5,8,7,6]]*4,index=np.arange(1,5),columns=header) df.loc[:,('One','E')] = 9 df.loc[:,('One','F')] = 10 &gt;&gt;&gt; df And I would like to change it as follows: header2 = pd.MultiIndex(levels=[['One', 'Two', 'Three'], ['E', 'F', 'A', 'B', 'C', 'D']], labels=[[0, 0, 0, 0, 1, 1, 1, 1, 2, 2], [0, 1, 2, 3, 4, 5, 2, 3, 4, 5]]) df2 = pd.DataFrame([[9,10,1,2,3,4,5,6,7,8]]*4,index=np.arange(1,5), columns=header2) &gt;&gt;&gt;&gt;df2
answer count: 1
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/91160315
tagged with: python
type: AnsweredQuestion
tagged with: multi-index

http://stackoverflow.com/comment/91099857
score: 0
comment on: http://stackoverflow.com/q/52073649
type: Comment
type: QuestionComment
has text: @Basj i need to mege them one after the other

http://stackoverflow.com/comment/91087654
has text: @Don Can you correct me ? where is the mistake that it is not returning me the record of User with max number i.e I want Result [<Shin_roma_1.2>,<Jessie_madrid_1.1>].
score: 0
type: Comment
comment on: http://stackoverflow.com/q/52064443
type: QuestionComment

http://stackoverflow.com/q/52026423
has comment: http://stackoverflow.com/comment/91003174
has comment: http://stackoverflow.com/comment/91003121
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/91003118
has answer: http://stackoverflow.com/a/52026727
tagged with: forms
type: Question
has body: I've created a form in html (code for that is below). I was wondering if there is a way for me to, using javascript, output the inputs of this form onto a text file on my desktop. So when someone fills in the form and presses submit, a new text file will be created with the two inputs on separate lines. I am then going to read this text file in python. Or if the results from the form could go straight to python instead? &lt;form&gt; School:&lt;br&gt; &lt;input type="text" name="schoolname"&gt;&lt;br&gt; School code:&lt;br&gt; &lt;input type="text" name="schoolcode"&gt;&lt;br&gt; &lt;input type="submit" value="next"&gt; &lt;/form&gt;
has comment: http://stackoverflow.com/comment/91003146
tagged with: javascript
has comment: http://stackoverflow.com/comment/91003028
has title: How could i use javascript to output the results from a html form into a text file on my desktop?
score: 0
linked to: http://stackoverflow.com/q/21012580
tagged with: http://stackoverflow.com/tag/html
answer count: 1

http://stackoverflow.com/comment/91130187
type: Comment
has text: alredy tried that and it didnt help, thank you any way!
comment on: http://stackoverflow.com/a/52041915
type: AnswerComment
score: 0

http://stackoverflow.com/comment/91033313
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52040297
score: 0
has text: Found a similar question like yours. https://stackoverflow.com/questions/7173850/possible-to-get-user-input-without-inserting-a-new-line According to that when we use raw_input() or input() within/through print statements, we cannot print them in same line. Unless we use **Curses** module.

http://stackoverflow.com/comment/90903332
has text: There is really no point in using numpy functions and not using numpy vectorization.
type: Comment
score: 3
type: AnswerComment
comment on: http://stackoverflow.com/a/51976575

http://stackoverflow.com/comment/91054189
comment on: http://stackoverflow.com/a/52041849
type: Comment
has text: oh, there is another thing i haven't noticed. when you add to the text here- `text += pageObj.extractText()` you make it a string ald not a list of strings. use `text += [pageObj.extractText()]` and it will be a list of strings, then i think you should get the result you expect
score: 0
type: AnswerComment

http://stackoverflow.com/a/52026185
has comment: http://stackoverflow.com/comment/91040031
type: Answer
has body: It is probably related to max-execution-time - The maximum time in seconds a script is allowed to run before it is terminated. You can changed this property by editing php.ini or by calling set-time-limit
answers question: http://stackoverflow.com/q/52025236
score: 0

http://stackoverflow.com/comment/91005507
has text: Sorry @shweta, but I don't get which transformation are you performing for going from "C:\webflow_implementaton\SpringWebFlowFlightBooking-master\src\main\java\it\iol\springwebflow\Booking.java" to "C:\webflow_implementaton\SpringWebFlowFlightBooking-master\src\main\webapp". You need to remove from the first "java" appearance and add webapp in its place?
comment on: http://stackoverflow.com/q/52027106
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52056034
answer count: 1
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/52056596
score: -3
upvote count: 0
has comment: http://stackoverflow.com/comment/91062231
has title: *args in python constructor
has comment: http://stackoverflow.com/comment/91062346
favorite count: 0
tagged with: python-3.x
has body: I am trying to write a class which accepts *args and so i need example of passing *args in init. i dont know how many parameters will be passed to *args and so not sure how will assign them. class bank(): def __init__(self, *args ): if args is not None: for i in in argv: self.name=i #now if there are more argument how do i assign them???like i am using "account" and "name" in below function ("withdraw") #but i dont want to pass this in "balance", i want pass just "name" def balance(self,name): bal="select account from banktab where name = '%s'" %(self.name) # result=b.query(bal) print (bal) def withdraw(self,name,account): wit="select account from banktab where name = '%s'" %(self.name) print (self.name) print (self.account)
has comment: http://stackoverflow.com/comment/91062256
type: Question
linked to: http://stackoverflow.com/q/36901
tagged with: python
duplicate of: http://stackoverflow.com/q/36901
has comment: http://stackoverflow.com/comment/91062319
downvote count: 3
linked to: http://stackoverflow.com/q/1373164

http://stackoverflow.com/q/52027739
downvote count: 0
has title: Sniffing The URL and parameters in scapy
favorite count: 0
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/91069992
has comment: http://stackoverflow.com/comment/91072890
answer count: 0
score: 1
tagged with: scapy
has comment: http://stackoverflow.com/comment/91006223
has body: When I sniffing using the python with scapt, The Password is encrypted in hash but in Ettercap it's normal? See this picture: Inside the red box you see the username, password even the INFO.Aside from it, The Password doesn't encrypted with hashes. But when I'm using the python, The Password is encrypted with hash? Why is it happen and how can I fix that? By the way this is the code. from scapy.all import * import re def get_credentials(source): username = None password = None userfields = ['username', 'user', 'name', 'login', 'nickname', 'userfield', 'login-name', 'log', "email", "login-id", 'user-name', 'userID', 'userid', 'user-id', 'login_name', 'login-name', 'login-user', 'login_user', 'account', 'acc-name', "account-user", "account-name"] passfields = ['passwords', 'pword', 'pwd', 'user-passwords', 'pass', '_password', 'password', 'password', 'pwords', 'login-passwords', 'login-pword', 'login-pwords', 'user-password', 'user-paswd'] for login in userfields: user = re.search('(%s=[^&amp;]+)' % login, source, re.IGNORECASE) if user: username = user.group() for p in passfields: passwd = re.search('(%s=[^&amp;]+)' % p, source, re.IGNORECASE) if passwd: password = passwd.group() if username and password != None: return username, password def ctp(pkt): if pkt.haslayer(Ether) and pkt.haslayer(Raw) and not pkt.haslayer(IP) and not pkt.haslayer(IPv6): pass if pkt.haslayer(TCP) and pkt.haslayer(Raw) and pkt.haslayer(IP): mains = str(bytes(pkt[TCP].payload)) source = str(pkt[TCP].payload) creds = get_credentials(source) if creds != None: print(creds) else: pass print('SNIFFING') sniff(iface="lo", prn=ctp, store=0) # lo is my Local Loopback interface
type: Question
has comment: http://stackoverflow.com/comment/91006411
upvote count: 1

http://stackoverflow.com/q/52068949
has body: I'm new to message queues in general and at the moment I'm working with apache Kafka. I have a python script that takes data from a crypto currency exchange and sends it to one of the Kafka topics. Are there better ways of connecting web sockets to Kafka as producers other than using scripting?
answer count: 0
upvote count: 2
type: UnansweredQuestion
tagged with: python
downvote count: 1
tagged with: apache-kafka
has title: What is the best practice to connect an incoming web socket to Kafka?
score: 1
has comment: http://stackoverflow.com/comment/91123404
type: Question
has comment: http://stackoverflow.com/comment/91125578
favorite count: 0
tagged with: kafka-producer-api
has comment: http://stackoverflow.com/comment/91102409

http://stackoverflow.com/q/52079297
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/52079746
tagged with: python
tagged with: gmail
score: 1
upvote count: 1
has title: Can't send email (gmail) via python
type: Question
has answer: http://stackoverflow.com/a/52079956
has comment: http://stackoverflow.com/comment/91110589
tagged with: smtplib
downvote count: 0
has comment: http://stackoverflow.com/comment/91110607
answer count: 2
has comment: http://stackoverflow.com/comment/91108838
favorite count: 0
has comment: http://stackoverflow.com/comment/91108848
has body: I have a code which was working like a half year ago. It basiclly sends email. import smtplib import socket gmail_user="SENDERMAIL" gmail_password="SENDERPASS" to = 'SENDTOTHIS' email_text = "ADSADSADSA" try: server = smtplib.SMTP_SSL('smtp.gmail.com', 465) server.ehlo() server.login(gmail_user, gmail_password) server.starttls() server.sendmail(gmail_user, to, email_text) server.close() #I was using this code below and it was working. I tried above code but it also did not work. #server = smtplib.SMTP("smtp.gmail.com:587") #server.ehlo() #server.starttls() #server.ehlo() #server.login(gmail_user, gmail_password) #server.sendmail(gmail_user, to, email_text) #server.close() print("Done") except Exception as exception: print(exception) Here's exception (534, b'5.7.14 5.7.14 KL7_2qGSLW9IBjP8dKKgP67bEgyKNc5ls76dnVDZcUlVQjJUQb0JX9BIVi_Agb84vKNOKB 5.7.14 fshB0ngZ_Tn8ocDpDHKavRKXmluVjHo5YM7ADKENtWn4aVTxyvaBlbXRGpA1EBh91bdV-o 5.7.14 pwiAWUHXKmRQEuSNSiFcv68DP4a7ghIu9YKnTyqtUEhGd4HgKtxa4Jz0mhSQDjD13UQWYB 5.7.14 -YEL5Sd2h5YxN8kkSAsK-J_hXMbpy7wNyeCov8lq1Aa3spZzgo> Please log in via 5.7.14 your web browser and then try again. 5.7.14 Learn more at 5.7.14 https://support.google.com/mail/answer/78754 f132-v6sm3660398wme.24 - gsmtp') I did try to logined gmail add device to trusted devices turned on IMAP via gmail let less secure apps tried this: https://support.google.com/mail/answer/7126229?visit_id=636711453029417344-336837064&amp;rd=2#cantsignin

http://stackoverflow.com/a/52084875
type: Answer
score: 0
has comment: http://stackoverflow.com/comment/91120029
has comment: http://stackoverflow.com/comment/91120200
answers question: http://stackoverflow.com/q/52084524
has body: for i in reversed(range(len(rows))): ... rows.pop(i) Don't remove items from a list while you're iterating over it. len() is only calculated once, at the top of the loop, so when you shorten the list during the loop execution, you end up trying to iterate over items that aren't there anymore.

http://stackoverflow.com/comment/90974440
type: Comment
has text: @GilbertoRoblesSilva Meanwhile, of course you can use any rule you want for when to exit. If you want "Press 'q' to end", just `print` that as the message, and do `if interest == 'q':` for the `break` instead of `if not interest:`.
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/52011147

http://stackoverflow.com/comment/91159841
comment on: http://stackoverflow.com/a/52084666
score: 0
type: AnswerComment
type: Comment
has text: @ysl in that case I'd recommend splitting up this column into separate columns or separate DataFrames. DataFrame columns should be only of one type (as Alex mentioned)

http://stackoverflow.com/q/52015836
answer count: 2
has answer: http://stackoverflow.com/a/52018958
downvote count: 0
favorite count: 0
tagged with: tkinter
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/90982271
has answer: http://stackoverflow.com/a/52016170
score: 3
upvote count: 3
has comment: http://stackoverflow.com/comment/90983433
type: Question
has comment: http://stackoverflow.com/comment/90982118
has title: Updating tkinter label based on loop
has body: Background Information Hello. What I'm trying to do currently is create the tkinter window, run a for loop and update the label in real-time as the for loop is running through the directories (in this case, it is listing all the directories with their full paths in the C drive of my computer). The Problem The problem that I'm running into is that as soon as I click the start button (which begins the for loop) the GUI completely freezes (I'm aware that this is because tkinter and loops don't play well, I just wonder if there is a solution I'm not aware of), which is counter intuitive as I'd like it to display the directory that the loop is currently iterating over within my tooltip label. What I've tried so far from tkinter import Tk, Label, Frame, Button import os def start_command(): for root_directory, sub_directories, files in os.walk("C:\\"): for sub_directory in sub_directories: full_directory = os.path.join(root_directory, sub_directory) tooltip.config(text=full_directory) window = Tk() tooltip = Label(window, text="Nothing Here Yet") tooltip.pack() start = Button(text="Start", command=start_command) start.pack() window.mainloop() Tl;Dr I'm trying to run a for loop within tkinter and update the label every iteration. The problem is the GUI is freezing with the above code. Any help would be greatly appreciated. Thank you for your time :)

http://stackoverflow.com/comment/90980212
score: 1
has text: Dupe: [How to correct TypeError: Unicode-objects must be encoded before hashing?](//stackoverflow.com/q/7585307)
comment on: http://stackoverflow.com/q/52014880
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91200622
type: Comment
comment on: http://stackoverflow.com/a/52110433
has text: I couldn't reproduce the behaviour :(
score: 0
type: AnswerComment

http://stackoverflow.com/q/51965039
has answer: http://stackoverflow.com/a/51967688
type: UnansweredQuestion
tagged with: python
has body: I'm querying mongo for a set of objects using mongoengine and I have to return the results as an array of JSON. This is how the object is defined: class OptimisedSummary(Document): date_from = DateTimeField() date_to = DateTimeField() (...) This is how I'm returning the data: return OptimisedSummary.objects(date_from__gte=_date_from, date_to__lte=_date_to).to_json() The problem is that my objects have date fields, and they are comming like this: "date_from": { "$date": 1534334450799 }, "date_to": { "$date": 1534420850799 }, There is any way to pre-format those to return them in a readable format? I appreciate any help, thanks
type: Question
tagged with: mongodb
has title: Mongoengine - Returning dates in a readable format
tagged with: flask
tagged with: mongoengine
score: 0
answer count: 1

http://stackoverflow.com/comment/90899074
score: 1
comment on: http://stackoverflow.com/q/51974293
type: Comment
type: QuestionComment
has text: For a mutable type? No, there isn't. Use immutable types (like tuples) if you want certainty. It's a good question, though.

django-migrations
tags question: http://stackoverflow.com/q/52057583
type: Tag
tag name: django-migrations

http://stackoverflow.com/q/51982806
has answer: http://stackoverflow.com/a/76265353
has comment: http://stackoverflow.com/comment/90937344
downvote count: 0
linked to: http://stackoverflow.com/q/48982061
has answer: http://stackoverflow.com/a/74837198
favorite count: 0
has comment: http://stackoverflow.com/comment/90936952
has answer: http://stackoverflow.com/a/51991091
has body: How can I make my bot use my custom emoji in any discord server? @bot.command(pass_context=True) async def ping(ctx): msg = "Pong :CustomEmoji: {0.author.mention}".format(ctx.message) await bot.say(msg) Example: If I upload some custom emojis on Server 1 and when we use the !ping command (mentioned above) in Server 2 or Server 3 or any server where the bot has access to, it should use the custom emoji. Result: Pong with :CustomEmoji:
tagged with: python
tagged with: discord
has answer: http://stackoverflow.com/a/64201302
has title: How do I make my discord.py bot use custom emoji?
tagged with: python-3.x
answer count: 5
type: UnansweredQuestion
type: Question
has comment: http://stackoverflow.com/comment/90955827
tagged with: discord.py
has comment: http://stackoverflow.com/comment/90937252
score: 15
upvote count: 15
has comment: http://stackoverflow.com/comment/90955580
has answer: http://stackoverflow.com/a/67944399

http://stackoverflow.com/a/51983668
upvote count: 3
downvote count: 0
has body: Short answer: the negation of "all B objects with a related A object with variable = True" is not the query "*all B objects with a related A object with variable = False". You can query on this like: B.objects.filter(a__variable=False) or in case the field is NULL-able: B.objects.filter(Q(a__variable=None) | Q(a__variable=False)) Background: negating existentially quantified expressions This is expected behavior. Since if you query a related model in a one-to-many fashion, the designers of the Django ORM have picked the existential quantifier ∃ over the universal quantifier ∀. There is no inherent best choice, although I think most queries humans will perform are existentially quantified*. An existential quantifier means "there exists", so if you write B.objects.filter(a__variable=True), you ask for B objects where "there exists a related A object with variable=True". But the negation of this is not the list of B objects "where there exists a related A object with variable=False" (let us ignore the NULL vase for now). Indeed a B object that has two related A objects, one with variable = True, and one with variable = False would occur in both the original variant, and its negation. The negation of a existentially quantified requirement, is the univerally quantified variant of the negation of that predicate. Or in mathematics: ¬∃x: P(x) ↔ ∀x: ¬ P(x) It thus means that the negation of the query "All B objects for which there exists an A with variable=True", is the query "*All B objects for which all related A objects have a variable that is not B*". Notice the all in the second query. It thus means that for each row in the A table, we need to "iterate" over the related "B" objects, to check if all these variables are not True. This is not really "tailored" for JOINs. In the case of a BooleanField we could do that with a GROUP BY and a MAX(..) to check if at least one such TRUE exists, and thus constrain it that this is not TRUE. Something like: SELECT b.*, MAX(a.variab…
type: Answer
score: 3
accepted answer of: http://stackoverflow.com/q/51983257
answers question: http://stackoverflow.com/q/51983257
type: AcceptedAnswer

http://stackoverflow.com/q/52041963
has comment: http://stackoverflow.com/comment/91035024
has comment: http://stackoverflow.com/comment/91034689
upvote count: 2
type: Question
has title: Select rows containing a NaN following a specific value in Pandas
has body: I am trying to create a new DataFrame consisting of the rows corresponding to the value 1.0 or NaN in the last column, whereby I only take the Nans under a 1.0 (that is, I'm interested in everything until a 0.0 appears). Timestamp Value Mode 00-00-10 34567 1.0 00-00-20 45425 00-00-30 46773 0.0 00-00.40 64567 00-00-50 25665 1.0 00-00-60 25678 My attempt is: for row in data.itertuples(): while data[data.Mode != 0.0]: df2 = df2.append(row) else: #How do I differentiate between a NaN under a 1.0 and a NaN under a 0.0? print (df2) The idea is to save every row until a 0.0 appears, and afterwards ignore every row until a 1.0 appears again.
tagged with: dataframe
has comment: http://stackoverflow.com/comment/91034720
downvote count: 0
answer count: 1
has answer: http://stackoverflow.com/a/52042025
favorite count: 0
tagged with: pandas
accepted answer: http://stackoverflow.com/a/52042025
tagged with: python
score: 2
type: AnsweredQuestion

http://stackoverflow.com/comment/91250855
score: 1
comment on: http://stackoverflow.com/q/52104679
has text: Have you checked your versions of middlewares? It looks like whitenoise would be the culprit. Did you `pip install --upgrade` it to a version that is compatible with django 2.1?
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52073574
has comment: http://stackoverflow.com/comment/91097457
accepted answer: http://stackoverflow.com/a/52073824
possible better answer: http://stackoverflow.com/a/52073646
tagged with: http://stackoverflow.com/tag/json
type: Question
has title: Dynamic JSON in Python
answer count: 2
downvote count: 0
favorite count: 0
has body: I need to build the following JSON structure dynamically. json = { "mainkey":"val1", "key2":[ {"keya":"val1rec1","keyb":"val2rec1","keyc":"val3rec1"}, {"keya":"val1rec2","keyb":"val2rec2","keyc":"val3rec2"}, {"keya":"val1rec3","keyb":"val2rec3","keyc":"val3rec3"}, {"keya":"val1rec4","keyb":"val2rec4","keyc":"val3rec4"}, {"keya":"val1rec5","keyb":"val2rec5","keyc":"val3rec5"} ] } only the "{"keya":"val1rec1","keyb":"val2rec1","keyc":"val3rec1"}," rows "iterate" - ie, reading values from a CSV file and then populating/creating the rows based on what is inside a CSV file. So my pseudo code looks something like this: #create dict path = 'somewhere\on\my\disk\file.csv' json_file = {} json_file['mainkey'] = "val1" #read from CSV file df1 = pd.read_csv(path, header=None) #iterate through csv for row,s in df1.iterrows(): number = df1.loc[row,0] #I'm reading keyb and keyc values from CSV as well, but for brevity my substitution below is not showing that.... json_file['key2'] = "'keya':'"+str(number)+"','keyb':'whatever','keyc':'whatever'" print (json_file) It obviously fails to produce what I'm looking for above - hence my post here for assistance.
has comment: http://stackoverflow.com/comment/91097003
upvote count: 3
has answer: http://stackoverflow.com/a/52073824
tagged with: python
has answer: http://stackoverflow.com/a/52073646
type: AnsweredQuestion
score: 3

http://stackoverflow.com/q/51958832
has comment: http://stackoverflow.com/comment/90873481
upvote count: 1
answer count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/90872579
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/90868642
has title: Read .img file in python script
type: Question
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51959147
accepted answer: http://stackoverflow.com/a/51959147
favorite count: 0
has body: I have tried pycdlib and isoparser to read .img files which contain about hundred of images. Both got error message. pycdlib: PyCdlibInvalidISO: Valid ISO9660 filesystems must have at least one PVD. isoparser: SourceError: Wrong volume descriptor identifier Is there any problem with .img file?

http://stackoverflow.com/comment/91161525
score: 0
type: AnswerComment
has text: Thank you -- it's too bad that `np.median` doesn't seem to work efficiently with memmapped arrays. Unfortunately I shouldn't test it on my own data if there's any risk of it using too much RAM, out of respect for others' processes that are running on the server.
comment on: http://stackoverflow.com/a/52103968
type: Comment

http://stackoverflow.com/a/52066913
has body: You can use a list comprehension: In [11]: [[int(i) for i in r if not np.isnan(i)] for _, r in df.iterrows()] Out[11]: [[1, 2, 4], [2, 3], [4, 4, 2]] In [12]: [[int(i) for i in r if not np.isnan(i)] for _, r in df.iteritems()] Out[12]: [[1, 2, 4], [2, 3, 4], [4, 2]]
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/52066865
upvote count: 3
score: 3

http://stackoverflow.com/comment/91022890
type: QuestionComment
type: Comment
score: 0
comment on: http://stackoverflow.com/q/52017030
has text: _forcemerge and reindex both API will help you to merge all this index

http://stackoverflow.com/comment/91045239
comment on: http://stackoverflow.com/q/52047077
score: 0
type: Comment
type: QuestionComment
has text: @Prune Sorry, thanks for catching the typo! I've fixed the question.

http://stackoverflow.com/comment/90977778
type: QuestionComment
type: Comment
score: 0
comment on: http://stackoverflow.com/q/52005471
has text: @wwii my numpy version is same as you

http://stackoverflow.com/a/52059279
type: Answer
has body: Here's a simple technique, might not suit for all cases i.e : def sum_t(x): # Compare the value with previous value m = x &gt; x.shift() # If all of them are increasing then return Up if m.sum() == len(m)-1: return 'UP' # if all of them are decreasing then return Down elif m.sum() == 0: return 'DOWN' # else return flat else: return 'FLAT' df.groupby('ColA')['ColB'].apply(sum_t) Output: ColA A UP C FLAT D UP L DOWN Name: ColB, dtype: object
has comment: http://stackoverflow.com/comment/91070481
answers question: http://stackoverflow.com/q/52059186
score: 4
upvote count: 4
downvote count: 0
has comment: http://stackoverflow.com/comment/91071327

http://stackoverflow.com/q/52104875
has answer: http://stackoverflow.com/a/52107852
answer count: 2
downvote count: 0
favorite count: 0
tagged with: python
accepted answer: http://stackoverflow.com/a/52111167
type: AnsweredQuestion
score: 2
has title: How check if website support http, htts and www prefix with scrapy
has comment: http://stackoverflow.com/comment/91161190
upvote count: 2
tagged with: scrapy
has body: I am using scrapy to check, if some website works fine, when I use http://example.com, https://example.com or http://www.example.com. When I create scrapy request, it works fine. for example, on my page1.com, it is always redirected to https://. I need to get this information as return value, or is there better way how to get this information using scrapy? class myspider(scrapy.Spider): name = 'superspider' start_urls = [ "https://page1.com/" ] def start_requests(self): for url in self.start_urls: yield scrapy.Request(url=url, callback=self.parse) def parse(self, response): url = response.url # removing all possible prefixes from url for remove in ['https://', 'http://', 'www.']: url = str(url).replace(remove, '').rstrip('/') # Try with all possible prefixes for prefix in ['http://', 'http://www.', 'https://', 'https://www.']: yield scrapy.Request(url='{}{}'.format(prefix, url), callback=self.test, dont_filter=True) def test(self, response): print(response.url, response.status) The output of this spider is this: https://page1.com 200 https://page1.com/ 200 https://page1.com/ 200 https://page1.com/ 200 This is nice, but I would like to get this information as return value to know, that e.g. on http is response code 200 and than save it to dictionary for later processing or save it as json to file(using items in scrapy). DESIRED OUTPUT: I would like to have dictionary named a with all information: print(a) {'https://': True, 'http://': True, 'https://www.': True, 'http://www.': True} Later I would like to scrape more information, so I will need to store all information under one object/json/...
has comment: http://stackoverflow.com/comment/91161026
type: Question
possible better answer: http://stackoverflow.com/a/52107852
has answer: http://stackoverflow.com/a/52111167

http://stackoverflow.com/comment/91000944
comment on: http://stackoverflow.com/a/52020683
score: 0
type: AnswerComment
type: Comment
has text: yes. it's like navigating in the explorer - if i send you to directory B and ask you if you see a file that is actually in directory A, you'll of course reply "no" (cause it's not there). however, i personally recommend working with absolute paths, as all that directory switching usually gives me headaches.

http://stackoverflow.com/a/52055009
upvote count: 1
has body: I found the error after all myself. The problem was that there is an instance on SQL server I am using. Though in freetds.conf there is the instance port mentioned, I also had to add it to the create_engine call. The working version of create_engine is so: engine = create_engine(r"mssql+pymssql://{0}:{1}@dbserver:12345/db_database?charset=utf8".format('user','p@ssw0rd')) where 12345 is the port number the instance is listening to. I am sorry that missed that one crucial information bit, but then again, if I had realized it, I probably wouldn't have even asked - and then somebody else might later fight with the same problem. hank
answers question: http://stackoverflow.com/q/52052536
has comment: http://stackoverflow.com/comment/91060228
downvote count: 0
type: Answer
score: 1

http://stackoverflow.com/comment/90893564
type: QuestionComment
comment on: http://stackoverflow.com/q/51971493
has text: Docs say "Refer to the C API for documentation". PyQt5 does something like that too. Means that the signature of the bindings is identical to the c functions under the hood.
score: 0
type: Comment

http://stackoverflow.com/a/51979914
score: 0
has comment: http://stackoverflow.com/comment/90931049
type: Answer
has body: Solving the original case &gt;&gt;&gt; import re &gt;&gt;&gt; links = ''' &lt;img style="width:100%" id="box_img1" alt="box1" src="https://smtgvs.weathernews.jp/s/topics/img/dummy.png" class="lazy" data-original="https://smtgvs.weathernews.jp/s/topics/img/201807/201807240125_box_img1_A.jpg?1534992203"&gt; &lt;img id="top_img" alt="top" style="width: 100%;" src="//smtgvs.cdn.weathernews.jp/s/topics/img/201808/201808010125_top_img_A.jpg?1534994171"&gt; &lt;img style="width:100%" id="box_img1" alt="box1" src="https://smtgvs.weathernews.jp/s/topics/img/dummy.png" class="lazy" data-original="https://smtgvs.weathernews.jp/s/topics/img/201808/201808220125_box_img1_A.jpg?1534992203"&gt; ''' &gt;&gt;&gt; re.findall("(https://smtgvs.weathernews.jp/s/topics/img/[0-9]+/.+)\?[0-9]+",links) ['https://smtgvs.weathernews.jp/s/topics/img/201807/201807240125_box_img1_A.jpg', 'https://smtgvs.weathernews.jp/s/topics/img/201808/201808220125_box_img1_A.jpg'] New case: to parse between 20180801 and 20180831 Two big changes: /. to \. to escape dot character Matches YYYYMM expressions matched by 201808 So, the new code: &gt;&gt;&gt; links = ''' &lt;img style="width:100%" id="box_img1" alt="box1" src="https://smtgvs.weathernews.jp/s/topics/img/dummy.png" class="lazy" data-original="https://smtgvs.weathernews.jp/s/topics/img/201807/201807240125_box_img1_A.jpg?1534992203"&gt; &lt;img id="top_img" alt="top" style="width: 100%;" src="//smtgvs.cdn.weathernews.jp/s/topics/img/201808/201808010125_top_img_A.jpg?1534994171"&gt; &lt;img style="width:100%" id="box_img1" alt="box1" src="https://smtgvs.weathernews.jp/s/topics/img/dummy.png" class="lazy" data-original="https://smtgvs.weathernews.jp/s/topics/img/201808/201808220125_box_img1_A.jpg?1534992203"&gt; ''' &gt;&gt;&gt; re.findall("([htps:]*?\/\/[^:\/\s]+[^#?\s]+\/s\/topics\/img\/201808\/[0-9a-zA-z]+\.+\w+)\?[0-9]+",links) ['//smtgvs.cdn.weathernews.jp/s/topics/img/201808/201808010125_top_img_A.jpg', 'https://smtgvs.weathernews.jp/s/topics/img/201…
has comment: http://stackoverflow.com/comment/90910206
answers question: http://stackoverflow.com/q/51978412

http://stackoverflow.com/a/52052615
answers question: http://stackoverflow.com/q/52038375
score: 0
type: Answer
has comment: http://stackoverflow.com/comment/91056127
has body: Change your code from: bViewResult = QtWidgets.QPushButton('View Results', self) bViewResult.clicked.connect(self.openCSV) to: bViewResult = QtWidgets.QPushButton('View Results', self) bViewResult.clicked.connect(cargar_configuracion())

http://stackoverflow.com/a/51976284
accepted answer of: http://stackoverflow.com/q/51976145
type: Answer
score: 1
has body: You may want to convert the numbers to strings before doing anything else, so I assume that col1 and col2 are strings. First, find the combined string lengths and how many zeros are missing: pads = 13 - (df.col1.str.len() + df.col2.str.len()) Then generate the necessary paddings and concatenate the columns and the paddings: df['var3'] = df.col1 + pads.apply(lambda x: x * '0') + df.col2 #0 1234561234567 #1 2000000000004 #2 12345671234567
upvote count: 1
answers question: http://stackoverflow.com/q/51976145
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/a/52080885
score: 9
has comment: http://stackoverflow.com/comment/91113498
upvote count: 9
accepted answer of: http://stackoverflow.com/q/52080799
has body: One solution df.groupby(['f']*df.shape[1], axis=1).first() Out[385]: f 0 2.0 1 5.0 2 13.0 3 14.0 The orther df.bfill(1)['a'] Out[388]: 0 2.0 1 5.0 2 13.0 3 14.0 Name: a, dtype: float64
answers question: http://stackoverflow.com/q/52080799
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/91112639
type: Answer

http://stackoverflow.com/q/51985975
tagged with: loops
type: Question
has answer: http://stackoverflow.com/a/51986240
has comment: http://stackoverflow.com/comment/90921763
tagged with: arrays
score: 0
tagged with: sql
answer count: 1
has comment: http://stackoverflow.com/comment/90921674
has comment: http://stackoverflow.com/comment/90921495
has comment: http://stackoverflow.com/comment/90921519
accepted answer: http://stackoverflow.com/a/51986240
has title: Python Array Becoming Index Out of Range for the second turn in the loop
tagged with: python
has body: row_norm_hours[col] = row_calculation[0][col] IndexError: list index out of range This happens when index = 1 (2nd turn in the loop) where col = 0, yet I declare the array/list as new. for index in range(num_rows): #where num_rows is a constant ... sql_calcultion = "SELECT MonH,TueH,WedH,ThuH,FriH,SatH,SunH,MonOH,TueOH,WedOH,ThuOH,FriOH,SatOH,SunOH FROM Calculation WHERE EmployeeID=" + str(row_employee[index][0]) #EmployeeID cursor.execute(sql_calcultion) row_calculation = cursor.fetchall() #one row only row_norm_hours = {} row_ot_hours = {} for col in range(7): row_norm_hours[col] = row_calculation[0][col] row_ot_hours[col] = row_calculation[0][col+7] Any ideas? Thanks UPDATE: I made a mistake with query, the EmployeeID exists without proper row for Calculation table. Which resulted in the row_calculation as being null. Hence row_calculation[0][col] for any value of col is an index out of range
type: AnsweredQuestion

http://stackoverflow.com/comment/91195010
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/52106864
type: Comment
has text: Sorry, this is the error I get: return vmin * np.ma.power((vmax / vmin), val) ZeroDivisionError: float division by zero. raise ValueError("values must all be positive")

http://stackoverflow.com/comment/90977041
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52012942
type: AnswerComment
has text: Thanks for the answer, I have another question here, when notifynonempty and notifynonfull is using same underlying lock object. would it be a deadlock if we call pop() when it's empty, then another thread call append()?

http://stackoverflow.com/comment/91059659
type: QuestionComment
comment on: http://stackoverflow.com/q/52054446
score: 0
type: Comment
has text: Oh its working now what ?

http://stackoverflow.com/comment/90999024
score: 0
type: Comment
type: QuestionComment
has text: If you're using packages that still require Python2, you should consider finding alternatives. At the very least, copy those entirely or run `2to3` on them
comment on: http://stackoverflow.com/q/52024351

http://stackoverflow.com/q/52061739
tagged with: nlp
type: AnsweredQuestion
tagged with: spacy
has title: Spacy download en not working in virtualenv
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/91073969
type: Question
accepted answer: http://stackoverflow.com/a/52095638
has answer: http://stackoverflow.com/a/52095638
downvote count: 0
answer count: 1
tagged with: virtualenv
favorite count: 0
tagged with: python-3.x
has body: I'm new to python and virtualenv. I have pip installed and have installed a virtualenv, through which I have downloaded the python NLP library spacy. Now I am having an issue downloading a language library (en). The command I run is: $ python3 -m spacy download en and the error I get is: Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/runpy.py", line 183, in _run_module_as_main mod_name, mod_spec, code = _get_module_details(mod_name, _Error) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/runpy.py", line 142, in _get_module_details return _get_module_details(pkg_main_name, error) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/runpy.py", line 109, in _get_module_details __import__(pkg_name) File "/Users/JoshiMac/Documents/pythonprojects/LangEnv/lib/python3.6/site-packages/spacy/__init__.py", line 4, in &lt;module&gt; from .cli.info import info as cli_info File "/Users/JoshiMac/Documents/pythonprojects/LangEnv/lib/python3.6/site-packages/spacy/cli/__init__.py", line 1, in &lt;module&gt; from .download import download File "/Users/JoshiMac/Documents/pythonprojects/LangEnv/lib/python3.6/site-packages/spacy/cli/download.py", line 11, in &lt;module&gt; from .link import link File "/Users/JoshiMac/Documents/pythonprojects/LangEnv/lib/python3.6/site-packages/spacy/cli/link.py", line 9, in &lt;module&gt; from ..util import prints File "/Users/JoshiMac/Documents/pythonprojects/LangEnv/lib/python3.6/site-packages/spacy/util.py", line 8, in &lt;module&gt; import regex as re File "/Users/JoshiMac/Documents/pythonprojects/LangEnv/lib/python3.6/site-packages/regex.py", line 683, in &lt;module&gt; _pattern_type = type(_compile("", 0, {})) File "/Users/JoshiMac/Documents/pythonprojects/LangEnv/lib/python3.6/site-packages/regex.py", line 436, in _compile pattern_locale = _getlocale()[1] File "/Users/JoshiMac/Documents/pythonprojects/LangEnv/lib/python3.6/locale.py", line 581, in getl…
has comment: http://stackoverflow.com/comment/91114899
tagged with: python

http://stackoverflow.com/q/52012126
has answer: http://stackoverflow.com/a/52012456
tagged with: python
has body: This is part of my list of list. My original list have more than 30 items: a = [[[1, 2, 3, 4, 5, 6, 7, 8, 9], [0.4, 3]], [[1, 2, 3, 4, 5, 6, 7, 8, 9], [1.8, 1]]] I need to compare all items of my a. I mean, if the first 9 items of my first item are equals to the first 9 items of the other item, "1, 2, 3, 4, 5, 6, 7, 8, 9"compare the item[1] of last item. I call item2 as the others items of a list lista = [] for item in a: print item &gt;&gt;&gt; [[1, 2, 3, 4, 5, 6, 7, 8, 9], [0.4, 3]] &gt;&gt;&gt; [[1, 2, 3, 4, 5, 6, 7, 8, 9], [1.8, 1]] if item[:1] == item2[:1]: if item[9][1] &lt;= item2[9][1]: lista.append(item) if item[9][1] &gt; item2[9][1]: lista.append(item2) print lista &gt;&gt;&gt; [[1, 2, 3, 4, 5, 6, 7, 8, 9, [1.8, 1]]
tagged with: list
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90975355
has comment: http://stackoverflow.com/comment/90975248
has answer: http://stackoverflow.com/a/52012341
type: Question
score: 0
has answer: http://stackoverflow.com/a/52020563
has title: Compare all elements of a list of list Python
upvote count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/90975364
favorite count: 0
has comment: http://stackoverflow.com/comment/90975719
answer count: 3

http://stackoverflow.com/comment/91102921
type: AnswerComment
score: 0
has text: you are right the script is in bigger html,so this script is in 124 th in html page so how to i select the 124th position script and pass the patten?
type: Comment
comment on: http://stackoverflow.com/a/52075867

http://stackoverflow.com/comment/91050776
has text: Possible duplicate of [Need to Pretty-Print JSON Data to a File using Python](https://stackoverflow.com/questions/9170288/need-to-pretty-print-json-data-to-a-file-using-python)
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/52050108

http://stackoverflow.com/a/56302957
answers question: http://stackoverflow.com/q/52016336
score: 20
has body: Can get that error for following reasons: Didn't change your version in setup.py didn't remove your previous dist file Solution: Change the version number in setup.py. Run setup file again. python setup.py bdist_wheel. Upload only that dist file or run twine (if using). twine upload --skip-existing dist/* As mentioned by @dustin, dist file of same name cannot be uploaded again.
upvote count: 22
downvote count: 2
type: Answer

http://stackoverflow.com/comment/91016510
has text: @riyasyash Without brackets (`[` and `]`) would work too, that will be faster
score: 0
comment on: http://stackoverflow.com/q/52033056
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51994094
has answer: http://stackoverflow.com/a/51994309
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90938132
tagged with: ironpython
has comment: http://stackoverflow.com/comment/90937931
type: Question
tagged with: c#
answer count: 2
has comment: http://stackoverflow.com/comment/90938152
tagged with: .net
upvote count: 16
has comment: http://stackoverflow.com/comment/90938155
has body: Am trying to integrate python code in my .net core application for data analysis and some machine learning classification. How can I do this the best way? Note: I don't want to execute scripts with IronPython. I already tried that before.
score: 15
tagged with: python.net
downvote count: 1
has title: How to integrate Python Code with C#.Net Core language?
possible better answer: http://stackoverflow.com/a/51994309
favorite count: 0
has answer: http://stackoverflow.com/a/51994214
accepted answer: http://stackoverflow.com/a/51994214
tagged with: python
has comment: http://stackoverflow.com/comment/95900574

http://stackoverflow.com/comment/90972031
comment on: http://stackoverflow.com/q/52010024
has text: Are you open to using numpy?
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/a/66781752
type: Answer
has body: I think you should use a file with PKL extension then it gonna work train_data = pickle.load(open('train_data.pkl','rb'))
downvote count: 1
upvote count: 0
answers question: http://stackoverflow.com/q/51963362
score: -1

http://stackoverflow.com/comment/90987974
type: Comment
has text: 1) I'm concerned by how much pure C code is relied on in things like `opencv`, `PIL`. OpenCV uses pretty much purely C bindings. PIL has some C. 2) Grokking this is very difficult: https://github.com/python-pillow/Pillow/blob/fdbd719da4c77c7e23e2e9e9b71d0d177f2d3369/src/PIL/ImageFile.py#L130
score: 0
comment on: http://stackoverflow.com/q/52018680
type: QuestionComment

http://stackoverflow.com/comment/90883241
comment on: http://stackoverflow.com/q/51966650
has text: Your indentation doesn't make sense. Does your code actually look like this, or are you uncertain how to paste code in Stack Overflow?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/52112209
score: 0
has comment: http://stackoverflow.com/comment/91194063
answers question: http://stackoverflow.com/q/52102257
type: Answer
has body: To extract the links, first you have to make sure that the urls to the links exists in the page source. For this you can search with any of the listing ids in the page source(ctrl+u if you are using google chrome,mozilla firefox). If the urls exist in the page source you can directly scrape them using xpath in the response text of the listing page. Here the above listing page of Airbnb is not having the links in the page source, so the page might be sending requests to some other pages(usually json requests). You can find out those requests and send requests to those pages and get the required data. Please comment if you have any doubt regarding this.
has comment: http://stackoverflow.com/comment/91194105

http://stackoverflow.com/q/51992019
accepted answer: http://stackoverflow.com/a/51993508
has comment: http://stackoverflow.com/comment/90933699
downvote count: 2
type: Question
has answer: http://stackoverflow.com/a/51993508
score: -2
has comment: http://stackoverflow.com/comment/90936412
has body: If anyone has time to take a look at this issue. What´s the best way to increase the processing speed of this function? It gets very slow if it has to deal with more than 50 000 values.Thank you. Data is a 2d numpy array. def mean_error(data): sub=[] for i in range(len(data)): soma=abs(data[i][0]-data[i][1]) sub.append(soma) mean_error=np.sum(sub)/len(sub) return mean_error
has title: What´s the best solution to improve the speed of a python loop that iterates over a numpy array?
tagged with: numpy
has comment: http://stackoverflow.com/comment/90934522
upvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/90937043
favorite count: 0
has comment: http://stackoverflow.com/comment/90936519
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/a/66820079
upvote count: 2
answers question: http://stackoverflow.com/q/52043027
type: Answer
has body: Using the example from Anthon as well as an issue in ruamel.yaml on sourceforge, here's a set of methods which should allow you to retrieve (almost - see below) all the comments in your documents: from ruamel.yaml import YAML from ruamel.yaml.comments import CommentedMap, CommentedSeq # set attributes def get_comments_map(self, key): coms = [] comments = self.ca.items.get(key) if comments is None: return coms for token in comments: if token is None: continue elif isinstance(token, list): coms.extend(token) else: coms.append(token) return coms def get_comments_seq(self, idx): coms = [] comments = self.ca.items.get(idx) if comments is None: return coms for token in comments: if token is None: continue elif isinstance(token, list): coms.extend(token) else: coms.append(token) return coms setattr(CommentedMap, 'get_comments', get_comments_map) setattr(CommentedSeq, 'get_comments', get_comments_seq) # load string yaml_str = &quot;&quot;&quot;\ - name: gather all complex custom facts using the custom module hosts: switches gather_facts: False connection: local tasks: # There is a bug in ansible 2.4.1 which prevents it loading # playbook/group_vars - name: ensure we're running a known working version assert: that: - 'ansible_version.major == 2' - 'ansible_version.minor == 4' &quot;&quot;&quot; yml = YAML(typ='rt') data = yml.load(yaml_str) def walk_data(data): if isinstance(data, CommentedMap): for k, v in data.items(): print(k, [ comment.value for comment in data.get_comments(k)]) if isinstance(v, CommentedMap) or isinstance(v, CommentedSeq): walk_data(v) elif isinstance(data, CommentedSeq): for idx, item in enumerate(data): print(idx, [ comment.value for comment in data.get_comments(idx)]) if isinstance(item, CommentedMap) or isinstance(item, CommentedSeq): walk_data(item) walk_data(data) Here's the output: 0 [] name [] hosts [] gather_facts [] connection [] tasks ['# There is a bug in ansible 2.4.1 which prevents it loading\n', '# playbook/group_vars\n'] 0 [] name [] ass…
score: 2
downvote count: 0

supervised-learning
type: Tag
tag name: supervised-learning
tags question: http://stackoverflow.com/q/52072821

http://stackoverflow.com/q/52098465
has comment: http://stackoverflow.com/comment/91153594
has comment: http://stackoverflow.com/comment/91147599
accepted answer: http://stackoverflow.com/a/52098830
has body: If I have a 1d array a and want to map a function f over each element, I could do &gt;&gt;&gt; import numpy as np &gt;&gt;&gt; a = np.arange(5) &gt;&gt;&gt; def f(x): ... return 3*x + x**2 #whatever &gt;&gt;&gt; np.fromiter(map(f,a),float) array([ 0., 4., 10., 18., 28.]) I'd like to do something analogous with more complex arrays. One example calculation is this: compose paired 3x3 arrays with matrix multiplication &gt;&gt;&gt; a = np.arange(5*2*3**2).reshape(5,2,3,3) &gt;&gt;&gt; def f(x): ... return np.matmul(x[0],x[1]) # is there a smarter way? &gt;&gt;&gt; np.array([f(x) for x in a]) array([[[ 42, 45, 48], [ 150, 162, 174], [ 258, 279, 300]], [[ 1716, 1773, 1830], [ 1986, 2052, 2118], [ 2256, 2331, 2406]], [[ 5334, 5445, 5556], [ 5766, 5886, 6006], [ 6198, 6327, 6456]], [[10896, 11061, 11226], [11490, 11664, 11838], [12084, 12267, 12450]], [[18402, 18621, 18840], [19158, 19386, 19614], [19914, 20151, 20388]]]) Another example calculation would be transform every vector in an array of vectors by matrix multiplication &gt;&gt;&gt; a = np.arange(3*5).reshape(5,3) &gt;&gt;&gt; def f(x): ... M = np.arange(3*3).reshape(3,3) ... return np.dot(M,x) &gt;&gt;&gt; np.array([f(x) for x in a]) array([[ 5, 14, 23], [ 14, 50, 86], [ 23, 86, 149], [ 32, 122, 212], [ 41, 158, 275]]) Is there a nice way to do such computations with an np.fromiter like approach? What is the most pythonic way to do these operations with numpy? Is there an approach which handles every example problem here as np.specialnumpything(map(f,a))?
tagged with: python
has comment: http://stackoverflow.com/comment/91147962
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91147786
has answer: http://stackoverflow.com/a/52098830
has comment: http://stackoverflow.com/comment/91147452
has title: mapping over higher dimensional numpy arrays
has comment: http://stackoverflow.com/comment/91153401
type: Question
tagged with: numpy
has answer: http://stackoverflow.com/a/52098703
score: 0
answer count: 2
possible better answer: http://stackoverflow.com/a/52098703

http://stackoverflow.com/q/52077043
downvote count: 1
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91107783
has comment: http://stackoverflow.com/comment/91107403
has comment: http://stackoverflow.com/comment/91106893
has comment: http://stackoverflow.com/comment/91112282
has comment: http://stackoverflow.com/comment/91108007
answer count: 0
tagged with: forex
has comment: http://stackoverflow.com/comment/91117573
favorite count: 0
has comment: http://stackoverflow.com/comment/91107770
has comment: http://stackoverflow.com/comment/91108472
type: Question
tagged with: pandas
has comment: http://stackoverflow.com/comment/91107554
has comment: http://stackoverflow.com/comment/91108496
tagged with: python
has body: I was trying to convert tick data from GainCapital to OHLCs in Python but I have come up with problems The source data link is here http://ratedata.gaincapital.com/ I have input my code as follows: import pandas as pd import matplotlib.pyplot as plt import numpy as np import mpl_finance from datetime import * def conv_str_to_datetime(x): return(datetime.strptime(x, '%Y/%m/%d %H:%M:%S')) df = pd.read_csv('USD_JPY_Week3.csv', names=['lTid', 'cDealable', 'CurrencyPair', 'RateDateTime','RateBid','RateAsk'], converters={'RateDateTime': conv_str_to_datetime}) # or change 'converters' to 'parse_dates=True' here grouped = df.groupby('CurrencyPair') ask = grouped['RateAsk'].resample('15Min').ohlc() bid = grouped['RateBid'].resample('15Min').ohlc() pandas.concat([ask, bid], axis=1, keys=['RateAsk', 'RateBid']) When I use converters, I get: ValueError: time data 'RateDateTime' does not match format '%Y/%m/%d %H:%M:%S' When I replace it with parse_dates=True, Python returns: TypeError: Only valid with DatetimeIndex, TimedeltaIndex or PeriodIndex, but got an instance of 'RangeIndex' I am completely baffled by this and would appreciate greatly if someone can help me make my code work. enter image description here Please note in the screenshot I highlighted in red circles the differences between the display of the datetime of the same cell, it may be one of the reasons to this, but I am not sure The first 10 lines of the file are here: lTid cDealable CurrencyPair RateDateTime RateBid RateAsk 6858533811 D USD/JPY 00:06.4 110.585 110.605 6858534097 D USD/JPY 03:10.1 110.584 110.604 6858534127 D USD/JPY 03:30.1 110.583 110.603 6858534151 D USD/JPY 04:11.6 110.58 110.593 6858534284 D USD/JPY 05:15.4 110.58 110.591 6858534287 D USD/JPY 05:15.6 110.58 110.59 6858534316 D USD/JPY 05:30.1 110.58 110.591 6858534335 D USD/JPY 05:34.9 110.565 110.585 6858534342 D USD/JPY 05:35.1 110.565 110.58
has comment: http://stackoverflow.com/comment/91116023
has title: Python, converting tick data to OHLCs
has comment: http://stackoverflow.com/comment/91107310
has comment: http://stackoverflow.com/comment/91106757
has comment: http://stackoverflow.com/comment/91107137
score: 0
upvote count: 1

http://stackoverflow.com/comment/91038167
has text: What's going on in EndDistance?
comment on: http://stackoverflow.com/q/52042806
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91093368
type: Comment
has text: I think the only place where we can improve the efficiency is on the image pre-processing. That is to provide only the necessary data to the tesseract OCR. Can you give one image and I'll try it on my machine to see the optimal adjustments.
type: QuestionComment
comment on: http://stackoverflow.com/q/52070514
score: 0

http://stackoverflow.com/comment/90869196
comment on: http://stackoverflow.com/a/51959350
type: Comment
has text: Can you try adding `uselist=False` in the `db.relationship of class Dish`
score: 0
type: AnswerComment

http://stackoverflow.com/comment/91721778
type: Comment
comment on: http://stackoverflow.com/q/52107447
has text: Why this line `form.PASSWORD.value = JSON.stringify(info);`?
score: 0
type: QuestionComment

http://stackoverflow.com/q/51991306
has title: Accessing Binned Data with pandas
type: AnsweredQuestion
type: Question
has comment: http://stackoverflow.com/comment/90932419
has answer: http://stackoverflow.com/a/51991985
score: 0
tagged with: pandas
answer count: 1
has body: I have a set of data for which i have put into a data frame and then binned: print(data1) [[-1.90658883e+00 5.66881290e-01 1.45443907e+00] [-1.82926850e+00 2.53325112e-01 1.45480072e+00] [-1.59073925e+00 5.33264011e-01 1.45461954e+00] ... [ 2.86246982e+02 4.52961148e-01 6.19121328e+00]] df = pd.DataFrame(data=data1,) print(df) bins = [0,50,100,150,200,250,300,400] df1 = pd.cut(df[0],bins, labels = False) print(df1) 1 0 2 0 .. 500 4 501 4 502 5 0 through 5 are the bin labels. I want to be able to access the data in each bin/category and store it in a variable. Something like this: x = df1(4) # this doesnt work, just an example. ^ meaning I want to access the data stored in the 4th bin in the pandas dataframe and assign it to the variable x as an array, but I am unsure how to do that.
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/51991985
has comment: http://stackoverflow.com/comment/90933251
tagged with: python
has comment: http://stackoverflow.com/comment/90932663
has comment: http://stackoverflow.com/comment/90934187

http://stackoverflow.com/a/51993342
type: Answer
has body: I would recommend packaging your lists in a dictionary and evaluating in the manner below: games_1 = ['Tennis', 'Football', 'Basketball'] games_2 = ['Cricket', 'Football', 'Lacrosse'] games_3 = ['Golf','Baseball', 'Rugby', 'Track'] games_N = {'games_1': games_1, 'games_2': games_2, 'games_3': games_3} var_game = 'Football' games_N_check = {key: 1 if var_game in val else 0 for key, val in games_N.items()} Outputs: {'games_1': 1, 'games_2': 1, 'games_3': 0} Additionally A quick means to create your dictionary from a series of lists, so that you do not have to explicitly name every list: games_lists = [['Tennis', 'Football', 'Basketball'],['Cricket', 'Football', 'Lacrosse'],['Golf','Baseball', 'Rugby', 'Track']] games_N = {'games_{}'.format(idx+1): game_list for idx, game_list in enumerate(games_lists)} Gives: {'games_1': ['Tennis', 'Football', 'Basketball'], 'games_2': ['Cricket', 'Football', 'Lacrosse'], 'games_3': ['Golf', 'Baseball', 'Rugby', 'Track']}
score: 3
upvote count: 3
downvote count: 0
answers question: http://stackoverflow.com/q/51993243
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/51993243
has comment: http://stackoverflow.com/comment/90936607

http://stackoverflow.com/q/52014262
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52029009
has answer: http://stackoverflow.com/a/52014607
has comment: http://stackoverflow.com/comment/90979004
type: Question
possible better answer: http://stackoverflow.com/a/52014421
has comment: http://stackoverflow.com/comment/90979040
has comment: http://stackoverflow.com/comment/91013955
score: 0
has title: Towers of Hanoi with Python, print each step by using list. but i don't want to use global variable
answer count: 3
has body: code explanation : input n is integer, other inputs are list(decreasing order). E.g., n=3, A=list(range(n,0,-1)), B=[], C=[] (larger integer represent larger disc). The fllowing code works, but input list variables (start_, inter_, end_) names must be A, B, C because Hanoi function includes global variable A, B, C. It's an annoying thing. How can I represent each step with list without a global variable? In other word, How can operations (append, remove) of base case depend on input position not variable name. For example: start_ is second input variable, end_ is fourth input variable. base case operation -> fourth input variable.append(second input variable[-1], second input variable.remove(second input variable[-1]) def Hanoi(n,start_,inter_,end_): if n==1: end_.append(start_[-1]) start_.remove(start_[-1]) print('start_peg , inter_peg, end_peg :{}\t{}\t{}'.format(A,B,C)) else: Hanoi(n-1,start_,end_,inter_) Hanoi(1,start_,inter_,end_) Hanoi(n-1,inter_,start_,end_) n=3 A=list(range(n,0,-1)) B,C=[],[] Hanoi(n,A,B,C) #variable name of three list input must be A,B,C Out: start_peg , inter_peg, end_peg :[3, 2] [] [1] start_peg , inter_peg, end_peg :[3] [2] [1] start_peg , inter_peg, end_peg :[3] [2, 1] [] start_peg , inter_peg, end_peg :[] [2, 1] [3] start_peg , inter_peg, end_peg :[1] [2] [3] start_peg , inter_peg, end_peg :[1] [] [3, 2] start_peg , inter_peg, end_peg :[] [] [3, 2, 1] ---- (start_,inter_,end_ )instead of (A,B,C) in fifth line ---- def Hanoi(n,start_,inter_,end_): if n==1: end_.append(start_[-1]) start_.remove(start_[-1]) print('start_peg , inter_peg, end_peg :{}\t{}\t{}'.format(start_,inter_,end_)) else: Hanoi(n-1,start_,end_,inter_) Hanoi(1,start_,inter_,end_) Hanoi(n-1,inter_,start_,end_) # it's possible to use any input variable name n=3 a=list(range(n,0,-1)) b,c=[],[] Hanoi(n,a,b,c) Out: start_peg , inter_peg, end_peg :[3, 2] [] [1] start_peg , inter_peg, end_peg :[3] [1] [2] start_peg , inter_peg, end_peg :[] [3] [2, 1] start_peg , inter_peg, end_…
tagged with: python-3.x
has answer: http://stackoverflow.com/a/52014421
accepted answer: http://stackoverflow.com/a/52029009

http://stackoverflow.com/comment/90911934
score: 1
comment on: http://stackoverflow.com/q/51981068
has text: How will you know that 3 belongs to a, 2 to b and 4 to c?
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/90867961
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51958310
has text: This seems to be the repr of a list. Try printing each item of the list instead, it'll probably look normal.
score: 0

http://stackoverflow.com/a/52027146
answers question: http://stackoverflow.com/q/52026877
type: AcceptedAnswer
downvote count: 0
type: Answer
score: 1
has body: You can split the tensor at the first axis, add one to the first tensors in the first axis and then stack the new and old tensors using tf.stack: &gt;&gt;&gt; x = tf.constant([[[1, 2], [3, 4]],[[5, 6], [7, 8]]]) &gt;&gt;&gt; with tf.Session() as sess: ... sess.run(tf.stack((x[:,0] + 1, x[:, 1]), axis=1)) ... array([[[2, 3], [3, 4]], [[6, 7], [7, 8]]], dtype=int32)
accepted answer of: http://stackoverflow.com/q/52026877
upvote count: 1

http://stackoverflow.com/comment/91150833
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52099985
score: 1
has text: Brackets `[]` are for character sets. `[6|7|8|9|10|11|12]` boils down to characters `0126889|`.

http://stackoverflow.com/comment/91335750
type: Comment
score: 0
comment on: http://stackoverflow.com/a/52100502
has text: Thank you that worked. The last line of the code is: arcpy.CalculateField_management(fc, "DOY", dtm.timetuple().tm_yday) which is supposed to take the dtm and calculate the day of the year from it and add it to a field called "DOY". However, when I try this I get an error message that reads "AttributeError: 'str' object has no attribute 'timetuple' " so does that mean I need to do a strptime function on a new line after the strftime one to get the object back into a datetime format? And if so what would that look like?
type: AnswerComment

http://stackoverflow.com/comment/91080166
type: Comment
type: QuestionComment
has text: @Scott, not whether `ModSpec` is a function, whether the thing `ModSpec` is describing is a function. But that's still a useful reference link for the question.
comment on: http://stackoverflow.com/q/52064613
score: 0

http://stackoverflow.com/q/52106557
has body: Is it possible to make a module callable with parameters? I am trying to make a callable module on Python, following the question and its answers Callable modules, like so: foo.py import sys class foo(object): def __call__(self): return 'callable' sys.modules[__name__] = foo() then I call it: import foo print(foo()) # 'callable' but my objective is to pass a parameter in the callable module: print(foo('parameter')) Any ideas how can I accomplish that?
upvote count: 1
answer count: 1
has comment: http://stackoverflow.com/comment/91164313
has comment: http://stackoverflow.com/comment/91164223
has comment: http://stackoverflow.com/comment/91164105
has answer: http://stackoverflow.com/a/52106763
has comment: http://stackoverflow.com/comment/91164063
has comment: http://stackoverflow.com/comment/91164293
has comment: http://stackoverflow.com/comment/91164109
has title: Callable modules with parameters
accepted answer: http://stackoverflow.com/a/52106763
linked to: http://stackoverflow.com/q/1060796
downvote count: 0
type: AnsweredQuestion
tagged with: python
score: 1
tagged with: module
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/91164355

http://stackoverflow.com/comment/90910715
type: Comment
type: QuestionComment
has text: @Xnkr you're right, thanks.
comment on: http://stackoverflow.com/q/51980447
score: 0

http://stackoverflow.com/comment/91054454
comment on: http://stackoverflow.com/q/52047937
has text: I don't understand what you mean. You have a try; you don't show the except but I guess you are just blindly catching every exception. So doing that and let Python tell you what is wrong.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52051338
type: UnansweredQuestion
has body: I am trying to convert the cloud-init logs to json, so that the filebeat can pick it up and send it to the Kibana. I want to do this by using a shell script or python script. Is there any script that converts such logs to json? My python script is below import json import subprocess filename = "/home/umesh/Downloads/scripts/cloud-init.log" def convert_to_json_log(line): """ convert each line to json format """ log = {} log['msg'] = line log['logger-name'] = 'cloud-init' log['ServiceName'] = 'Contentprocessing' return json.dumps(log) def log_as_json(filename): f = subprocess.Popen(['cat','-F',filename], stdout=subprocess.PIPE,stderr=subprocess.PIPE) while True: line = f.stdout.readline() log = convert_to_json_log(line) print log with open("/home/umesh/Downloads/outputs/cloud-init-json.log", 'a') as new: new.write(log + '\n') log_as_json(filename) The scripts returns a file with json format, but the msg filed returns empty string. I want to convert each line of the log as message string.
has title: Converting cloud-init logs to json using a script
upvote count: 1
type: Question
score: 1
tagged with: http://stackoverflow.com/tag/json
answer count: 2
has answer: http://stackoverflow.com/a/52108643
downvote count: 0
has comment: http://stackoverflow.com/comment/91052914
favorite count: 0
tagged with: bash
has answer: http://stackoverflow.com/a/52111939
tagged with: python
tagged with: python-3.x

http://stackoverflow.com/q/51958728
has body: Is there a simple way of adding captions to images in Jupyter notebooks? I haven't figured out how to do this just yet and was hoping that somebody could give me some direction. So far in my searches I've come across two sources. I wasn't able to get the first, Source 1, to work. When I try out that route I don't see a displayed image, but rather the latex code within a closed box like so: Snapshot image The other reference that I've come across is Source 2. This has a description under the "Figures" section which describes how you can insert a caption by editing a cell's metadata. In my version of Jupyter however(version 4.4.0), I don't see any tool bars that would allow me to edit the metadata of an individual cell. Without this capability I'm not sure how to follow the instructions of the given post. Does anybody have any ideas where I'm going wrong or does anyone know of a simple way to add image captions within Jupyter notebooks? Any help would be very much appreciated!
has title: Jupyter Notebook Image Captions
upvote count: 9
linked to: http://stackoverflow.com/q/32855828
has comment: http://stackoverflow.com/comment/107693074
score: 9
type: Question
answer count: 1
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/72153722
tagged with: python
tagged with: jupyter-notebook
type: UnansweredQuestion

http://stackoverflow.com/q/52035474
has answer: http://stackoverflow.com/a/52035784
has title: Using database objects in base.html
type: AnsweredQuestion
score: 1
upvote count: 1
type: Question
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/91021194
accepted answer: http://stackoverflow.com/a/52035784
favorite count: 0
has body: When I have full set of model+view+url+template then it goes fine, but I want to try a top menu with my products' categories without specific given url. I want it to be in menu child template(?) whose parent is base.html. (I want it to be global within my website, yes) here are my codes: models.py class Category(models.Model): parent = models.ForeignKey('self', null=True, blank=True, on_delete=models.CASCADE) name = models.CharField(max_length=100) def __str__(self): return self.name def parents(self): return self.parent def tree(self): return f"{self.parent} | {self.name}" views.py class CategoryView(ListView): model = Category template_name = 'category_list.html' queryset = model.objects.all() context_object_name = 'categories' base.html &lt;body&gt; &lt;div class="container-fluid"&gt; {% include 'navbar.html' %} {% include 'category_list.html' %} {% block content_body %}{% endblock %} {% include 'footer.html' %} &lt;/div&gt; &lt;/body&gt; category_list.html &lt;div class="row"&gt; {% for cat in categories %} &lt;div class="col-1"&gt; {{ cat.name }} &lt;/div&gt; {% endfor %} &lt;/div&gt; urls.py urlpatterns = [ path('category/', CategoryView.as_view(), name='category'), ] If I visit the url 127.0.0.1/category, these categories show up, but not in any other pages. So it's not globally showing in every pages of my website. Any suggestions?
tagged with: django
tagged with: python

http://stackoverflow.com/q/51993547
type: Question
answer count: 2
tagged with: python
has body: I have a data frame A which has a column called text which are long strings. I want to keep the rows of 'A' that have any string that are in a list 'author_id' of strings. A data frame: Dialogue Index author_id text 10190 0 573660 How is that even possible? 10190 1 23442 @573660 I do apologize. 10190 2 573661 @AAA do you still have the program for free checked bags? author_id list: [573660, 573678, 5736987] So since 573660 is in the author_id list and is in the text column of A, my expected outcome would be to keep only the second row of the data frame A: Dialogue Index author_id text 10190 1 23442 @573660 I do apologize. The most naive way of solving I can think of would be to do: new_A=pd.DataFrame() for id in author_id: new_A.append(A[A['text'].str.contains(id, na=False)] but this will take a long time. So I come up with this solution: [id in text for id in author_id for text in df['text'] ] But this doesn't work for subsetting the data frame because I obtain true false values for all the strings in df['text'] for each author id. So I created a new column in the data frame which is a combination of Dialogue and Index so I can return that in the list comprehension but it gave an error I don't know how to interpret. A["DialogueIndex"]= df["Dialogue"].map(str) + df["Index"] newA = [did for did in df["DialogueIndex"] for id in author_id if df['text'].str.contains(id) ] error: ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all(). Please help.
has answer: http://stackoverflow.com/a/51993635
score: 0
possible better answer: http://stackoverflow.com/a/51993949
accepted answer: http://stackoverflow.com/a/51993635
has answer: http://stackoverflow.com/a/51993949
tagged with: list-comprehension
tagged with: pandas
type: AnsweredQuestion
has title: subset panda dataframe using list comprehension

http://stackoverflow.com/comment/91099339
comment on: http://stackoverflow.com/q/52073960
has text: Really, you should avoid this where possible. But I have updated with a solution which reverses `str` output.
type: QuestionComment
type: Comment
score: 1

http://stackoverflow.com/comment/91070016
has text: Isn't it possible to start from what @Josh Friedlander says, then `pivot` the resulting dataframe to get desired result?
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52059751

http://stackoverflow.com/q/52073561
tagged with: flask-sqlalchemy
tagged with: python-3.x
tagged with: python
has answer: http://stackoverflow.com/a/52075985
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91097965
has body: We are trying to run a flask db migrate and flask db upgrade which throws the following error: Usage: flask db upgrade [OPTIONS] [REVISION] Error: The file/path provided (C) does not appear to exist. Please verify the path is correct. If app is not on PYTHONPATH, ensure the extension is .py We have added the app's directory to the PYTHONPATH environment variable but still get the error. Any help would be appreciated. Below is our __init__.py code. Are we missing something? import logging from flask import Flask from flask_appbuilder import SQLA, AppBuilder """ Logging configuration """ logging.basicConfig(format='%(asctime)s:%(levelname)s:%(name)s:%(message)s') logging.getLogger().setLevel(logging.DEBUG) app = Flask(__name__) app.config.from_object('config') db = SQLA(app) appbuilder = AppBuilder(app, db.session) migrate.init_app(app, db) """ from sqlalchemy.engine import Engine from sqlalchemy import event #Only include this for SQLLite constraints @event.listens_for(Engine, "connect") def set_sqlite_pragma(dbapi_connection, connection_record): # Will force sqllite contraint foreign keys cursor = dbapi_connection.cursor() cursor.execute("PRAGMA foreign_keys=ON") cursor.close() """ from app import views
tagged with: sqlalchemy
type: Question
accepted answer: http://stackoverflow.com/a/52075985
tagged with: flask
score: 0
has comment: http://stackoverflow.com/comment/91097197
has title: `flask db migrate` error
answer count: 1

http://stackoverflow.com/comment/95733620
score: 0
has text: This was the solution to my problem. I'm not sure why this was down-voted. I'm on Flask `0.12.1`, and was getting this error on Werkzeug `0.14.0`. Please include comments with your down-votes folks!
comment on: http://stackoverflow.com/a/53073753
type: Comment
type: AnswerComment

http://stackoverflow.com/q/52101907
tagged with: pandas
has comment: http://stackoverflow.com/comment/91154918
tagged with: python
tagged with: python-3.x
score: 2
downvote count: 0
has title: Writing a function for a single line of code?
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91155223
has comment: http://stackoverflow.com/comment/91162824
type: Question
upvote count: 2
has body: I am currently working with a pandas DataFrame and came across a problem. Should there be a separate function for setting the index or does it make the code to complex since you could simply write the one line of code anyway. def set_time_as_index(df): return df.set_index('time') Simplified version of current code: def create_df_rdy_for_export(input_data): dframe = pd.DataFrame(input_data) dframe = set_time_as_index(dframe) return dframe Or is it better to write: def create_df_rdy_for_export(input_data): dframe = pd.DataFrame(input_data) dframe = dframe.set_index('time') return dframe I am simply setting the index to the time-column. And since it only appears only one time in the script, there is no need to write a separate function but I am so used to it, that it feels odd, without a function. Are there any conventions or performance trade-offs?
answer count: 1
has comment: http://stackoverflow.com/comment/91154656
has answer: http://stackoverflow.com/a/52102027
accepted answer: http://stackoverflow.com/a/52102027
favorite count: 0

http://stackoverflow.com/comment/90896488
score: 0
comment on: http://stackoverflow.com/q/51972968
type: QuestionComment
type: Comment
has text: @RaunaqJain split '10|12|17|35' with '|' to get [10, 12, 17, 35]

http://stackoverflow.com/a/51993382
has body: IIUC, use str.contains and str.match vals = ['apple', 'candy', 'time'] df.loc[df.A.str.contains('|'.join(vals), case=False) | df.A.str.match(r'(\d+/\d+/\d+)')] A Q R S 0 Apple chair red english 3 Apple chair purple english 4 10/01/2016 05/02/2004 05/05/2014 06/20/2018 5 02/20/2017 01/01/2017 07/07/2017 02/04/2004
type: Answer
score: 2
downvote count: 0
answers question: http://stackoverflow.com/q/51993333
has comment: http://stackoverflow.com/comment/90936338
upvote count: 2

http://stackoverflow.com/comment/91056318
has text: sorry, it has little bit messy data. If I couldnt make you clear, maybe we could do chat. I can write another sample dataframe for it :)
type: Comment
score: 1
comment on: http://stackoverflow.com/a/52051933
type: AnswerComment

http://stackoverflow.com/q/52026759
type: UnansweredQuestion
tagged with: python
tagged with: kivy
has body: Ive been working on this code for some time now for a tetris app which makes blocks fall systematically one after the other and do not overlap each other.I have come up with this code but keep getting this an error saying that my widget class already has a parent. Some help please #Block 1 - 5 are stated above class Block6(Widget): vel_x = NumericProperty(0) vel_y = NumericProperty(-5) position = ReferenceListProperty(vel_x,vel_y) def fall(self, pos): self.pos = Vector(self.position) + self.pos if self.pos[1]==0: self.position[1] = 0 class TetrisApp(App): def build(self): game = TetrisGame() x = Window.width block1 = Block1(pos=(randint(0,x),Window.height)) block2 = Block2(pos=(randint(0,x),Window.height)) block3 = Block3(pos=(randint(0,x),Window.height)) block4 = Block4(pos=(randint(0,x),Window.height)) block5 = Block5(pos=(randint(0,x),Window.height)) block6 = Block6(pos=(randint(0,x),Window.height)) allblocks = (block1, block2, block3, block4, block5, block6) while game: blockchoice = randint(1,6) if blockchoice == 1: game.add_widget(block1) Clock.schedule_interval(block1.fall,1/60) for i in allblocks: if block1.collide_widget(i): block1.position[1] = 0 elif blockchoice == 2: game.add_widget(block2) Clock.schedule_interval(block2.fall,1/60) for i in allblocks: if block2.collide_widget(i): block2.position[1] = 0 elif blockchoice == 3: game.add_widget(block3) Clock.schedule_interval(block3.fall,1/60) for i in allblocks: if block3.collide_widget(i): block3.position[1] = 0 elif blockchoice == 4: game.add_widget(block4) Clock.schedule_interval(block4.fall,1/60) for i in allblocks: if block4.collide_widget(i): block4.position[1] = 0 elif blockchoice == 5: game.add_widget(block5) Clock.schedule_interval(block5.fall,1/60) for i in allblocks: if block5.collide_widget(i): block5.position[1] = 0 elif blockchoice == 6: game.add_widget(block6) Clock.schedule_interval(block6.fall,1/60) for i in allblocks: if block6.collide_widget(i): block6.position[1] = 0 else: print('this is…
type: Question
has answer: http://stackoverflow.com/a/52027199
score: 0
has title: Kivy, Systematic Animation using Clock.interval Error
answer count: 1

http://stackoverflow.com/comment/91173967
type: Comment
type: QuestionComment
has text: @Teoman imagine if you had a 400 column 1 million row dataframe and you printed that... you'd not get your computer back for a bit and you wouldn't want to see all that anyway... So it works on the basis if you do want that, you have to be really explicit about it... It'll try and print the first N and last N (with the ...) between and the first N columns and last N columns as above... so you get an idea of what's there... Generally setting the number of columns to None (or really high number) so you can scroll across columns makes sense but you'll rarely want to see all rows :)
comment on: http://stackoverflow.com/q/52111660
score: 0

http://stackoverflow.com/a/51992497
upvote count: 19
has comment: http://stackoverflow.com/comment/90935244
accepted answer of: http://stackoverflow.com/q/51992375
has comment: http://stackoverflow.com/comment/90936187
has comment: http://stackoverflow.com/comment/90937756
has comment: http://stackoverflow.com/comment/90935203
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/110856429
score: 18
has comment: http://stackoverflow.com/comment/90935294
has comment: http://stackoverflow.com/comment/90935686
has comment: http://stackoverflow.com/comment/90935160
has comment: http://stackoverflow.com/comment/90934945
has comment: http://stackoverflow.com/comment/90937709
has comment: http://stackoverflow.com/comment/90935070
type: Answer
has body: portaudio is not a Python package, it's a C library that's entirely independent of Python, so you can't install it via pip. See the PortAudio for website for details on the official way to get it and install it on your platform. AFAIK, the official way to get it on Windows is to download the source and then follow the instructions in the Tutorial for compiling it yourself. You probably want to build it with the same compiler you use for Python C extensions, although I'm not sure if that's required. Or, if you're using a third-party package manager like Chocolatey on Windows, there's a good chance it can install PortAudio. Or, if you use Anaconda or Miniconda for your Python, the conda package manager knows how to install non-Python packages that Python packages depend on, including portaudio. Finally, there seem to be a number of people providing unofficial pre-compiled PortAudio binaries for Windows. If you search for "portaudio windows binary" or "portaudio windows pre-compiled" you'll find a number of them. I have no idea how well-tested, up-to-date, etc. any of these are. If you're using Anaconda/Miniconda, you should have used conda install pyaudio rather than pip install pyaudio in the first place. You should really only use pip for packages that aren't available on conda or conda-forge. If you haven't set up conda-forge yet, you probably want to do that first: conda config --add channels conda-forge And then, this should be all you need: conda install pyaudio Unlike the pip package, which just assumes you have portaudio installed properly, the conda package will either automatically install portaudio as a dependency for pyaudio, or tell you why it can't.
answers question: http://stackoverflow.com/q/51992375
has comment: http://stackoverflow.com/comment/90937659
downvote count: 1
has comment: http://stackoverflow.com/comment/90937619
has comment: http://stackoverflow.com/comment/90935643

http://stackoverflow.com/q/52098291
score: 1
tagged with: scrapy
type: Question
upvote count: 2
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/52098331
accepted answer: http://stackoverflow.com/a/52098331
downvote count: 1
has body: I have a spider for LinkedIn. It is working fine on my local machine but when I deploy on Scrapinghub I got error: Error downloading &lt;GET https://www.linkedin.com/&gt;: Connection was refused by other side: 111: Connection refused. The complete log of Scrapinghub is: 0: 2018-08-30 12:58:34 INFO Log opened. 1: 2018-08-30 12:58:34 INFO [scrapy.log] Scrapy 1.0.5 started 2: 2018-08-30 12:58:34 INFO [scrapy.utils.log] Scrapy 1.0.5 started (bot: facebook_stats) 3: 2018-08-30 12:58:34 INFO [scrapy.utils.log] Optional features available: ssl, http11, boto 4: 2018-08-30 12:58:34 INFO [scrapy.utils.log] Overridden settings: {'NEWSPIDER_MODULE': 'facebook_stats.spiders', 'STATS_CLASS': 'sh_scrapy.stats.HubStorageStatsCollector', 'LOG_LEVEL': 'INFO', 'SPIDER_MODULES': ['facebook_stats.spiders'], 'RETRY_TIMES': 10, 'RETRY_HTTP_CODES': [500, 503, 504, 400, 403, 404, 408], 'BOT_NAME': 'facebook_stats', 'MEMUSAGE_LIMIT_MB': 950, 'DOWNLOAD_DELAY': 1, 'TELNETCONSOLE_HOST': '0.0.0.0', 'LOG_FILE': 'scrapy.log', 'MEMUSAGE_ENABLED': True, 'USER_AGENT': 'Mozilla/5.0 (X11; Linux x86_64; rv:7.0.1) Gecko/20100101 Firefox/7.7'} 5: 2018-08-30 12:58:34 INFO [scrapy.log] HubStorage: writing items to https://storage.scrapinghub.com/items/341545/3/9 6: 2018-08-30 12:58:34 INFO [scrapy.middleware] Enabled extensions: CoreStats, TelnetConsole, MemoryUsage, LogStats, StackTraceDump, CloseSpider, SpiderState, AutoThrottle, HubstorageExtension 7: 2018-08-30 12:58:35 INFO [scrapy.middleware] Enabled downloader middlewares: HttpAuthMiddleware, DownloadTimeoutMiddleware, UserAgentMiddleware, RetryMiddleware, DefaultHeadersMiddleware, MetaRefreshMiddleware, HttpCompressionMiddleware, RedirectMiddleware, CookiesMiddleware, ChunkedTransferMiddleware, DownloaderStats 8: 2018-08-30 12:58:35 INFO [scrapy.middleware] Enabled spider middlewares: HubstorageMiddleware, HttpErrorMiddleware, OffsiteMiddleware, RefererMiddleware, UrlLengthMiddleware, DepthMiddleware 9: 2018-08-30 12:58:35 INFO [scrapy.middleware] E…
tagged with: scrapinghub
tagged with: python
has title: Connection was refused by other side: 111: Connection refused
type: AnsweredQuestion

http://stackoverflow.com/comment/91110098
score: 0
comment on: http://stackoverflow.com/a/52080004
type: Comment
has text: @Jakob Then move it out of the class.
type: AnswerComment

http://stackoverflow.com/q/52058626
answer count: 2
tagged with: python
has comment: http://stackoverflow.com/comment/91067575
upvote count: 3
has title: Discord.py check if user reacts with a specific emoji
has comment: http://stackoverflow.com/comment/91067606
has body: I was wondering if there's a way to check if someone reacted with a specific emoji using Discord.py.
has answer: http://stackoverflow.com/a/52058840
has answer: http://stackoverflow.com/a/52058889
tagged with: discord.py
downvote count: 0
type: UnansweredQuestion
score: 3
favorite count: 0
type: Question

http://stackoverflow.com/q/51957941
has answer: http://stackoverflow.com/a/51958310
has answer: http://stackoverflow.com/a/51957996
answer count: 2
score: 2
downvote count: 0
tagged with: unicode
favorite count: 0
has comment: http://stackoverflow.com/comment/90866945
tagged with: python
has comment: http://stackoverflow.com/comment/90867520
has comment: http://stackoverflow.com/comment/90866405
tagged with: character
has comment: http://stackoverflow.com/comment/90896219
has title: I want to print the "\" character in python but I get "\\"
upvote count: 2
has comment: http://stackoverflow.com/comment/90866387
type: UnansweredQuestion
has body: I have a python list of strings with 000_S_0000 formatting. Since I want this list to be displayed in a LaTeX document, I want to save it first in a .txt file using a different formatting for each of its strings, specifically this one: 000\_S\_0000. However, when I wrote the modified list in the .txt file, each string was formated as 000\\_S\\_0000 instead. How could I solve that? Why isn't it working? Thanks in advance! This is my code: def posa_barres_latex(ll_PTIDs): for i in range(len(ll_PTIDs)): snou = '' for caracter in ll_PTIDs[i]: if caracter == "_": snou = snou + "\_" else: snou = snou + caracter ll_PTIDs[i] = snou with open("sortida_exclosos_criteri_c.txt","w") as f: f.write(str(ll_PTIDs)) posa_barres_latex(['002_S_2043', '018_S_2138', '013_S_2324', '129_S_4073', '002_S_4237', '019_S_4285', '130_S_4468', '136_S_4517', '013_S_4791', '031_S_4194','002_S_4219', '002_S_4251', '136_S_4408', '130_S_4605', '130_S_4925', '013_S_4985']) P.S. I am using python 3.
type: Question

http://stackoverflow.com/comment/90895905
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51972610
has text: Why did you make a tuple in the first place?

http://stackoverflow.com/q/52048943
has body: I have to get the text and link of an element if there is 'theme-cell-card Ace' else not. Following is the sample html code: textqwqw textegg textdgfh textgrth I am able to get text of an element but I want to pass the condition class="theme-cell-card Ace" is true. ${grid} Set Variable //div[@class='theme-cell'] @{elements} Get Webelements ${grid} :FOR ${element} IN @{elements} \ ${text} Get Text ${element} I am a newbie, so please let me know if you need more info. Thank you
answer count: 2
has answer: http://stackoverflow.com/a/52049653
favorite count: 0
possible better answer: http://stackoverflow.com/a/52067822
tagged with: python
has answer: http://stackoverflow.com/a/52067822
tagged with: selenium-webdriver
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/52049653
upvote count: 1
downvote count: 1
type: Question
tagged with: robotframework
has title: Get a link text and element text based on a condition
score: 0

del
tags question: http://stackoverflow.com/q/52041035
type: Tag
tag name: del

http://stackoverflow.com/q/52050527
tagged with: python-2.7
score: 0
answer count: 3
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/52053049
tagged with: python
tagged with: regex
has answer: http://stackoverflow.com/a/52050919
has body: I have the following list: ['L INE', 'LI NE', 'LIN E', 'L I NE', 'L I NE', 'L I N E'] I would like to use regex to replace every instance of the above list with 'LINE'. I used the follow expression re.sub('^L\s+[A-Z]E$'|'^L\s+[A-Z]\s+E$', 'LINE') but I'm getting incorrect results. I'm hoping any good soul can give me a nice expression that can tackle all the cases above, and also point me to a good and simple regex source that I can follow to learn more about it as I'm very new to using it. Many thanks in advance.
type: Question
has title: Regex python2.7
has answer: http://stackoverflow.com/a/52050783

http://stackoverflow.com/a/52026244
answers question: http://stackoverflow.com/q/52023734
type: Answer
has body: Python represents floating point numbers as binary fractions. Therefore numbers like 0.5 can be represented accurately, whereas 0.1 for example can not. Floating point numbers in Python are just approximations, if they can not be exactly represented using binary fractions. If you need more accuracy when dealing with floating point arithmetic, I would suggest taking a look at decimals: https://docs.python.org/3/library/decimal.html Additionally, a good resource on floating point numbers in Python can be found here: https://docs.python.org/3/tutorial/floatingpoint.html
score: 0

http://stackoverflow.com/comment/91177081
score: 0
type: Comment
comment on: http://stackoverflow.com/q/52110428
type: QuestionComment
has text: @VishalSingh He meant that your data should be scaled properly. Please, read [Tips on Practical Use](http://scikit-learn.org/stable/modules/svm.html#tips-on-practical-use) carefully. The first error you made is that you scaled train vector independently. "the same scaling must be applied to the test vector to obtain meaningful results." The second is - did you check what you've obtained after using StandardScaler? Maybe you should use another Scaler or Normalizer.

http://stackoverflow.com/comment/90927255
type: Comment
has text: I am pretty much confused by the error as we haven't hardcoded any size for the _List_ as such :( I have executed almost 20 times without any error. Did you `from random import randint`?
comment on: http://stackoverflow.com/a/51987760
type: AnswerComment
score: 0

http://stackoverflow.com/q/52082351
type: AnsweredQuestion
score: 3
tagged with: matplotlib
has answer: http://stackoverflow.com/a/52083432
accepted answer: http://stackoverflow.com/a/52084205
type: Question
has title: matplotlib - creating bars on x axis per group on y axis
answer count: 2
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/52084205
upvote count: 3
tagged with: pandas
tagged with: python
possible better answer: http://stackoverflow.com/a/52083432
has body: I have the following data frame: data = pd.DataFrame(data={'group': ['A', 'B', 'C'], 'start': [2, 5, 9], 'end': [9, 8, 6]}) I would love to create the following graph, I've searched everywhere and couldn't find an answer: graph I have looked everywhere, on matplotlib website, on pandas, i couldn't find a simple way to perform it.

http://stackoverflow.com/comment/90890496
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51969836
has text: @abarnert okay think I understand what I have to do now thanks. what would I use instead of `raw_input`?
score: 0

http://stackoverflow.com/q/52022692
tagged with: python
answer count: 4
type: AnsweredQuestion
has title: AWK reformat portion of results (names) within larger string
has body: My goal is to reformat names from Last First Middle (LFM) to First Middle Last (FML), which are part of a larger string. Here's some sample data: Name, Address1, Address2 Smith Joe M, 123 Apple Rd, Paris TX Adams Keith Randall, 543 1st Street, Salinas CA Price Tiffany, 11232 32nd Street, New York NY Walker Karen E F, 98 West Ave, Denver CO What I would like is: Name, Address1, Address2 Joe M Smith, 123 Apple Rd, Paris TX Keith Randall Adams, 543 1st Street, Salinas CA Tiffany Price, 11232 32nd Street, New York NY Karen E F Walker, 98 West Ave, Denver CO I know how to reorder the first column, but I end up dropping the rest of the row data: # Return the first colum via comma seperation (name), then seperate by spaces # If there are two strings but not three (only a last and first name), # then change the order to first last. awk -F, '{print $1}'| awk -F" " '$2!="" &amp;&amp; $3=="" {print $2,$1}' &gt;&gt; names.txt awk -F, '{print $1}'| awk -F" " '$3!="" &amp;&amp; $4=="" {print $3,$1,$2}' &gt;&gt; names.txt ...# Continue to iterate column numbers If there's an easier way to put the last string found and move it to the front I'd like to hear about it, but here's my real interest... My problem is that I want to reorder the space separated fields of the 1st comma separated field (what I did above), but then also print the rest of the comma separated data. Is there a way I can store the address info in a variable and append it after the space seperated names? Alternatively, could I do some kind of nested split? I'm currently doing this with awk in bash, but am willing to use python/pandas or any other efficient methods. Thanks for the help!
type: Question
has answer: http://stackoverflow.com/a/52024356
possible better answer: http://stackoverflow.com/a/52022924
accepted answer: http://stackoverflow.com/a/52022782
has answer: http://stackoverflow.com/a/52022924
has answer: http://stackoverflow.com/a/52025543
score: 0
tagged with: bash
tagged with: awk
has answer: http://stackoverflow.com/a/52022782

http://stackoverflow.com/q/52103391
has comment: http://stackoverflow.com/comment/91158365
upvote count: 4
favorite count: 0
score: 2
type: AnsweredQuestion
tagged with: pipe
has title: BrokenPipeError in Python but not in Perl
type: Question
answer count: 2
downvote count: 2
has answer: http://stackoverflow.com/a/52103634
tagged with: perl
linked to: http://stackoverflow.com/q/26692284
tagged with: runtime-error
possible better answer: http://stackoverflow.com/a/52103634
tagged with: flush
has answer: http://stackoverflow.com/a/52103885
accepted answer: http://stackoverflow.com/a/52103885
has body: Consider this Python script: for i in range(4000): print(i) and this Perl script: for my $i (0..4000-1) { print $i, "\n"; } python3 pipe.py | head -n3000 &gt;/dev/null produces an error: Exception ignored in: &lt;_io.TextIOWrapper name='&lt;stdout&gt;' mode='w' encoding='UTF-8'&gt; BrokenPipeError: [Errno 32] Broken pipe but perl pipe.pl | head -n3000 &gt;/dev/null produces no error (in Perl v5.26.1). Why such a discrepancy between Python and Perl? How to make Perl to produce a similar error message?
tagged with: python

http://stackoverflow.com/a/51991482
score: 4
type: Answer
upvote count: 4
answers question: http://stackoverflow.com/q/51991377
downvote count: 0
has body: Group by index mod 5 and concat horizontally. The last step is just fixing the column names with rename. df = pd.concat([g.reset_index(drop=True) for _, g in df.groupby(df.index % 5)], axis=1) df.columns = [f'Col {i}' for i in range(1, 6)] Col 1 Col 2 Col 3 Col 4 Col 5 0 Text A1 Text B1 Text C1 Text D1 Text E1 1 Text A2 Text B2 Text C2 Text D2 Text E2 2 Text A3 Text B3 Text C3 Text D3 Text E3

http://stackoverflow.com/comment/91015452
comment on: http://stackoverflow.com/a/52032629
score: 0
type: AnswerComment
type: Comment
has text: is atan2 a trignometric function? because if so that kind of kills the whole point. I know how to find the angle using arcsine/arctan

http://stackoverflow.com/a/52046041
has comment: http://stackoverflow.com/comment/91043405
type: Answer
has comment: http://stackoverflow.com/comment/117191021
upvote count: 10
accepted answer of: http://stackoverflow.com/q/52045839
type: AcceptedAnswer
score: 10
answers question: http://stackoverflow.com/q/52045839
downvote count: 0
has body: You don't pass it to reverse_lazy. Instead of using success_url, you should define the get_success_url method, which allows you to create the URL dynamically using whatever parameters you want. However there are few other things wrong with your code here. Firstly, you should not be trying to do all that calculation based on the HTTP_REFERER attribute. If your view needs a piece of information, you should pass it in the URL as a keyword parameter, which you can then get in your view by using self.kwargs. In your case it looks like your view already has the pk argument; you can use self.kwargs['pk']. Given that, your get_success_url method would look like: def get_success_url(self): return reverse('piece-detail', kwargs={'pk': self.kwargs['pk']}) Secondly, your get_form_kwargs method will always give a KeyError; the super method won't return a dictionary with a "piece" key, and even if it did the method must return a dict, not an individual value, including all the relevant items like the actual POST data. Again it's not clear what you are trying to do with this method; since you don't specify a custom form, it doesn't need custom kwargs. You should remove this method altogether. Finally, you don't need to call form.save() inside your form_valid method, even with commit=False. A CreateView already assigns an instance to the form, so you can just do form.instance.piece = ....

http://stackoverflow.com/comment/90976182
has text: If you solved the problem yourself, please post your solution as an answer and accept it. Self-answering questions is **encouraged** here.
comment on: http://stackoverflow.com/q/52009967
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52045893
has answer: http://stackoverflow.com/a/52047096
has comment: http://stackoverflow.com/comment/91042900
has comment: http://stackoverflow.com/comment/91042853
has comment: http://stackoverflow.com/comment/91042967
answer count: 1
has title: Pandas Output File not separating into different lines
has comment: http://stackoverflow.com/comment/91042867
accepted answer: http://stackoverflow.com/a/52047096
score: 0
tagged with: pandas
tagged with: python
has comment: http://stackoverflow.com/comment/91042920
type: AnsweredQuestion
tagged with: python-3.x
has body: I have this: with open(str(ssis_txt_file_names_only[a]) + '.dts', 'w', encoding='utf16') as file: whatever = whatever.replace("\n","") print(whatever) file.write(str(whatever)) When I do a print(whatever) all of the text appears on 1 line instead of broken up. Do anyone know what might be the cause? Currently, my output looks like this: >N</IsConnectionProperty> 0 What I want is this: >N<I/IsConnectionProperty> 0 Shouldn't the \n be doing this?
has comment: http://stackoverflow.com/comment/91042943
has comment: http://stackoverflow.com/comment/91042907
type: Question

http://stackoverflow.com/q/51977643
score: 0
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51978954
has comment: http://stackoverflow.com/comment/90905365
has answer: http://stackoverflow.com/a/52087888
has body: I'm a newbie to the random forest (as well as python). I'm using random forest classifier, the dataset is defined 't2002'. t2002.column So here are the columns: Index(['IndividualID', 'ES2000_B01ID', 'NSSec_B03ID', 'Vehicle', 'Age_B01ID', 'IndIncome2002_B02ID', 'MarStat_B01ID', 'EcoStat_B03ID', 'MainMode_B03ID', 'TripStart_B02ID', 'TripEnd_B02ID', 'TripDisIncSW_B01ID', 'TripTotalTime_B01ID', 'TripTravTime_B01ID', 'TripPurpFrom_B01ID', 'TripPurpTo_B01ID'], dtype='object') I'm using codes as below to run the classifier: from sklearn.ensemble import RandomForestClassifier from sklearn.metrics import make_scorer, accuracy_score from sklearn.model_selection import GridSearchCV from sklearn.model_selection import train_test_split X_all = t2002.drop(['MainMode_B03ID'],axis=1) y_all = t2002['MainMode_B03ID'] p = 0.2 X_train,X_test, y_train, y_test = train_test_split(X_all,y_all,test_size=p, random_state=23) clf = RandomForestClassifier() acc_scorer = make_scorer(accuracy_score) parameters = { } # parameter is blank grid_obj = GridSearchCV(clf,parameters,scoring=acc_scorer) grid_obj = grid_obj.fit(X_train,y_train) clf = grid_obj.best_estimator_ clf.fit(X_train,y_train) predictions = clf.predict(X_test) print(accuracy_score(y_test,predictions)) In this case, how could I use pandas to generate a crosstab (like a table) to show the detailed prediction results? Thanks in advance!
type: Question
has comment: http://stackoverflow.com/comment/90905475
answer count: 2
tagged with: random-forest
tagged with: scikit-learn
has comment: http://stackoverflow.com/comment/90905550
has title: How to use pandas to create a crosstab to show the prediction result of random forest predictor?
tagged with: pandas
tagged with: python
tagged with: sklearn-pandas

http://stackoverflow.com/comment/91023300
comment on: http://stackoverflow.com/a/52035991
has text: yes right now I'm just running localhost, so that may very well be the case, thank you for pointing that out. I could deploy it to a test server, to see if it works with an acutal IP? I just want to make sure, that you can just add the request.remote_addr parameter to the url?
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/a/52107088
accepted answer of: http://stackoverflow.com/q/52100621
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/52100621
has comment: http://stackoverflow.com/comment/91170725
has body: What you have to do is save the data of each item for this I have created the itemToTuple method that returns a tuple of the data to be saved, also given that saved tuple you must set those properties and for that you use the tupleToItem function (if you want add more information of the items you only have to modify those methods). But to save all the items of QTreeWidget, the whole tree must be traversed. For this, the dataFromChild method that returns the data of the item and its children is used. The inverse process, that is, given the data must be established in all the items, dataToChild must be used, which establishes the respective data to the item and its children. Also I have divided the application into several classes to have it sorted, if you want the information of a widget to be saved you must create a method called writeSettings(...) with a format similar to the ones I show then the application will call in the closeEvent(...) method. Similarly, you can create the readSettings(...) method and call it in its constructor. import os import sys from PyQt5 import QtCore, QtGui, QtWidgets iconroot = os.path.dirname(__file__) ORGANIZATION_NAME = 'Circularcolumn App' ORGANIZATION_DOMAIN = 'Circular shape' APPLICATION_NAME = 'QSettings program' SETTINGS_TRAY = 'settings/tray' QSS = """ QTreeWidget{ border:none; } QTreeView::branch:has-siblings:!adjoins-item { border-image: url(images/vline.png) 0; } QTreeView::branch:has-siblings:adjoins-item { border-image: url(images/branch-more.png) 0; } QTreeView::branch:!has-children:!has-siblings:adjoins-item { border-image: url(images/branch-end.png) 0; } QTreeView::branch:has-children:!has-siblings:closed, QTreeView::branch:closed:has-children:has-siblings { border-image: none; image: url(images/branch-closed.png); } QTreeView::branch:open:has-children:!has-siblings, QTreeView::branch:open:has-children:has-siblings { border-image: none; image: url(images/branch-open.png); } """ class TreeWidget(QtWidgets.QTreeWidget): …
has comment: http://stackoverflow.com/comment/91170504
type: Answer
score: 0
has comment: http://stackoverflow.com/comment/91170561

http://stackoverflow.com/a/52095829
score: 0
type: Answer
has body: Let say there n number of list l1, l2, l3, ... and If you add them it has only one copy on some address. eg: In [8]: l1 = [1,2,3] In [9]: l2 = [4,5,6] In [10]: id(l1 + l2) Out[10]: 140311052048072 In [11]: id(l1) Out[11]: 140311052046704 In [12]: id(l2) Out[12]: 140311052047136 id() returns identity of an object. https://docs.python.org/2/library/functions.html#id
answers question: http://stackoverflow.com/q/52095550

http://stackoverflow.com/a/73585446
answers question: http://stackoverflow.com/q/51980383
type: Answer
has body: The solution above did not work for me, however, this worked: server = TSC.Server('yourURL',use_server_version=False) server.add_http_options({'verify': False}) setting 'use_server_version=' to 'False' worked for me. Also, you can try to change 'https' to 'http'. Others noted that it also helped them to update their certificates: pip install python-certifi-win32
score: 0

http://stackoverflow.com/comment/90917382
score: 0
type: AnswerComment
type: Comment
has text: What version of NumPy do you have?
comment on: http://stackoverflow.com/a/51983415

http://stackoverflow.com/a/52062635
has comment: http://stackoverflow.com/comment/91106998
has comment: http://stackoverflow.com/comment/91099519
answers question: http://stackoverflow.com/q/52061978
has body: In Pycharm go to project setting,then go to project interpreter make sure that you have your required python virtual environment (which I think you did it already) Under same selected environment, make sure that you have installed Django Of course, if there is the dependency on Django, you can just type pip install django
score: 0
type: Answer

http://stackoverflow.com/comment/91005400
has text: If I try to use this, it just gives me an error: "Unable to open file" at "the attack_sounds.append" part
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52021725

http://stackoverflow.com/q/52098208
score: 2
answer count: 0
upvote count: 2
type: Question
has body: I'm trying to freeze my application using pyInstaller, unfortunately although my .exe file is created properly, when i'm trying to run the app, it's failed every time with ImportError of missing dll file without notify which one is missing as you can see below: File "Lib\site-packages\PyInstaller\loader\pyimod03_importers.py", line 396, i n load_module File "site-packages\matplotlib\pyplot.py", line 31, in &lt;module&gt; File "Lib\site-packages\PyInstaller\loader\pyimod03_importers.py", line 396, i n load_module File "site-packages\matplotlib\colorbar.py", line 36, in &lt;module&gt; File "Lib\site-packages\PyInstaller\loader\pyimod03_importers.py", line 396, i n load_module File "site-packages\matplotlib\contour.py", line 20, in &lt;module&gt; File "Lib\site-packages\PyInstaller\loader\pyimod03_importers.py", line 396, i n load_module File "site-packages\matplotlib\font_manager.py", line 55, in &lt;module&gt; File "Lib\site-packages\PyInstaller\loader\pyimod03_importers.py", line 687, i n load_module ImportError: DLL load failed: The specified procedure could not be found. [5532] Failed to execute script Main after some research i found out that the dll that cause the problem was zlib.dll, its seems that pyInstaller isn't collecting the right zlib.dll because when i have tried to add zlib.dll from \my\path\to\anaconda\Library\bin by hand to the .exe folder, my app ran perfect. I'm using Python=2.7, Anaconda=5.2.0, pyInstaller=3.3.1.
tagged with: zlib
downvote count: 0
favorite count: 0
has title: wrong zlib.dll added by pyinstaller to exe folder
tagged with: pyinstaller
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91587588
tagged with: python

http://stackoverflow.com/a/52005039
type: Answer
has body: I think you forgot a comma between pos and (4,8,12,3,17,6): matplotlib.pyplot.bar(pos,(4,8,12,3,17,6),align="center",color="red") Output:
score: 0
answers question: http://stackoverflow.com/q/52004987

http://stackoverflow.com/a/51994671
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/91290767
has comment: http://stackoverflow.com/comment/91182954
has comment: http://stackoverflow.com/comment/91099405
answers question: http://stackoverflow.com/q/51994368
has comment: http://stackoverflow.com/comment/91290845
has comment: http://stackoverflow.com/comment/91075325
type: Answer
has comment: http://stackoverflow.com/comment/90948396
has comment: http://stackoverflow.com/comment/91293095
accepted answer of: http://stackoverflow.com/q/51994368
has comment: http://stackoverflow.com/comment/90940061
has comment: http://stackoverflow.com/comment/91161385
has comment: http://stackoverflow.com/comment/91208004
has comment: http://stackoverflow.com/comment/91192025
has body: If you want to remove everything that is not a digit or a space, why don't you use a variation on this idea for line in data: print(''.join(c for c in line if c in '0123456789 ')) where we stick together (''.join(...)) only the wanted characters in each of the input line? Update The previous answer remains because it's perfect for the requirements the OP originally expressed (see the edit history of the question). However, given the new requirements the OP has given, they could try to use the following code $ cat nofubar.py from sys import stdin q = '"' + "'" # we want to remove the 'q'outes foobar = 'FooBar:' # and also Foo, Bar and ':' too... print(next(stdin), end='') # print the header line to stdout, note end='' for line in stdin: # strip quotes on both sides, # strip (all) the characters in foobar * only on the left * toks = [tok.strip(q).lstrip(foobar) for tok in line.split()] print(' '.join(toks)) $ Let's put this new code to test $ python nofubar.py &lt;&lt; END &gt; good.csv COLUMN1 COLUMN2 COLUMN3 'Foo325GoodData' Bar:388GoodData 383GoodData 'Foo123GoodData' Bar:998GoodData 293GoodData END $ cat good.csv COLUMN1 COLUMN2 COLUMN3 325GoodData 388GoodData 383GoodData 123GoodData 998GoodData 293GoodData $ Assuming that the file with extraneous characters is named bad.csv you can connect it to stdin using the input redirection symbol &lt; on the shell command line $ python nofubar.py &lt; bad.csv &gt; good.csv $
score: 0

http://stackoverflow.com/a/52080609
upvote count: 1
answers question: http://stackoverflow.com/q/52080551
type: Answer
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/91115430
has body: You can use os.get_terminal_size: import os os.get_terminal_size() #os.terminal_size(columns=80, lines=24) and this class returned supports unpacking: columns, lines = os.get_terminal_size()
has comment: http://stackoverflow.com/comment/91113075

http://stackoverflow.com/a/52074956
score: 0
type: Answer
has body: A two liner, extracting class and dict if the 'orig_h' is in the mapper dictionary's keys, if it id, keep it, otherwise don't keep it, then create a new dictionary comprehension inside the list comprehension to add 'class' to the dictionary's 'conn' key's dictionary. l=[(i,mapper[i['conn']['orig_h']]) for i in (dict_1,dict_2) if i['conn']['orig_h'] in mapper] print([{'conn':dict(a['conn'],**{'class':b})} for a,b in l]) BTW this answer chooses the dictionaries automatically
answers question: http://stackoverflow.com/q/52074701

http://stackoverflow.com/a/52086256
has comment: http://stackoverflow.com/comment/91137955
accepted answer of: http://stackoverflow.com/q/52085864
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/91141437
answers question: http://stackoverflow.com/q/52085864
type: Answer
score: 0
has body: Good question, it depends on what data is but certainly the code snippet is misleading. To clarify: If you call model directly you need to pass tensors, it acts like another layer. model(anotherlayer) works for example. But if you pass actual data such as a NumPy error it will give this error: ValueError: Layer sequential_1 was called with an input that isn't a symbolic tensor. Received type: . Full input: [array(...)]. All inputs to the layer should be tensors. If you want to predict, as in pass some numeric data and run the network / propagate values / compute output then you need to model.predict(data) which is why it is misleading as it is a predict function. My guess is that the author needed to chain models together and edited the predict function of the class instead of creating a different class function.
has comment: http://stackoverflow.com/comment/91159172
has comment: http://stackoverflow.com/comment/91137869

http://stackoverflow.com/a/78365049
answers question: http://stackoverflow.com/q/52085191
has body: If the proposed solutions don't work, here's what I did: I had to specify the path to my virtual environment to do a pip install. I don't know why it didn't work before when I had activated my environment. CD Path/to/virtual/env pip install pyodbc
score: 0
type: Answer

http://stackoverflow.com/comment/91077659
comment on: http://stackoverflow.com/a/52063255
score: 0
type: Comment
has text: @saitam, I edited my answer, adding a code snippet for that
type: AnswerComment

http://stackoverflow.com/q/52018267
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/52019989
tagged with: opengl
score: 1
has body: I'm trying to implement viewing matrix and projection, similar to gluLookAt to get the view position of each 3D coordinate. I have implemented something that seems close to working but is reversed. For example - the following code gets the correct position (When I actually don't change the coordinates. But if I change the up-vector to point towards X instead of Y, I get reversed coordinates. import numpy as np def normalize_vector(vector): return vector / (np.linalg.norm(vector)) def get_lookat_matrix(position_vector, front_vector, up_vector): m1 = np.zeros([4, 4], dtype=np.float32) m2 = np.zeros([4, 4], dtype=np.float32) z = normalize_vector(-front_vector) x = normalize_vector(np.cross(up_vector, z)) y = np.cross(z, x) m1[:3, 0] = x m1[:3, 1] = y m1[:3, 2] = z m1[3, 3] = 1.0 m2[0, 0] = m2[1, 1] = m2[2, 2] = 1.0 m2[:3, 3] = -position_vector m2[3, 3] = 1.0 return np.matmul(m1, m2) def get_projection_matrix(near, far): aspect = 1.0 fov = 1.0 # 90 Degrees m = np.zeros([4, 4], dtype=np.float32) m[0, 0] = fov/aspect m[1, 1] = fov m[2, 2] = (-far)/(far-near) m[2, 3] = (-near*far)/(far-near) m[3, 2] = -1.0 return m position_vector = np.array([0, 0, 0], dtype=np.float32) front_vector = np.array([0, 0, -1], dtype=np.float32) up_vector = np.array([0, 1, 0], dtype=np.float32) viewing_matrix = get_lookat_matrix(position_vector=position_vector, front_vector=front_vector, up_vector=up_vector) print("viewing_matrix\n", viewing_matrix, "\n\n") projection_matrix = get_projection_matrix(near=0.1, far=100.0) point = np.array([1, 0, -10, 1], dtype=np.float32) projected_point = projection_matrix.dot(viewing_matrix.dot(point)) # Normalize projected_point /= projected_point[3] print(projected_point) And it happens with many changes of the coordinates. I'm not sure where am I wrong.
tagged with: pyopengl
type: Question
tagged with: projection
answer count: 2
upvote count: 1
has answer: http://stackoverflow.com/a/52019342
accepted answer: http://stackoverflow.com/a/52019342
downvote count: 0
has title: Manually project coordinates similar to gluLookAt in python
favorite count: 0
has answer: http://stackoverflow.com/a/52019989
tagged with: python-3.x
tagged with: python

http://stackoverflow.com/comment/91087934
comment on: http://stackoverflow.com/q/52067432
score: 0
has text: I see only one version of the code here, can you show both versions, or am I misunderstanding ? Also I see only 1 set of results..?
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51976479
has comment: http://stackoverflow.com/comment/90904270
has answer: http://stackoverflow.com/a/51977548
tagged with: django-rest-framework
has comment: http://stackoverflow.com/comment/90904843
score: 0
tagged with: rest
answer count: 1
tagged with: patch
has title: How to make PATCH method work for partial update in Django app? Without ImageField update, it doesn't work
tagged with: django
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51977548
type: Question
has body: I'm trying to enable partial update in Django web app (using Django Rest Framework). The model I want to update includes ImageField. PATCH method works when I update the ImageField, but it doesn't work when I don't update the ImageField. Error message says AttributeError:'NoneType' object has no attribute 'items' How can I fix it? Model: class Work(models.Model): owner = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True, blank=True) title = models.CharField(max_length=120) made_date = models.DateField(default=datetime.date.today, null=True, blank=True) note = models.TextField(max_length=2000, null=True, blank=True) image = models.ImageField(upload_to='work_pic', default='default_image.png') def __str__(self): return self.title def save(self, *args, **kwargs): if self.image and self.image.name.lower().endswith(('.jpg', '.jpeg')): pilImage = Img.open(BytesIO(self.image.read())) for orientation in ExifTags.TAGS.keys(): if ExifTags.TAGS[orientation] == 'Orientation': break exif = dict(pilImage._getexif().items()) if exif[orientation] == 3: pilImage = pilImage.rotate(180, expand=True) elif exif[orientation] == 6: pilImage = pilImage.rotate(270, expand=True) elif exif[orientation] == 8: pilImage = pilImage.rotate(90, expand=True) output = BytesIO() pilImage.save(output, format='JPEG', quality=75) output.seek(0) self.image = File(output, self.image.name) return super(Work, self).save(*args, **kwargs) Serializer: class WorkSerializer(serializers.ModelSerializer): owner = serializers.HiddenField(default=serializers.CurrentUserDefault()) class Meta: model = Work fields = '__all__' def create(self, validated_data): return Work.objects.create(**validated_data) ViewSet: class WorkViewSet(viewsets.ModelViewSet): queryset = Work.objects.all() serializer_class = WorkSerializer def partial_update(self, request, *args, **kwargs): kwargs['partial'] = True return self.update(request, *args, **kwargs) Method to send request (Vue.js): updateWork: function() …

http://stackoverflow.com/q/51990639
tagged with: python
tagged with: nlp
type: AnsweredQuestion
type: Question
accepted answer: http://stackoverflow.com/a/51990961
tagged with: http://stackoverflow.com/tag/r
has answer: http://stackoverflow.com/a/51990961
score: 0
tagged with: apache-spark
answer count: 1
has body: I have a csv with a single column, each row is a text document. All text has been normalized: all lowercase no punctuation no numbers no more than one whitespace between words no tags(xml, html) I have also this R script which constructs the Document Term Matrix on these documents and does some machine learning analysis. I need to convert this in Spark. The first step is to produce the Document Term Matrix where for each term there is the relative frequency count in the document. The problem is that I am getting different vocabularies size using R, respect to spark api or python sklearn (spark and python are consistent in the result). This is the relevant code for R: library(RJDBC) library(Matrix) library(tm) library(wordcloud) library(devtools) library(lsa) library(data.table) library(dplyr) library(lubridate) corpus &lt;- read.csv(paste(inputDir, "corpus.csv", sep="/"), stringsAsFactors=FALSE) DescriptionDocuments&lt;-c(corpus$doc_clean) DescriptionDocuments &lt;- VCorpus(VectorSource(DescriptionDocuments)) DescriptionDocuments.DTM &lt;- DocumentTermMatrix(DescriptionDocuments, control = list(tolower = FALSE, stopwords = FALSE, removeNumbers = FALSE, removePunctuation = FALSE, stemming=FALSE)) # VOCABULARY SIZE = 83758 This is the relevant code in Spark (1.6.0, Scala 2.10): import org.apache.spark.ml.feature.{CountVectorizer, CountVectorizerModel, RegexTokenizer} var corpus = sqlContext.read.format("com.databricks.spark.csv").option("header", "true").option("inferSchema", "false").load("/path/to/corpus.csv") // RegexTokenizer splits by default on one or more spaces, which is ok val rTokenizer = new RegexTokenizer().setInputCol("doc").setOutputCol("words") val words = rTokenizer.transform(corpus) val cv = new CountVectorizer().setInputCol("words").setOutputCol("tf") val cv_model = cv.fit(words) var dtf = cv_model.transform(words) // VOCABULARY SIZE = 84290 I've also checked in python sklearn and I got consistent result with spark: import pandas as pd from sklearn.f…
tagged with: scala
has title: R tm package and Spark/python give different vocabulary size for Document Term Frequency task

http://stackoverflow.com/comment/90988805
has text: So actually it return an iterator to a list not a list itself ! Thanks for your response
type: QuestionComment
comment on: http://stackoverflow.com/q/52019192
score: 0
type: Comment

http://stackoverflow.com/q/52043027
type: AnsweredQuestion
tagged with: yaml
downvote count: 0
favorite count: 0
type: Question
score: 3
tagged with: python
has answer: http://stackoverflow.com/a/66820079
has answer: http://stackoverflow.com/a/52045749
upvote count: 3
answer count: 2
possible better answer: http://stackoverflow.com/a/66820079
has comment: http://stackoverflow.com/comment/91042862
tagged with: ruamel.yaml
linked to: http://stackoverflow.com/q/66820321
accepted answer: http://stackoverflow.com/a/52045749
has title: get comment during iteration in ruamel.yaml
has body: How can I get the comments when I iterate through the YAML object yaml = YAML() with open(path, 'r') as f: yaml_data = yaml.load(f) for obj in yaml_data: # how to get the comments here? This is the source data (an ansible playbook) --- - name: gather all complex custom facts using the custom module hosts: switches gather_facts: False connection: local tasks: # There is a bug in ansible 2.4.1 which prevents it loading # playbook/group_vars - name: ensure we're running a known working version assert: that: - 'ansible_version.major == 2' - 'ansible_version.minor == 4' After Anthon comments, this is the way I found to access the comments in the child nodes (needs to be refined): for idx, obj in enumerate(yaml_data): for i, item in enumerate(obj.items()): pprint(yaml_data[i].ca.items)

http://stackoverflow.com/q/52089002
tagged with: vim
has answer: http://stackoverflow.com/a/53032515
has answer: http://stackoverflow.com/a/52089861
type: Question
answer count: 2
has title: Getting errors when entering a vim file and tmux
score: 0
tagged with: tmux
tagged with: macos
type: UnansweredQuestion
has body: I was trying to install a plugin for tmux called powerline. I was installing some thing on brew like PyPy and python. Now when I try to open a vim file I get: dyld: Library not loaded: /usr/local/opt/python/Frameworks/Python.framework/Versions/3.6/Python Referenced from: /usr/local/bin/vim Reason: image not found Abort trap: 6 and when I try to open tmux i get: exited
tagged with: python

http://stackoverflow.com/comment/91067705
has text: @Cut7er - Yes, because need correct align vertical line.
comment on: http://stackoverflow.com/q/52058695
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52097835
tagged with: python-3.x
score: 0
has comment: http://stackoverflow.com/comment/91293568
has title: IF string contains 'XX' then change color...Write_rich_string to Panda Dataframe?
has comment: http://stackoverflow.com/comment/91194981
type: UnansweredQuestion
tagged with: numpy
answer count: 0
tagged with: python-2.7
type: Question
tagged with: pandas
tagged with: python
has body: I have about 7 dfs that are saved and write to individual sheets within an excel workbook. They are currently doing so using openpyxl. I found this code which does almost exactly what I am looking for - the issue is that if I replace the 'sequences = .....' with 'sequences = df' which is the name of my dataframe, the data is not populating correctly.. Ultimately I have 7 dfs that I am trying to put on this 1 workbook (on different sheets), some with this condition, some with other conditions and some without conditions. Does anyone have any ideas on how to do this properly? I am still learning from xlsxwriter.workbook import Workbook workbook = Workbook('sequences.xlsx') worksheet = workbook.add_worksheet() red = workbook.add_format({'color': 'red'}) green = workbook.add_format({'color': 'green'}) sequences = [ 'ACAAGATG', 'CCATTGTC', 'CCCCGGCC', 'CCTGCTGC', 'GCTGCTCT', 'CGGGGCCA', 'GGCCACCG', ] worksheet.set_column('A:A', 40) for row_num, sequence in enumerate(sequences): format_pairs = [] # Get each DNA base character from the sequence. for base in sequence.upper(): # Prefix each base with a format. if base == 'A' or base == 'T': format_pairs.extend((red, base)) elif base == 'G' or base == 'C': format_pairs.extend((green, base)) else: # Non base characters are unformatted. format_pairs.append(base) worksheet.write_rich_string(row_num, 0, *format_pairs) workbook.close() This is the output of df: enter image description here This is what I get in excel file: enter image description here

http://stackoverflow.com/q/51992551
tagged with: serialization
has body: I have a Marshmallow schema where an objects use a key to refer to an object that is defined in a dictionary in another part of the structure. I want to have the key automatically resolved when deserializing the object. How can I achieve this effect in Marshmallow in an idiomatic manner? The workaround for now is to resolve all of the references manually, but this seems clunky, since the declarative nature of Marshmallow should be able to do it for us automatically. Note that Marshmallow-SQLAlchemy supports this kind of (de-)serialization when columns are declared as relationships" which do this automatically for us, but I want to do it with JSON data. Here is an example of what I want to achieve, with fields.Relationship being something that does not exist yet: class UserSchema(Schema): name = fields.String() email = fields.Email() friends = fields.Relationship('self', path="AddressBook.contacts", many=True) class AddressBookSchema(Schema): contacts = nested.Dict(keys=fields.String(), values=fields.Nested(UserSchema)) # ... create ``user`` ... serialized_data = AddressBookSchema().dump(user) pprint(serialized_data) # "contacts": { # "Steve": { # "name": "Steve", # "email": "steve@example.com", # "friends": ["Mike"] # }, # "Mike": { # "name": "Mike", # "email": "mike@example.com", # "friends": [] # } deserialized_data = UserSchema().load(result) pprint(deserialized_data) # "contacts": { # "Steve": { # "name": "Steve", # "email": "steve@example.com", # "friends": [ {"name": "Mike", "email": "mike@example.com"] # }, # "Mike": { # "name": "Mike", # "email": "mike@example.com", # "friends": [] # } I have also filed an issue on the Marshmallow Github repository.
tagged with: python
upvote count: 6
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/52812320
score: 6
has title: Automatic dictionary key resolution with nested schemas using Marshmallow
type: Question
tagged with: schema
has answer: http://stackoverflow.com/a/52812320
tagged with: marshmallow
downvote count: 0
answer count: 1
tagged with: nested
favorite count: 0

http://stackoverflow.com/comment/90960788
has text: Please don't link to an image of the output, but put it, with code formatting, in your question. And you should run pip from the command line, not the python interpreter.
type: Comment
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/52005532

http://stackoverflow.com/q/52009997
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/91292223
tagged with: python
has comment: http://stackoverflow.com/comment/91260170
has body: For png images I could use: ax.imshow(plt.imread('./image.png')) It is possible to use something similar but for svg or pdf images?
favorite count: 0
answer count: 0
has title: Adding a vector graphic in to a matplotlib axis
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91292324
upvote count: 1
tagged with: vector-graphics
tagged with: matplotlib
type: Question

http://stackoverflow.com/a/52117885
has comment: http://stackoverflow.com/comment/92592036
has comment: http://stackoverflow.com/comment/92378446
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/91187027
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52078244
has comment: http://stackoverflow.com/comment/92591775
has comment: http://stackoverflow.com/comment/92396933
answers question: http://stackoverflow.com/q/52078244
has body: Don´t do 12000 find_one queries, do 1 query to bring all that exist with $in operator. Code would be something like: pet_codes = [] pet_names = [] while dictionary != False: pet_codes.append(dictionary['pet_code']) pet_names.append(dictionary['pet_name']) pets = dict() for pet in pet.find({"code": {$in: pet_codes}}): pets[pet['code']] = pet new_pets = [] for code, name in zip(pet_codes, pet_names): if code not in pets: new_pets.add({'pet_code': code, 'name': name}) pet.insert_many(new_pets) As you already have an index on pet_code making it unique, we can do better: just try to insert them all, because if we try to insert an existing one that record will get an error, but the rest will succeed by using the ordered=False from the docs: new_pets = [] while dictionary != False: new_pets.add({ "code" : dictionary['pet_code'], "name" : dictionary['name'] }) pet.insert_many(new_pets, ordered=False) In the case where you do not have a unique restriction set, another method is batching the operations
has comment: http://stackoverflow.com/comment/92378926
type: Answer
has comment: http://stackoverflow.com/comment/91187283
has comment: http://stackoverflow.com/comment/92576822
has comment: http://stackoverflow.com/comment/92377554
score: 1
has comment: http://stackoverflow.com/comment/92409891
has comment: http://stackoverflow.com/comment/92557704
upvote count: 1
has comment: http://stackoverflow.com/comment/91186967
has comment: http://stackoverflow.com/comment/92560692
has comment: http://stackoverflow.com/comment/92543410
has comment: http://stackoverflow.com/comment/92378752
has comment: http://stackoverflow.com/comment/91187432
has comment: http://stackoverflow.com/comment/92559475

http://stackoverflow.com/a/52075834
has comment: http://stackoverflow.com/comment/91101288
score: 1
has comment: http://stackoverflow.com/comment/91101335
downvote count: 0
has body: An alternative solution, especially on older versions of Pandas, is to use GroupBy + apply on a sequence, then combine via concat. Benchmarking on Python 3.60 / Pandas 0.19.2. This contrived example has a small number of groups; you should test with your data if efficiency is a concern. import pandas as pd df = pd.DataFrame({'A': ['test2', 'test2', 'test4', 'test4'], 'B': [{'x': 'a'}, {'x': 'b'}, {'y': 'a'}, {'y': 'b'}], 'C': ['test1', 'test2', 'test3', 'test4']}) df = pd.concat([df]*10000) def jpp(df): g = df.groupby('A') L = [g[col].apply(list) for col in ['B', 'C']] return pd.concat(L, axis=1).reset_index() %timeit jpp(df) # 11.3 ms per loop %timeit df.groupby('A').agg(lambda x: list(x)) # 20.5 ms per loop
has comment: http://stackoverflow.com/comment/91101414
answers question: http://stackoverflow.com/q/52075442
has comment: http://stackoverflow.com/comment/91101372
has comment: http://stackoverflow.com/comment/91101397
type: Answer
upvote count: 1

apache-spark
tags question: http://stackoverflow.com/q/51997349
tags question: http://stackoverflow.com/q/52038368
tags question: http://stackoverflow.com/q/52078014
tags question: http://stackoverflow.com/q/51990639
tags question: http://stackoverflow.com/q/51975317
tags question: http://stackoverflow.com/q/52090066
tags question: http://stackoverflow.com/q/52024326
tags question: http://stackoverflow.com/q/52001195
tag name: apache-spark
tags question: http://stackoverflow.com/q/51990946
tags question: http://stackoverflow.com/q/52049311
tags question: http://stackoverflow.com/q/52081890
tags question: http://stackoverflow.com/q/51969739
tags question: http://stackoverflow.com/q/52111009
tags question: http://stackoverflow.com/q/52013366
tags question: http://stackoverflow.com/q/52086089
tags question: http://stackoverflow.com/q/52096069
tags question: http://stackoverflow.com/q/52071854
tags question: http://stackoverflow.com/q/51976974
tags question: http://stackoverflow.com/q/52104966
tags question: http://stackoverflow.com/q/52111694
tags question: http://stackoverflow.com/q/51994256
tags question: http://stackoverflow.com/q/51977088
tags question: http://stackoverflow.com/q/52031127
tags question: http://stackoverflow.com/q/52008233
tags question: http://stackoverflow.com/q/51987725
tags question: http://stackoverflow.com/q/52083433
tags question: http://stackoverflow.com/q/52095181
tags question: http://stackoverflow.com/q/51970729
type: Tag
tags question: http://stackoverflow.com/q/52111141
tags question: http://stackoverflow.com/q/52049512
tags question: http://stackoverflow.com/q/52076651
tags question: http://stackoverflow.com/q/52046947
tags question: http://stackoverflow.com/q/52032966

http://stackoverflow.com/a/51990289
answers question: http://stackoverflow.com/q/51977805
type: Answer
has body: The problem because of permission issue therefore you have to open cmd as administrator mode and run below command pip install tensorflow-gpu
score: 0

http://stackoverflow.com/q/52026904
downvote count: 1
type: Question
has answer: http://stackoverflow.com/a/52060028
has title: How to draw an histogram with multiple categories in python
score: 0
answer count: 1
tagged with: histogram
favorite count: 0
has comment: http://stackoverflow.com/comment/91053294
type: UnansweredQuestion
has body: I am a freshman in python, and I have a problem of how to draw a histogram in python. First of all, I have ten intervals that are divided evenly according to the length of flowers' petal, from min to max. Thus I can separate flowers into ten intervals based on petals. The number of flowers' kind is three, so I want to draw a histogram to describe the distribution of different kinds of flowers in different intervals(bins). And in the same bin, different flowers have different colors. I know the hist functions in Matplotlib, but I don't know how to use it to draw pictures like below. The data are Lbins = [0.1 , 0.34, 0.58, 0.82, 1.06, 1.3 , 1.54, 1.78, 2.02, 2.26, 2.5 ] and Data_bins is an array of shape (number of flowers, 3).
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/91004101
tagged with: matplotlib

http://stackoverflow.com/comment/91038250
score: 0
comment on: http://stackoverflow.com/q/52024319
type: Comment
has text: You need the log from the broker, not from `mosquitto_sub` to show which client is actually doing the publishing
type: QuestionComment

http://stackoverflow.com/comment/91004537
type: QuestionComment
has text: `join` cannot slow anything down. It just waits until the thread finishes. Why you have a `count=0`? It seems to be useless and I don't know if python is smart enough to selialize access to this variable. This could be a potential time-hole.
comment on: http://stackoverflow.com/q/52026987
score: 0
type: Comment

http://stackoverflow.com/q/52030118
upvote count: 1
type: Question
score: 1
has answer: http://stackoverflow.com/a/52031068
downvote count: 0
answer count: 1
tagged with: neo4j
favorite count: 0
type: UnansweredQuestion
has body: I have installed neo4j desktop and I am able to use neo4j database from it. The problem is when I try to connect to neo4j database from a Django project. I have configured my settings.py with config.DATABASE_URL = 'bolt://neo4j:neo4j@localhost:7687', but when I run neomodel_install-labels, I get this error: Connecting to bolt://neo4j:neo4j@localhost:7687 Traceback (most recent call last): File "/Users/hugovillalobos/Documents/Code/AttractoraProject/AttractoraVenv/lib/python3.6/site-packages/neo4j/bolt/connection.py", line 578, in _connect s.connect(resolved_address) ConnectionRefusedError: [Errno 61] Connection refused During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/Users/hugovillalobos/Documents/Code/AttractoraProject/AttractoraVenv/bin/neomodel_install_labels", line 67, in &lt;module&gt; main() File "/Users/hugovillalobos/Documents/Code/AttractoraProject/AttractoraVenv/bin/neomodel_install_labels", line 62, in main db.set_connection(bolt_url) File "/Users/hugovillalobos/Documents/Code/AttractoraProject/AttractoraVenv/lib/python3.6/site-packages/neomodel/util.py", line 65, in set_connection max_pool_size=config.MAX_POOL_SIZE) File "/Users/hugovillalobos/Documents/Code/AttractoraProject/AttractoraVenv/lib/python3.6/site-packages/neo4j/v1/api.py", line 94, in driver return Driver(uri, **config) File "/Users/hugovillalobos/Documents/Code/AttractoraProject/AttractoraVenv/lib/python3.6/site-packages/neo4j/v1/api.py", line 133, in __new__ return subclass(uri, **config) File "/Users/hugovillalobos/Documents/Code/AttractoraProject/AttractoraVenv/lib/python3.6/site-packages/neo4j/v1/direct.py", line 7 3, in __new__ pool.release(pool.acquire()) File "/Users/hugovillalobos/Documents/Code/AttractoraProject/AttractoraVenv/lib/python3.6/site-packages/neo4j/v1/direct.py", line 4 4, in acquire return self.acquire_direct(self.address) File "/Users/hugovillalobos/Documents/Code/AttractoraProject/AttractoraVenv/lib/python3…
has title: Does neo4j desktop include a usable neo4j database
tagged with: python
tagged with: django

http://stackoverflow.com/comment/91046313
type: AnswerComment
type: Comment
score: 0
has text: Thanks a lot for all your answers. I think I have got this problem resolved. And I will try both within all your suggestions.
comment on: http://stackoverflow.com/a/52047585

http://stackoverflow.com/comment/91133948
has text: Maybe something like https://tinydb.readthedocs.io/en/latest/?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52085573
score: 1

http://stackoverflow.com/comment/90948689
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51998834
score: 0
has text: My question still stands. As you are apparently trying to convert `float64` to `uint32`, then how do you want to handle the conversion? If your `float64` is `5.6`, then what should the resulting `uint32` look like?

http://stackoverflow.com/comment/91141873
comment on: http://stackoverflow.com/q/52095109
score: 0
has text: As per your new requirement try [`(?:\[[^]]*]|\([^)[]*\[[^)]*\))`](https://regex101.com/r/iwup6M/3)
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51986493
tagged with: python-3.x
upvote count: 5
has answer: http://stackoverflow.com/a/51986594
tagged with: python
has comment: http://stackoverflow.com/comment/90922522
answer count: 4
has answer: http://stackoverflow.com/a/51986542
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51986544
has body: Suppose I have a list as such li = [1, 2, 3, 4, 5] and a scale function as def scale(data, factor): for j in range(len(data)): data[j] *= factor Now if I pass li to scale function with a factor = 2, my list gets modified. That is the actual parameter gets changed here. So if i print li after executing the above function it gives [2, 4, 6, 8, 10] and not the original one. Another way scale function is implemented is as follows:- def scale(data, factor): for val in data: val *= factor Now if I execute scale(li, 2) then it doesn't modify the actual parameter. So li stays as [1, 2, 3, 4, 5]. So my question is why does one modify the list and the other doesn't? Has this got anything to do with mutability or immutability?
linked to: http://stackoverflow.com/q/986006
type: Question
has title: Why does one function work and other don't ? How is the mutability or immutability working here?
has comment: http://stackoverflow.com/comment/90922566
score: 4
has answer: http://stackoverflow.com/a/51986668
accepted answer: http://stackoverflow.com/a/51986668
possible better answer: http://stackoverflow.com/a/51986544
downvote count: 1
favorite count: 0

http://stackoverflow.com/comment/90899017
score: 0
type: AnswerComment
has text: When mentioning performance, you should at least time your code.
type: Comment
comment on: http://stackoverflow.com/a/51974046

http://stackoverflow.com/q/51992072
has comment: http://stackoverflow.com/comment/90933838
has title: Websocket python flask update live template
downvote count: 0
favorite count: 0
type: UnansweredQuestion
upvote count: 1
tagged with: python
answer count: 0
score: 1
type: Question
has comment: http://stackoverflow.com/comment/90934252
has body: i wan to update live a template using flask websocket IO. So bassic i have some message and for each one i wan to transfer it to the socket: @socketio.on('message') def handleMessage(msg): print('Message: ' + msg) emit(msg, broadcast=True) @app.route('/run_script/&lt;script_name&gt;') def run_script(script_name): path_to_file = os.path.dirname(os.path.abspath(__file__)) + "/files/" + script_name command = "python " + path_to_file process_handle = Popen(command, shell=True, stdout=PIPE) while process_handle.poll() is None: for line in iter(process_handle.stdout.readline, ""): output = line.decode('utf-8') if output != '': print('Last message is: ' + output) handleMessage(output) return redirect("/admin/fileadmin/") And the javascript looks like this: $(document).ready(function() { var socket = io.connect('http://127.0.0.1:5000'); socket.on('connect', function() { socket.send('User has connected!'); }); socket.on('message', function(msg) { $("#messages").append('&lt;li&gt;'+msg+'&lt;/li&gt;'); console.log('Received message'); }); $('#sendbutton').on('click', function() { socket.send($('#myMessage').val()); $('#myMessage').val(''); }); But every time i try to send a message i receive the following error: AttributeError: 'Request' object has no attribute 'namespace' Can you help please?`[2018-08-23 21:37:51,855] ERROR in app: Exception on /run_script/TestScript.py [GET] Traceback (most recent call last): File "C:\Python27\lib\site-packages\flask\app.py", line 2292, in wsgi_app response = self.full_dispatch_request() File "C:\Python27\lib\site-packages\flask\app.py", line 1815, in full_dispatch_request rv = self.handle_user_exception(e) File "C:\Python27\lib\site-packages\flask\app.py", line 1718, in handle_user_exception reraise(exc_type, exc_value, tb) File "C:\Python27\lib\site-packages\flask\app.py", line 1813, in full_dispatch_request rv = self.dispatch_request() File "C:\Python27\lib\site-packages\flask\app.py", line 1799, in dispatch_request return self.view_funct…

http://stackoverflow.com/a/52011147
has comment: http://stackoverflow.com/comment/91081452
has comment: http://stackoverflow.com/comment/91080093
accepted answer of: http://stackoverflow.com/q/52010981
has comment: http://stackoverflow.com/comment/90974428
has comment: http://stackoverflow.com/comment/91080022
has comment: http://stackoverflow.com/comment/90973759
has comment: http://stackoverflow.com/comment/90974318
downvote count: 1
has comment: http://stackoverflow.com/comment/91080876
has comment: http://stackoverflow.com/comment/91081146
has comment: http://stackoverflow.com/comment/90974068
score: -1
has comment: http://stackoverflow.com/comment/90973994
has comment: http://stackoverflow.com/comment/90973726
upvote count: 0
type: AcceptedAnswer
has body: I want to make the parameter 'interests' into a tuple or a list. The user should be able to input many interests and decide when to stop through a flag such as 'active = True' I'm not sure how the user is going to set active=True, but the rest of that sentence just screams "I want a loop": @classmethod def get_userinfo(cls): first = raw_input("Welcome. PLease Enter Your First Name: ") last = raw_input("Please Enter Your Last Name: ") user = raw_input("Username: ") location = raw_input("What is your location? : ") interests = [] print("List some of your interests (just type Return on its own when you're done)") while True: interest = raw_input().strip() if not interest: break interests.append(interest) OK, that gives us a list, not a tuple. We could create a tuple by doing interests = interests + (interest,), but that's clunky and inefficient. If you really need a tuple, it's actually simpler to just build a list and then convert it at the end: interests = tuple(interests) And now we can pass all of those variables to the constructor: return cls(first, last, user, location, interests) … and then finally return the results as a string to be able to write it to the file. Hold on; what kind of file are you creating here? If this file is mean to be read and edited by a human being, and never looked at by Python again, that's easy. You can, e.g., just join them up with spaces, or commas, or newlines, or whatever you want. Or you can manually loop over them to format them more fancily: def write_to_file(self, filename): with open(filename, 'w') as file: file.write('First Name: {}\n'.format(self.first_name)) file.write('Last Name: {}\n'.format(self.last_name)) file.write('Username: {}\n'.format(self.username)) file.write('Location: {}\n'.format(self.location)) file.write('Interests:\n') for interest in self.interests: file.write(' {}\n'.format(interest)) But if it's meant to be used for storing data to be read later by Python, you want to write things in a format that's mea…
answers question: http://stackoverflow.com/q/52010981
has comment: http://stackoverflow.com/comment/90974440
type: Answer

http://stackoverflow.com/comment/90927585
type: QuestionComment
comment on: http://stackoverflow.com/q/51988051
has text: It s not the same as the previously opened questions because: The old questions give you a way to import a SINGLE csv file into postgres. But in my case, I want to automate the import of a very large number of files where there are 2 manual processes involved: 1. Create a new table 2. Import the csv into this new table. I want to accomplish these 2 steps in one procedure for multiple thousands of files through automation.
score: 0
type: Comment

http://stackoverflow.com/comment/90968171
score: 0
comment on: http://stackoverflow.com/q/52008638
type: QuestionComment
type: Comment
has text: i use ubuntu , i dont know whats going wrong because someone else generated a 20gb file without any problems

http://stackoverflow.com/comment/91012989
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52031203
score: 1
has text: Ah, that would explain it, I am using python 3. I changed it and it now works, thanks!

http://stackoverflow.com/q/52056472
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91064060
tagged with: python
tagged with: pygame
linked to: http://stackoverflow.com/q/16183265
has body: So, I've used another answer to help me figure out an easy way into moving my player sprite in pygame. The only issue is that the buttons for movement have to be spammed in order for the sprite to move more than the five pixels specified every time the button is pressed. Here's the code in full. The areas in question are the Player() class and the " player." areas in the loop: import pygame player_path = "downChara.png" #specifies image path class Player(object): #representitive of the player's overworld sprite def __init__(self): self.image = pygame.image.load(player_path).convert_alpha() #creates image, the player_path variable allowing it to be updated self.X = 284; # x co-ord of player self.Y = 184; # y co-ord of player def handle_keys(self): #handling the keys/inputs key = pygame.key.get_pressed() dist = 5 #distance travelled in one frame of the program if key[pygame.K_DOWN]: #if down self.Y += dist #move down the length of dist player_path = "downChara.png" #change image to down self.image = pygame.image.load(player_path).convert_alpha() elif key[pygame.K_UP]: #if up self.Y -= dist #move up the length of dist player_path = "upChara.png" #change to up self.image = pygame.image.load(player_path).convert_alpha() if key[pygame.K_RIGHT]: #etc. self.X += dist player_path = "rightChara.png" self.image = pygame.image.load(player_path).convert_alpha() elif key[pygame.K_LEFT]: self.X -= dist player_path = "leftChara.png" self.image = pygame.image.load(player_path).convert_alpha() def draw(self, surface): #draw to the surface/screen surface.blit(self.image, (self.X, self.Y)) pygame.init() (width, height) = (600, 400) #specify window resolution bg_colour = (100,20,156) #specify bg colour screen = pygame.display.set_mode((width, height)) #create window pygame.display.set_caption('EduGame') #specify window name player = Player() clock = pygame.time.Clock() pygame.display.flip() #paints screen gameRun = True #allow game events to loop/be carried out more than once while game…
has comment: http://stackoverflow.com/comment/91063755
downvote count: 1
type: Question
has title: Able to get image to move in Pygame; but I have to keep on pressing the button to make it move
upvote count: 0
has answer: http://stackoverflow.com/a/52074109
answer count: 1
favorite count: 0
score: -1

http://stackoverflow.com/q/52089832
accepted answer: http://stackoverflow.com/a/52089871
favorite count: 0
tagged with: python-3.x
upvote count: 2
tagged with: python
score: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91129635
has body: I'm going through the book Python Crash Course and I'm stuck at the example given in the book. I even copy - pasted the script from the book and still got an error. File called car.py """A class that can be used to represent a car.""" class Car(): """A simple attempt to represent a car.""" def __init__(self, make, model, year): """Initialize attributes to describe a car.""" self.make = make self.model = model self.year = year self.odometer_reading = 20 def get_descriptive_name(self): """Return a neatly formatted descriptive name.""" long_name = str(self.year) + " " + self.make +\ " " + self.model return long_name.title() def read_odometer(self): """Print a statement showing the car's mileage""" print("This car has " + str(self.odometer_reading) + " miles on it.") def update_odometer(self, mileage): """ Set the odometer reading to the given value. Reject the change if it attempts to roll the odometer back. """ if mileage &gt;= self.odometer_reading: self.odometer_reading = mileage else: print("You can't roll back an odometer!") def increment_odometer(self, miles): """Add the given amount to the odometer reading.""" self.odometer_reading += miles class Battery(): """A simple attempt to model a battery for an electric car.""" def __init__(self, battery_size=60): """Initialize the battery's attributes.""" self.battery_size = battery_size def describe_battery(self): """Print a statement describing the battery size.""" print("This car has a " + str(self.battery_size) + "-kWh battery.") def get_range(self): """Print a statement about the range this battery provides.""" if self.battery_size == 70: range = 240 elif self.battery_size == 85: range = 270 message = "This car can go approximately " + str(range) message += " miles on a full charge." print(message) class ElectricCar(Car): """Models aspects of a car, specific to electric vehicles.""" def __init__(self, make, model, year): """ Initialize attributes of the parent class. Then initialize attributes specific to an electr…
type: Question
has answer: http://stackoverflow.com/a/52089871
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/91129651
has title: Python Crash Course - Chapter 9 my_electric_car - problem with get_range()

http://stackoverflow.com/comment/91146178
type: QuestionComment
type: Comment
has text: I thought I figured it out and wrote the answer while I was running the tests. Still failed, even with the adjustments :-(
score: 0
comment on: http://stackoverflow.com/q/52097869

http://stackoverflow.com/comment/91050785
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/52050108
score: 0
has text: Does this seem like a suitable solution? [Json dumps escaping forward slashes](https://stackoverflow.com/questions/27129681/json-dumps-escaping-forward-slashes)

http://stackoverflow.com/comment/91149510
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52098893
score: 0
has text: Yes .. please keep in mind in both the directory files are in millions and have to search for all files to match ..

http://stackoverflow.com/comment/95778341
score: 1
comment on: http://stackoverflow.com/a/51959828
type: AnswerComment
has text: It works! In my case a had an `Enum`, which values were `gettext_lazy`. The string representations of the values were displayed on admin site as read-only values. Replacing `gettext_lazy` with `gettext` fixed the issue.
type: Comment

http://stackoverflow.com/a/52169052
type: Answer
has body: For zipping directories I have always used the zipfile module, and used it like so; import zipfile def zip(src, dst): zf = zipfile.ZipFile("%s.zip" % (dst), "w", zipfile.ZIP_DEFLATED) abs_src = os.path.abspath(src) for dirname, subdirs, files in os.walk(src): for filename in files: absname = os.path.abspath(os.path.join(dirname, filename)) arcname = absname[len(abs_src) + 1:] print('zipping %s as %s' % (os.path.join(dirname, filename), arcname)) zf.write(absname, arcname) zf.close() Then called with this; zip(str(source), str(destination))
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/51967818
downvote count: 0

http://stackoverflow.com/q/51968493
has comment: http://stackoverflow.com/comment/90891159
has body: I have the following dataframe 01/01/2017 02/01/2017 Productid ProductName Sales Discount Sales Discount 1 abc 100 12 234 23 2 xyz 156 13 237 13 3 pqr 300 12 198 18 I need to convert this into the following dataframe. Productid ProductName Date Sales Discount 1 abc 01/01/2017 100 12 1 abc 02/01/2017 234 23 2 xyz 01/01/2017 156 13 2 xyz 02/01/2017 237 13 3 pqr 01/01/2017 300 12 3 pqr 02/01/2017 198 18 How can I do this in Python?
accepted answer: http://stackoverflow.com/a/51982443
has comment: http://stackoverflow.com/comment/90924037
type: Question
downvote count: 4
answer count: 1
has title: Pivot/ Unstack a Pandas Dataframe in Python
tagged with: pandas
has answer: http://stackoverflow.com/a/51982443
has comment: http://stackoverflow.com/comment/90887331
tagged with: python
favorite count: 0
linked to: http://stackoverflow.com/q/47152691
has comment: http://stackoverflow.com/comment/90887312
tagged with: pivot
has comment: http://stackoverflow.com/comment/90914645
score: -3
upvote count: 1
type: AnsweredQuestion

http://stackoverflow.com/q/52013552
has comment: http://stackoverflow.com/comment/90994540
accepted answer: http://stackoverflow.com/a/52023931
linked to: http://stackoverflow.com/q/1787110
score: 0
answer count: 1
favorite count: 0
has body: from stemming.porter2 import stem documents = ['got',"get"] documents = [[stem(word) for word in sentence.split(" ")] for sentence in documents] print(documents) The result is : [['got'], ['get']] Can someone help to explain this ? Thank you !
has title: Why the stem of word "got " is still "got" instead of "get"?
tagged with: python
linked to: http://stackoverflow.com/q/17317418
downvote count: 1
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90977853
linked to: http://stackoverflow.com/q/22333392
tagged with: stem
type: Question
upvote count: 1
tagged with: nltk
has answer: http://stackoverflow.com/a/52023931

http://stackoverflow.com/q/52004804
has title: Heroku cannot import name 'login'
favorite count: 0
has comment: http://stackoverflow.com/comment/90960151
tagged with: python
linked to: http://stackoverflow.com/q/51906428
answer count: 0
has body: Since I deployed my django application to heroku I am getting an error when opening the project. It works just fine localy but after pushing to django the following error is appearing: ImportError at / cannot import name 'login' Request Method: GET Request URL: https://blooming-headland-56472.herokuapp.com/ Django Version: 2.1 Exception Type: ImportError Exception Value: cannot import name 'login' Exception Location: /app/Clientes/urls.py in &lt;module&gt;, line 5 Python Executable: /app/.heroku/python/bin/python Python Version: 3.6.6 Python Path: ['/app/.heroku/python/bin', '/app', '/app/.heroku/python/lib/python36.zip', '/app/.heroku/python/lib/python3.6', '/app/.heroku/python/lib/python3.6/lib-dynload', '/app/.heroku/python/lib/python3.6/site-packages'] Server time: Sex, 24 Ago 2018 11:32:30 +0000 My urls.py looks like this: from django.urls import path from . import views from django.conf import settings from django.contrib.auth import views as auth_views from django.contrib.auth.views import ( login, logout, password_reset, password_reset_done, password_reset_confirm ) from django.conf.urls.static import static app_name = 'client' urlpatterns = [ path('register/', views.register, name='register'), path('login/', login, {'template_name': 'Clientes/login.html'}, name='login'), path('mail/', views.mail, name='mail'), path('profile/config', views.config_view, name="config"), path('profile/dashboard', views.dashboard_view, name="dashboard"), path('reset-password/', password_reset, name="reset_password"), path('reset-password/done/', password_reset_done, name="password_reset_done"), path('reset-password/confirm/', password_reset_confirm, name="password_reset_confirm"), path('profile/logout/', views.logout_view, name='logout'), path('profile/', views.ProfileView.as_view(), name='profile'), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
type: UnansweredQuestion
upvote count: 1
tagged with: django
duplicate of: http://stackoverflow.com/q/51906428
tagged with: heroku
score: 1
type: Question
has comment: http://stackoverflow.com/comment/90959131
downvote count: 0

http://stackoverflow.com/comment/91084204
comment on: http://stackoverflow.com/q/52066916
type: Comment
type: QuestionComment
score: 0
has text: Have you tried including `encoding = utf-16`?

http://stackoverflow.com/q/52081551
type: AnsweredQuestion
upvote count: 0
has comment: http://stackoverflow.com/comment/91113749
type: Question
possible better answer: http://stackoverflow.com/a/52081683
score: -1
has answer: http://stackoverflow.com/a/52081683
tagged with: class
has body: So, I'm working on a command line RPG for the sake of filling time, and re-stretching my Python muscles as I've been out of practice for a couple of years. I used to code in a really functional manner but I'm trying to get my head around object-orientated programming. Preamble aside, I have an issue where after creating an instance of a class, my class variable is no longer being defined. I've made 2 versions of this which I'll use to demonstrate since I'm finding it hard to articulate. Below I created a "character" class which I intended to use as a basis for both player characters and npcs. In the first draft I was updating this class, before realising it was going to affect subclasses, when I really just wanted it as a template. Either way, this particular code block worked; it adds the values of 2 dictionaries together, then assigns them to character.characterStats. It then prints them as per displayStats(). from collections import Counter class character: def __init__(self, *args, **kwargs): pass def __setattr__(self, name, value): pass characterRace = '' characterStats = {} charLocation = '' charName = '' class race: def __init__(self): pass baseStatsDict = { 'Strength' : 5, 'Agility' : 5, 'Toughness' : 5, 'Intelligence' : 5 } humanStatsDict = { 'Strength' : 1, 'Agility' : 1, 'Toughness' : 1, 'Intelligence' : 1 } def displayRace(): print("Race: ", character.characterRace, "\n") def displayStats(): for stat, value in character.characterStats.items(): print(stat, "=", value) print("\n") def raceSelection(): playerInput = input("I am a ") playerInput playerLower = playerInput.lower() while "human" not in playerLower: if "human" in playerLower: character.characterStats = dict(Counter(race.baseStatsDict)+Counter(race.humanStatsDict)) character.characterRace = 'Human' break playerInput = input() playerInput playerLower = playerInput.lower() playerChar = character() raceSelection() displayRace() displayStats() And this was the output: Race: Human Strength = 6 Agility…
answer count: 2
downvote count: 1
tagged with: undefined
tagged with: variables
has comment: http://stackoverflow.com/comment/91114070
favorite count: 0
has answer: http://stackoverflow.com/a/52091100
accepted answer: http://stackoverflow.com/a/52091100
tagged with: python
has title: Variable within an instance of a class does not take a new value when it is assigned.

http://stackoverflow.com/q/51957231
has title: Spatial join in geopandas when overlapping polygons?
has body: I have two datasets, one with points (shops) and one with polygons (districts). The districts dataset sometimes has overlapping polygons (as I have buffered them). I want to know if each polygon has any matching points? joined = geopandas.sjoin(districts,shops, op='contains', how='inner') joined The above code probably give me only one of the matching polygons. How do I check each polygon?
type: Question
downvote count: 0
has comment: http://stackoverflow.com/comment/93108991
tagged with: geopandas
answer count: 1
has answer: http://stackoverflow.com/a/69571285
favorite count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91157718
tagged with: python
score: 3
upvote count: 3
has comment: http://stackoverflow.com/comment/90865132

http://stackoverflow.com/comment/91122152
type: QuestionComment
comment on: http://stackoverflow.com/q/52085839
has text: @NChauhan Won't work with dicts!
score: 1
type: Comment

http://stackoverflow.com/a/51964033
upvote count: 1
score: 1
downvote count: 0
type: Answer
has body: int does not care about newline characters, so you can skip stripping those. &gt;&gt;&gt; fake_file = '3 8 6 9 4\n4 3 0 8 6\n2 8 3 6 9\n3 7 9 0 3\n'.splitlines() &gt;&gt;&gt; [[int(x) for x in line.split()] for line in fake_file] [[3, 8, 6, 9, 4], [4, 3, 0, 8, 6], [2, 8, 3, 6, 9], [3, 7, 9, 0, 3]] Note that pandas and numpy offer high level functions for reading in data such as this, e.g. numpy.loadtxt or pandas.read_csv.
answers question: http://stackoverflow.com/q/51963942

http://stackoverflow.com/comment/117549167
type: Comment
has text: It should be noted that the only [allowed values](https://docs.python.org/3/library/functions.html#open) for the `newline` argument are `None`, `''`, `'\n'`, `'\r'`, and `'\r\n'`. This may bite you when lines in your file are separated by one of the various [Unicode newline characters](https://en.wikipedia.org/wiki/Newline#Unicode).
score: 3
type: AnswerComment
comment on: http://stackoverflow.com/a/51981438

http://stackoverflow.com/comment/91041627
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52045288
score: 0
has text: The "yields" looks like it's part of a test case name; you shouldn't actually use `yield` here.

http://stackoverflow.com/comment/90960052
type: QuestionComment
comment on: http://stackoverflow.com/q/52005234
has text: If the code still works then it might be more appropriate to migrate this to Code Review.
type: Comment
score: 0

http://stackoverflow.com/a/51990035
type: Answer
has body: The code does not "append every dictionary mapping". It only appends anything for letters found in opening. What gets appended is the counterpart from closing. It will quite often return the queue to [], because it does also a lot of pop(), which reomves a letter. The pop() occurs when the current letter from input matches the last appended letter, i.e. when a recently opened pair gets closed. So for example, the queue is [] at these positions for the following input: vvv vvv vvv vvv vvvvv abc(xxxx)fg[....]hi{llll}gh(--[ff]++)gggg Note, as also mentioned in the comments, queue behaves more like a stack here, and rightly so.
accepted answer of: http://stackoverflow.com/q/51989660
answers question: http://stackoverflow.com/q/51989660
upvote count: 1
score: 1
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/98660357
type: QuestionComment
has text: @GordThompson I've edited my question quite a bit, it should be a lot clearer now. Please check it out :)
comment on: http://stackoverflow.com/q/52052296
score: 0
type: Comment

http://stackoverflow.com/comment/90953414
has text: @SyafiqurRahman Please elaborate your requirement next time as you will get what you need soon.
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52002011

http://stackoverflow.com/q/52089405
score: 0
answer count: 1
type: UnansweredQuestion
tagged with: classname
has comment: http://stackoverflow.com/comment/91128874
tagged with: python
tagged with: isinstance
has answer: http://stackoverflow.com/a/60960341
has comment: http://stackoverflow.com/comment/91129011
type: Question
has comment: http://stackoverflow.com/comment/91133500
has title: use isinstance() cannot check python object class import other module
has body: class A: somemethod class A in module m1 in module m2 I want to use isinstance() to check object obj1 is or not class A and obj1 = A() but isinstance(obj1,A) is False....type(obj1) == &lt;class, m1.A&gt; I can't understand why? help me

http://stackoverflow.com/q/52010752
type: Question
score: 0
has body: Actually I wrote a code to find a character from the list and print the index but am not getting the difference between these two codes please help me out: #My list: l = ["MA-%78*%%1","MA%-78*%1","MA%%-%78*1","M%A#-78*%%1"] search(l,"%") Code 1: def search(string_list,search_character): sl = string_list char1 = search_character l1 = list() l11 = list() for j in range(len(string_list)): l1.clear() s1 = string_list[j] for i in range(len(s1)): if s1[i] == search_character: l1.append(i+1) l11.append(l1) return l11 This yields the output: [[1, 8, 9], [1, 8, 9], [1, 8, 9], [1, 8, 9]] Code 2: def search(string_list,search_character): sl = string_list char1 = search_character l11 = list() for j in range(len(string_list)): l1 = list() s1 = string_list[j] for i in range(len(s1)): if s1[i] == search_character: l1.append(i+1) l11.append(l1) return l11 I get correct output when I initialized the list again without clearing it: [[4, 8, 9], [3, 8], [3, 4, 6], [2, 9, 10]] I didn't understood what is wrong with l1.clear() function.
answer count: 1
has comment: http://stackoverflow.com/comment/90972500
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/240178
tagged with: python
has answer: http://stackoverflow.com/a/52010859
has title: list initialization VS list clear in python
has comment: http://stackoverflow.com/comment/90972499
duplicate of: http://stackoverflow.com/q/240178
has comment: http://stackoverflow.com/comment/90973372

http://stackoverflow.com/comment/91054597
type: QuestionComment
score: 1
has text: the new line is only for raw HTTP exchanges. The python client simply uses a list and will add the newline character when building the HTTP request.
comment on: http://stackoverflow.com/q/52052187
type: Comment

http://stackoverflow.com/comment/90899352
type: Comment
has text: Do I get it right you want to turn `B.2017ZZZZ.8` into `B2017ZZZZ8`? Try `.replace(r'\W+|(?<!\d)[^\W\d_](?!\S*\d)', '')`
comment on: http://stackoverflow.com/q/51973529
score: 0
type: QuestionComment

http://stackoverflow.com/q/51998504
accepted answer: http://stackoverflow.com/a/51998635
tagged with: pandas
answer count: 1
downvote count: 0
favorite count: 0
tagged with: python
has body: I am printing a list of DataFrames along with their plots using the following code: from IPython.core.display import display ... for df in list_df: df.plot() display(df) The desired outcome is that each df's plot and data are next to each other. However, when I run the code, in the output of the cell all the df data are first displayed and then all the plots of dfs. How can I get what I want?
has title: Python - How can I make DataFrame plots not always printed at the bottom of a cell output?
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51998635
score: 1
tagged with: matplotlib
upvote count: 1
tagged with: ipython
type: Question

http://stackoverflow.com/q/52018196
tagged with: django
accepted answer: http://stackoverflow.com/a/52020979
type: Question
has comment: http://stackoverflow.com/comment/91193643
has comment: http://stackoverflow.com/comment/90986597
score: 1
has body: I'm trying to run manage.py server but it hit some error! I've just trying to print hello in web but it insn't working (venv) ubuntu@node:~/PycharmProjects/Oin$ python manage.py runserver Performing system checks... Unhandled exception in thread started by &lt;function check_errors.&lt;locals&gt;.wrapper at 0x7fd985430158&gt; Traceback (most recent call last): File "/home/ubuntu/PycharmProjects/Oin/venv/lib/python3.4/site-packages/django/urls/resolvers.py", line 542, in url_patterns iter(patterns) TypeError: 'module' object is not iterable During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/home/ubuntu/PycharmProjects/Oin/venv/lib/python3.4/site-packages/django/utils/autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "/home/ubuntu/PycharmProjects/Oin/venv/lib/python3.4/site-packages/django/core/management/commands/runserver.py", line 120, in inner_run self.check(display_num_errors=True) File "/home/ubuntu/PycharmProjects/Oin/venv/lib/python3.4/site-packages/django/core/management/base.py", line 364, in check include_deployment_checks=include_deployment_checks, File "/home/ubuntu/PycharmProjects/Oin/venv/lib/python3.4/site-packages/django/core/management/base.py", line 351, in _run_checks return checks.run_checks(**kwargs) File "/home/ubuntu/PycharmProjects/Oin/venv/lib/python3.4/site-packages/django/core/checks/registry.py", line 73, in run_checks new_errors = check(app_configs=app_configs) File "/home/ubuntu/PycharmProjects/Oin/venv/lib/python3.4/site-packages/django/core/checks/urls.py", line 13, in check_url_config return check_resolver(resolver) File "/home/ubuntu/PycharmProjects/Oin/venv/lib/python3.4/site-packages/django/core/checks/urls.py", line 23, in check_resolver return check_method() File "/home/ubuntu/PycharmProjects/Oin/venv/lib/python3.4/site-packages/django/urls/resolvers.py", line 400, in check warnings.extend(check_resolver(pattern)) File "/home/ubuntu/PycharmProjects/Oin/venv/li…
has comment: http://stackoverflow.com/comment/90992322
has title: Django is not able to run manage.py runserver how to solve?
has comment: http://stackoverflow.com/comment/90986992
answer count: 2
possible better answer: http://stackoverflow.com/a/52018253
upvote count: 1
has answer: http://stackoverflow.com/a/52018253
favorite count: 0
tagged with: python
has comment: http://stackoverflow.com/comment/91315091
type: AnsweredQuestion
tagged with: pycharm
downvote count: 0
has comment: http://stackoverflow.com/comment/90992220
has answer: http://stackoverflow.com/a/52020979

http://stackoverflow.com/a/52051555
accepted answer of: http://stackoverflow.com/q/52051521
answers question: http://stackoverflow.com/q/52051521
type: Answer
has body: Create list of DataFrames and then join them together by concat, last convert to nested lists: results=[] for filename in glob.glob(os.path.join('/path/*.csv')): df = pd.read_csv(filename) #filter by conditions and also columns by names with .loc filtered = df.loc[(df['duration'] &gt; low1) &amp; (df['duration'] &lt; high1), ['artist','track']] #alternative solution filtered = df.loc[df['duration'].between(low1, high1,inclusive=False), ['artist','track']] results.append(filtered) out = pd.concat(results).values.tolist() Another solution id append lists and last flattening them by list comprehension: results=[] for filename in glob.glob(os.path.join('/path/*.csv')): df = pd.read_csv(filename) #filter by conditions and also columns by names with .loc mask = df['duration'].between(low1, high1,inclusive=False) filtered = df.loc[mask, ['artist','track']].values.tolist() results.append(filtered) out = [y for x in results for y in x]
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/91053397
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/52072938
accepted answer: http://stackoverflow.com/a/52073240
has answer: http://stackoverflow.com/a/65535701
has body: I made this code to open the pi camera and to close it. When i run the code it makes .h264 videos but i can't play these on windows. Heres the code import picamera from time import * from subprocess import call with picamera.PiCamera() as camera: camera.start_recording("beepvid.h264") sleep(5) camera.stop_recording()
has comment: http://stackoverflow.com/comment/91095707
has comment: http://stackoverflow.com/comment/91095802
possible better answer: http://stackoverflow.com/a/65535701
score: 0
answer count: 2
linked to: http://stackoverflow.com/q/45040261
favorite count: 0
tagged with: python
type: AnsweredQuestion
has title: Converting my .h264 video (python)
has comment: http://stackoverflow.com/comment/91095796
upvote count: 1
downvote count: 1
has answer: http://stackoverflow.com/a/52073240
type: Question

http://stackoverflow.com/q/52037166
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91024752
duplicate of: http://stackoverflow.com/q/41918836
accepted answer: http://stackoverflow.com/a/52037316
type: Question
linked to: http://stackoverflow.com/q/41950021
answer count: 1
has comment: http://stackoverflow.com/comment/91024822
tagged with: serial-port
has comment: http://stackoverflow.com/comment/91050730
has answer: http://stackoverflow.com/a/52037316
has comment: http://stackoverflow.com/comment/91024701
has comment: http://stackoverflow.com/comment/91025033
has title: In the python serial port program, What should I do with 'b'?
has comment: http://stackoverflow.com/comment/91050703
has comment: http://stackoverflow.com/comment/91024988
score: 0
duplicate of: http://stackoverflow.com/q/20449427
tagged with: python
has body: The serial port program attempted to print the data from the Python Let me show you the code I used. import serial import time ser =serial.Serial(port="COM1", baudrate=926100, bytesize=serial.EIGHTBITS, parity=serial.PARITY_NONE, timeout=20) ser.isOpen() ## open port print ("Sensortag's connected Succesfully!.") while 1: res1 =ser.readline() res3=res1[13:21] time.sleep(1.0) if res3 &gt;=250: print("Sensor has invalid value Please wait a moment.") elif res3 &lt; 250 &amp; res3&gt;=200: print("The user's movements are abnormal. Please check.") else: print("The user Your movements are normal.") print(res3) First of all, what I want is to print numbers in a program and see if they exceed a certain range.But here's the problem. Traceback (most recent call last): File "C:\Users\SEOI\AppData\Local\Programs\Python\Python37-32\ㅋㅋㅋㅋ.py", line 37, in &lt;module&gt; if res3 &gt;=250: ## 3).When UART outputs a value, it outputs the required parts TypeError: '&gt;=' not supported between instances of 'bytes' and 'int' In the following questions, you have identified an error because the value i can receive in the program is not numeric However, it is not possible to know how 'b' should remove the part from the part that is output from the file We used sliding to solve the following problem, but 'b' as shown in the picture has been output. I'll attach the picture to the printout section of B mentioned above. ++)I just checked, and I can't see the image of B in the right direction, so I'll leave it in writing. b'0253.787' b'0261.909' b'0268.000' b'0263.939' b'0261.909' b'0259.878' b'0257.848' b'0255.818' b'0253.787' b'0290.333' b'0282.212' b'0276.121' b'0270.030' b'0265.969' b'0263.939' b'0261.909' b'0259.878' b'0261.909' b'0263.939' b'0261.909' b'0259.878' b'0257.848' b'0255.818' b'0253.787' b'0300.484' b'0485.242' b'0633.454'

http://stackoverflow.com/q/51991188
accepted answer: http://stackoverflow.com/a/51991292
score: 1
has comment: http://stackoverflow.com/comment/90932243
duplicate of: http://stackoverflow.com/q/25336726
type: Question
has title: why zipping the result of a function and iterable does not work?
answer count: 2
has comment: http://stackoverflow.com/comment/90932248
downvote count: 0
favorite count: 0
tagged with: process-pool
has comment: http://stackoverflow.com/comment/90932340
has body: So I had the following code which works fine: from concurrent.futures import ProcessPoolExecutor import itertools def grid_search_helper(vec_input): v1 = vec_input[0] v2 = vec_input[1] v3 = vec_input[2] d = {'v1' : v1, 'v2' : v2, 'v3' : v3} return(d) idx = range(0,10) cutoff = np.ndarray.tolist(np.arange(0.6,0.95,0.05)) opt = [2] iters = itertools.product(idx, cutoff, opt) with ProcessPoolExecutor(max_workers = 11) as executor: for res in executor.map(grid_search_helper,iters): print(res) Then I tried zip() to print the iterable that ProcessPoolExecuter is working on, however nothing is printed when I run the following code: from concurrent.futures import ProcessPoolExecutor import itertools def grid_search_helper(vec_input): v1 = vec_input[0] v2 = vec_input[1] v3 = vec_input[2] d = {'v1' : v1, 'v2' : v2, 'v3' : v3} return(d) idx = range(0,10) cutoff = np.ndarray.tolist(np.arange(0.6,0.95,0.05)) opt = [2] iters = itertools.product(idx, cutoff, opt) with ProcessPoolExecutor(max_workers = 11) as executor: for res, itr in zip(executor.map(grid_search_helper,iters), iters): print(res, itr) I cannot figure out why. Can anybody help?
has answer: http://stackoverflow.com/a/51991292
tagged with: python
has answer: http://stackoverflow.com/a/51991309
upvote count: 1
possible better answer: http://stackoverflow.com/a/51991309
tagged with: parallel-processing
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/25336726
tagged with: python-itertools

http://stackoverflow.com/comment/91043826
comment on: http://stackoverflow.com/q/52046224
has text: It's also unclear what you mean by "keep the class variable values". Do you want it to *be* a `Salmon`, but still be able to *call* `some_special_trout_method` on it, despite the fact that it is no longer a `Trout`? If so, what about it is really "`Salmon`y" if it's still supposed behave like a `Trout`?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52084506
tagged with: py-telegram-bot-api
type: Question
has answer: http://stackoverflow.com/a/55139944
has body: Trying to build a Telegram Quiz Bot using pyTelegramBotAPI. I'm using sched to schedule the message Handler but i don't know how to stop the Message Handler and return to my Main Script which will scheudle the next Round. Tryed to use timeout but it is not working! My Code: import telebot import sched, time def listen(): print("Send my your Answer") @bot.message_handler(func=lambda message: True, content_types=['text']) def command_default(m): print(m.text) bot.polling() API_TOKEN = 'xxxx' s = sched.scheduler(time.time, time.sleep) bot = telebot.TeleBot(API_TOKEN) s.enter(50, 1, listen) s.run()
score: 0
answer count: 1
has title: Telegram Quiz Bot with pyTelegramBotAPI
tagged with: telegram
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/q/51959304
accepted answer: http://stackoverflow.com/a/51959523
has body: I'm trying to use python huey (https://github.com/coleifer/huey/blob/master/huey/api.py) to allow usage of a task queue with flask. Starting with a function: def some_long_calculation(): driver = create_chromedriver(True) print(driver.capabilities['version']) driver.get("https://www.yahoo.com/news/") I import it into the tasks.py file and turn into into a task function with: from . import my_huey some_long_calculation_task = my_huey.task(some_long_calculation) I then import some_long_calculation_task into main/views.py and try to run it with: @main.route('/sanity_check') def sanity_check(): png = some_long_calculation_task() return send_file(io.BytesIO(png),mimetype='image/png') but I get: traceback (most recent call last): File "...lib\site-packages\flask\app.py", line 1994, in __call__ return self.wsgi_app(environ, start_response) File "...lib\site-packages\flask\app.py", line 1985, in wsgi_app response = self.handle_exception(e) File "...lib\site-packages\flask\app.py", line 1540, in handle_exception reraise(exc_type, exc_value, tb) File "...lib\site-packages\flask\_compat.py", line 33, in reraise raise value File "...lib\site-packages\flask\app.py", line 1982, in wsgi_app response = self.full_dispatch_request() File "...lib\site-packages\flask\app.py", line 1614, in full_dispatch_request rv = self.handle_user_exception(e) File "...lib\site-packages\flask\app.py", line 1517, in handle_user_exception reraise(exc_type, exc_value, tb) File "...lib\site-packages\flask\_compat.py", line 33, in reraise raise value File "...lib\site-packages\flask\app.py", line 1612, in full_dispatch_request rv = self.dispatch_request() File "...lib\site-packages\flask\app.py", line 1598, in dispatch_request return self.view_functions[rule.endpoint](**req.view_args) File "...app\main\views.py", line 123, in sanity_check png = some_long_calculation_task() TypeError: decorator() missing 1 required positional argument: 'func' &gt;&gt;&gt; some_long_calculation_task &lt;function Huey.task.&…
tagged with: python
type: AnsweredQuestion
has title: TypeError: decorator() missing 1 required positional argument: 'func'
type: Question
has answer: http://stackoverflow.com/a/51959523
score: 0
tagged with: python-huey
answer count: 1

http://stackoverflow.com/q/52044120
type: Question
linked to: http://stackoverflow.com/q/3389574
has answer: http://stackoverflow.com/a/52044157
score: 0
answer count: 2
tagged with: python-3.7
tagged with: python-3.x
has body: I'm fairly new to python, and I've started creating a little script that saves a user's name into a text file. I want to have a list of blacklisted characters that can't appear in one's name, but I only manage to not let the blacklisted characters BE the name. How can I do this? Name = input("What is your name?\n") NameDoc = open("Name.txt", "w") Black_List = ["B", "A"] if Name in Black_List: print("Blacklisted Name") elif len(Name) &gt; 10: print("Sorry, 10 characters max!") else: NameDoc.write(Name) NameDoc.close() Name2 = open("Name.txt", "r") print("Name accepted!") print("Hello " + Name2.read()) Name2.close() try: NameDoc.close() except: pass
type: UnansweredQuestion
tagged with: python
has title: Blacklisting Certain Characters in Python
duplicate of: http://stackoverflow.com/q/3389574
has answer: http://stackoverflow.com/a/52044198

http://stackoverflow.com/comment/90965212
type: Comment
type: QuestionComment
has text: Thank you. That got me part of the way there. I will outline how it was used in an answer.
comment on: http://stackoverflow.com/q/52004350
score: 0

strftime
type: Tag
tag name: strftime
tags question: http://stackoverflow.com/q/51962778

http://stackoverflow.com/q/52105455
tagged with: python
has comment: http://stackoverflow.com/comment/91183459
has comment: http://stackoverflow.com/comment/91162062
has body: I have a large data frame of at least 500 rows and 60 columns. Let's call this df1. Some cells have NaN in them, which I've typically used df2 = df1.fillna(value = 0.0) in order to replace them in just one line of code. But this is with much, much smaller dataframes, where it worked in the past, and I would like to implement the same step on larger volumes of data in the future. Using the above command goes above my recursion limit. I've also tried to increase the recursion limit, and my program would crash as a result. My initial recursion limit is: sys.getrecursionlimit() 1000 Then increasing it with sys.setrecursionlimit(10000) and running fillna() afterwards makes my program crash. In order to work around recursion and rather make this command work iteratively, I created this loop: for index, row in sdd_root_excel.iterrows(): if(pd.isnull(row[index])): sdd_root_excel.iloc[index].fillna(0) But I get an error message that to my interpretation looks like it's telling me that an index (which is 711?) is out of bounds, and it's also interpreted as a KeyError: Traceback (most recent call last): File "C:\Users\isabel.wingert\Anaconda3\lib\site-packages\pandas\core\indexes\base.py", line 3103, in get_value tz=getattr(series.dtype, 'tz', None)) File "pandas\_libs\index.pyx", line 106, in pandas._libs.index.IndexEngine.get_value File "pandas\_libs\index.pyx", line 114, in pandas._libs.index.IndexEngine.get_value File "pandas\_libs\index.pyx", line 162, in pandas._libs.index.IndexEngine.get_loc File "pandas\_libs\hashtable_class_helper.pxi", line 1492, in pandas._libs.hashtable.PyObjectHashTable.get_item File "pandas\_libs\hashtable_class_helper.pxi", line 1500, in pandas._libs.hashtable.PyObjectHashTable.get_item KeyError: 711 During handling of the above exception, another exception occurred: Traceback (most recent call last): File "&lt;stdin&gt;", line 2, in &lt;module&gt; File "C:\Users\isabel.wingert\Anaconda3\lib\site-packages\pandas\core\series.py", line 766, in __g…
upvote count: 1
has comment: http://stackoverflow.com/comment/91181504
tagged with: recursion
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91162040
has title: Pandas -- iterrows for fillna()
has comment: http://stackoverflow.com/comment/91183512
tagged with: pandas
answer count: 0
downvote count: 0
has comment: http://stackoverflow.com/comment/91183548
score: 1
has comment: http://stackoverflow.com/comment/91162086
favorite count: 0
tagged with: iteration
tagged with: fillna
type: Question
has comment: http://stackoverflow.com/comment/91186648
has comment: http://stackoverflow.com/comment/91165043

http://stackoverflow.com/a/51983885
type: Answer
has body: Use groupby and chain from itertools Ex: from itertools import groupby, chain lst = [[1],[2],[3,4],[5,6],[7,8,9,10,11],[12,13,14,15,16],[17]] result = [list(chain.from_iterable(v)) for k, v in groupby(sorted(lst, key=lambda h: len(h)), lambda x: len(x))] print(result) Output: [[1, 2, 17], [3, 4, 5, 6], [7, 8, 9, 10, 11, 12, 13, 14, 15, 16]] sorted(lst, key=lambda h: len(h)) to sort your list by len then use groupby to group your list by len of list
accepted answer of: http://stackoverflow.com/q/51983817
answers question: http://stackoverflow.com/q/51983817
score: 5
upvote count: 5
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/91012510
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52030945
score: 1
has text: It's an interesting problem though, I will give it a try.

http://stackoverflow.com/comment/91022339
type: Comment
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/52035565
has text: If the enemy sprites should fire at a moving target (the player), check out [this answer](https://stackoverflow.com/a/50350184/6220679).

http://stackoverflow.com/a/52096469
has comment: http://stackoverflow.com/comment/91143403
upvote count: 3
score: 3
accepted answer of: http://stackoverflow.com/q/52096432
has comment: http://stackoverflow.com/comment/91143341
answers question: http://stackoverflow.com/q/52096432
type: AcceptedAnswer
downvote count: 0
has body: Use next() on a generator that yields each word in the words list that locus is in. However, since you want the index, you should enumerate the words list and only yield the index, i. next(i for i, w in enumerate(words) if 'locus' in w) #6 To get the indexes of all the occurrences, we can use a list-comprehension: [i for i, w in enumerate(words) if 'locus' in w]
has comment: http://stackoverflow.com/comment/91144092
has comment: http://stackoverflow.com/comment/91143035
type: Answer
has comment: http://stackoverflow.com/comment/91144247

http://stackoverflow.com/a/52039827
has body: df.loc creates a new column if it doesn't exist. I think you want something like this: filter = (df['Salary'] &gt; 35) df.loc[filter, 'New_Salary_Range'] = 'VERY HIGH' filter = (df['Salary'] &gt; 30) &amp; (df['Salary'] &lt;= 35) df.loc[filter, 'New_Salary_Range'] = 'HIGH' filter = (df['Salary'] &gt; 20) &amp; (df['Salary'] &lt;= 30) df.loc[filter, 'New_Salary_Range'] = 'MEDIUM' filter = (df['Salary'] &lt; 20) df.loc[filter, 'New_Salary_Range'] = 'LOW' I hope that was helpful (:
has comment: http://stackoverflow.com/comment/91101345
score: 0
answers question: http://stackoverflow.com/q/52002753
type: Answer
has comment: http://stackoverflow.com/comment/91134329

http://stackoverflow.com/comment/90898064
type: Comment
comment on: http://stackoverflow.com/a/51973312
has text: Thanks for the response @MrName , but unfortunately I'm still being shown a `null` value when setting it up this way. I could possibly just be misunderstanding the set-up. I saved the function outside the class, and called it using: `specific_workouts = JSONField(default=default_specific_workouts())`
type: AnswerComment
score: 0

http://stackoverflow.com/a/52016647
has comment: http://stackoverflow.com/comment/90983388
answers question: http://stackoverflow.com/q/52016577
type: Answer
upvote count: 1
has body: You may try using re.match here: phone = "+1 ***-***-**98" matches = re.match( r'\+1 \*+(?:-\*+)*\d{2}', phone) if matches: print("match") Demo \+1 matches plus one \*+ match any number of * (?:-\*+)* then match -*+, any number of times \d{2} match final two actual digits
score: 1
has comment: http://stackoverflow.com/comment/90983318
downvote count: 0
has comment: http://stackoverflow.com/comment/90983343
has comment: http://stackoverflow.com/comment/90983361

http://stackoverflow.com/comment/91091926
type: AnswerComment
score: 0
type: Comment
has text: Let me explain it in the answer, so that for future people also it's understandable.
comment on: http://stackoverflow.com/a/52070859

http://stackoverflow.com/comment/91140088
comment on: http://stackoverflow.com/q/52094973
type: Comment
type: QuestionComment
has text: SO is not a coding service. Show some of your work and you might be able to get some help.
score: 1

http://stackoverflow.com/comment/90916101
has text: Easier solution is to add `dfnonreturnguidecount.drop(['Ts_id'], axis=1, inplace=True) ` before writing it to_csv.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51982625
type: Comment

http://stackoverflow.com/a/52039265
has body: from scipy import stats import pandas as pd x=[1,5,3,3,3,5,2,1,8,10,2,3,3,3] data=pd.DataFrame({"values":x}) print(stats.mode(data["values"])) output:-ModeResult(mode=array([3], dtype=int64), count=array([6]))
downvote count: 0
answers question: http://stackoverflow.com/q/52038896
type: Answer
score: 1
upvote count: 1

http://stackoverflow.com/comment/90903598
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51976729
has text: (mydata/mydata.iloc[0]*100).plot(figsize = (50,5)); plt.show()
score: 0

http://stackoverflow.com/comment/91043860
type: Comment
comment on: http://stackoverflow.com/a/52022974
score: 2
type: AnswerComment
has text: Took a closer look at your GitHub repo. Looks interesting. You run gunicorn in each app container, and connect to that from a single nginx instance, which basically accomplishes what I was hoping. I'll see if I can replicate that using nginx-proxy, but it doesn't sound like I should have any problems. Thanks

http://stackoverflow.com/q/52004801
tagged with: grequests
has comment: http://stackoverflow.com/comment/90959377
upvote count: 2
has comment: http://stackoverflow.com/comment/90959294
has comment: http://stackoverflow.com/comment/90959744
type: Question
has title: How to slow down asynchrounous API calls to match API limits?
has comment: http://stackoverflow.com/comment/90959637
has answer: http://stackoverflow.com/a/52133209
tagged with: api-design
answer count: 3
has comment: http://stackoverflow.com/comment/90959137
downvote count: 0
has comment: http://stackoverflow.com/comment/90959414
has answer: http://stackoverflow.com/a/52004937
accepted answer: http://stackoverflow.com/a/52133209
tagged with: asynchronous
favorite count: 0
tagged with: python-3.x
possible better answer: http://stackoverflow.com/a/52005268
has answer: http://stackoverflow.com/a/52005268
tagged with: python
has comment: http://stackoverflow.com/comment/90959253
linked to: http://stackoverflow.com/q/20247354
score: 2
type: AnsweredQuestion
has body: I have a list of ~300K URLs for an API i need to get data from. The API limit is 100 calls per second. I have made a class for the asynchronous but this is working to fast and I am hitting an error on the API. How do I slow down the asynchronous, so that I can make 100 calls per second? import grequests lst = ['url.com','url2.com'] class Test: def __init__(self): self.urls = lst def exception(self, request, exception): print ("Problem: {}: {}".format(request.url, exception)) def async(self): return grequests.map((grequests.get(u) for u in self.urls), exception_handler=self.exception, size=5) def collate_responses(self, results): return [x.text for x in results] test = Test() #here we collect the results returned by the async function results = test.async() response_text = test.collate_responses(results)

http://stackoverflow.com/q/52087285
answer count: 1
has title: Pycharm tkinter displays gui and a green border appears around the window but nothing else works
type: UnansweredQuestion
has body: I am new to Python and using pycharm. Everything I tried worked until about an hour ago. The application is running but a green border appears around the gui (tkinter) and no code works. I run a simple print string but nothing happens. I have added buttons and frames and the application runs but the buttons and frames don't appear. All previous project run just fine but all new projects I create does the above mentioned. I am not sure what I did, any ideas? Below are screenshots. The first two show the issue and the bottom shows an exercise I did before that runs just fine. from tkinter import * root = Tk() print ("Ready") root.mainloop()
tagged with: python
has answer: http://stackoverflow.com/a/52097843
tagged with: tkinter
tagged with: pycharm
type: Question
score: 0

http://stackoverflow.com/q/52059217
downvote count: 1
type: Question
has body: So, I'm currently plotting some data that I have imported to my code via a csv file. My y values are NO2 columns My x values are Julian Dates My data looks as follows: As you can see, the Julian date always increases as you would expect. The NO2 data fluctuates upwards and downwards As you would also expect. When I plot it though, this happens: I'm wondering how to get my NO2 data to properly distribute? My code is the following: filein='filein' fileout='fileout' import csv import matplotlib.pyplot as plt import pandas as pd import numpy as np headers = ['JulianDate','NO2'] with open(filein, 'r') as sat: ##opens data with open(fileout, 'w') as outfile: ##Opens file to write csv data to for line in sat: if " Julian date" in line: writer=csv.writer(outfile)#Specifies to write this to outfile writer.writerow(headers)#Writes Headers elif "2004" in line: #specifies the year of data I want to look at line=line.split() #Eliminates unnecessary spacing in output writer=csv.writer(outfile) writer.writerow(line)#writes to output file df=pd.read_csv(output,names=headers,delimiter=',') plt.scatter(x=df['JulianDate'],y=df['NO2'])
has title: Why are my plot values incorrect?
score: -1
has comment: http://stackoverflow.com/comment/91068841
has comment: http://stackoverflow.com/comment/91079528
has answer: http://stackoverflow.com/a/52059546
tagged with: pandas
tagged with: http://stackoverflow.com/tag/csv
upvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/91069080
favorite count: 0
has comment: http://stackoverflow.com/comment/91079635
tagged with: python
has comment: http://stackoverflow.com/comment/91068756
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/52059546
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/91069980
has comment: http://stackoverflow.com/comment/91068964

http://stackoverflow.com/a/52072498
upvote count: 1
downvote count: 1
has body: Here is a simple demo x = [1,2,3,5,3,2] y = [] for a in x: if not a in y: y.append(a) print(a) So here is how it works.Iterate over every items in x.If the current iteration item doesn't exist in y append it
answers question: http://stackoverflow.com/q/52072381
score: 0
has comment: http://stackoverflow.com/comment/116498687
type: Answer

http://stackoverflow.com/a/61245680
answers question: http://stackoverflow.com/q/51989352
type: Answer
upvote count: 1
has body: num_list = [[1,2,3],[10,20,30],[100,200,300]] for x in range(0,3): for y in range(len(num_list[x])): if y==0 or y==2: print(num_list[x][y]) you can use above code
downvote count: 0
score: 1

http://stackoverflow.com/a/52032629
downvote count: 0
has body: To get angle between two vectors you can use atan2 function angle = Math.atan2(a.x * b.y - a.y * b.x, a.x * b.x + a.y * b.y) if you already have got cosines and sines (the same as coordinates on unit circle): angle = Math.atan2(cos(a) * sin(b) - sin(a) * cos(b), cos(a) * cos(b) + sin(a) * sin(b)) This approach gives angle needed to rotate a until it coincides with b accounting for direction (in range -Pi..Pi)
has comment: http://stackoverflow.com/comment/91047290
has comment: http://stackoverflow.com/comment/91015452
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/91015495
has comment: http://stackoverflow.com/comment/91048419
answers question: http://stackoverflow.com/q/52031687
type: Answer

http://stackoverflow.com/q/52015479
downvote count: 2
tagged with: python
tagged with: lambda
tagged with: java-8
possible better answer: http://stackoverflow.com/a/52015513
has answer: http://stackoverflow.com/a/52015513
type: AnsweredQuestion
tagged with: java-stream
upvote count: 14
tagged with: java
has comment: http://stackoverflow.com/comment/90990789
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/90984119
has comment: http://stackoverflow.com/comment/90987605
has title: How to iterate over lambda functions in Java
has comment: http://stackoverflow.com/comment/90987573
has answer: http://stackoverflow.com/a/52015508
has comment: http://stackoverflow.com/comment/90981597
favorite count: 0
has body: I was able to do it in Python and my Python code is: signs = {"+" : lambda a, b : a + b, "-" : lambda a, b : a - b} a = 5 b = 3 for i in signs.keys(): print(signs[i](a,b)) And the output is: 8 2 How do I do this same thing in Java through HashMap?
score: 12
accepted answer: http://stackoverflow.com/a/52015508

http://stackoverflow.com/q/51973396
has answer: http://stackoverflow.com/a/51973974
type: Question
answer count: 2
tagged with: vpython
has body: I want to code in VPython with Pycharm. I use the conda interpreter. But the keywords of Python are red underlined and it says: unsolved reference 'vPython' . I actually installed vPython and anaconda but it doesn't seem to recognize it. It even gives me the advice: install vPython when I press the red bulb. When I do so I get the error message: PackagesNotFoundError: The following packages are not available from current channels: Solving environment: ...working... failed PackagesNotFoundError: The following packages are not available from current channels: vpython Current channels: https://repo.anaconda.com/pkgs/main/osx-64 https://repo.anaconda.com/pkgs/main/noarch https://repo.anaconda.com/pkgs/free/osx-64 https://repo.anaconda.com/pkgs/free/noarch https://repo.anaconda.com/pkgs/r/osx-64 https://repo.anaconda.com/pkgs/r/noarch https://repo.anaconda.com/pkgs/pro/osx-64 https://repo.anaconda.com/pkgs/pro/noarch To search for alternate channels that may provide the conda package you're looking for, navigate to https://anaconda.org and use the search bar at the top of the page.
score: 0
accepted answer: http://stackoverflow.com/a/51973974
has title: How to fix unsolved reference 'vPython' in PyCharm?
possible better answer: http://stackoverflow.com/a/53325679
tagged with: pycharm
has answer: http://stackoverflow.com/a/53325679
tagged with: python
type: AnsweredQuestion
tagged with: anaconda

http://stackoverflow.com/q/52102217
has comment: http://stackoverflow.com/comment/91155382
tagged with: python
tagged with: precision-recall
tagged with: precision
has comment: http://stackoverflow.com/comment/91181129
has comment: http://stackoverflow.com/comment/91160473
answer count: 0
upvote count: 2
type: UnansweredQuestion
downvote count: 1
has comment: http://stackoverflow.com/comment/91155468
type: Question
has comment: http://stackoverflow.com/comment/91181396
score: 1
has comment: http://stackoverflow.com/comment/91155865
tagged with: evaluation
has title: Identifying the evaluation measures for unranked lists (set)
tagged with: scikit-learn
has comment: http://stackoverflow.com/comment/91159650
favorite count: 0
has body: I have a dataframe as follows: Column 0 (0,1,2,3...) refers to document_ids 40041,37962,37985... are ids representing objects related to the documents.For example, document_id 2 has related (truth) object 37985 and predicted objects 37985,37983. Truth – actual objects (gold standard) Predicted – objects predicted by my algorithm Overlaps – Objects exist in both Truth and Predicted lists Not detected – Objects exist in the Truth list but not detected by the algorithm. My question: Which evaluation measures I can use given the datasets below? precision will not be possible as i dont have false positives yet. How about accuracy or jaccard similarity? Scikit listed several evaluation measures here. I am looking for measures to evaluate unranked lists..
has comment: http://stackoverflow.com/comment/91155621

http://stackoverflow.com/comment/91082577
has text: We will not find the error for you. Please be specific.
score: 1
comment on: http://stackoverflow.com/q/52066069
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52109211
accepted answer: http://stackoverflow.com/a/54189597
upvote count: 1
tagged with: mailchimp-api-v3.0
type: AnsweredQuestion
score: 1
tagged with: mailchimp
type: Question
downvote count: 0
has body: I am very beginner with Python as well as with Mailchimp API, so I desperately need your advice. My ambition is to get the campaign report from the MailChimp that will contain the data in the format: Email ----- email openDate ----- clicked (True/False) ----- clickDate So far I was able to write the following code: list_campaigns = client.campaigns.all(get_all=True) for line in list_campaigns['campaigns']: campaign_list_name = line['recipients']['list_name'] campaign_list_id = line['recipients']['list_id'] print(campaign_list_id, campaign_list_name) That provides me with the list of campaign and IDs. However, campaign-based reports are giving me general information on the campaign performance (e.g. number of users opened, number of clicks), and I was unable to get anything on a granular level. Is it ever possible and if so, what might be the algorithm for the solution? p.s. here's the library I've used for Python. Thank you!
answer count: 1
tagged with: python
has answer: http://stackoverflow.com/a/54189597
favorite count: 0
has title: MailChimp API | Python Shell | Get the list of user activity with openDate, clickDate and user email

http://stackoverflow.com/comment/90865987
type: QuestionComment
has text: Sorry, but the code snippet provided does not work. It throughs an error about the `elif` that is in the code and not accompanied by an `if`. Also, this code does not seem to have any output mechanism; either printing the glitching speed or showing the graphic. It doesn't seem possible to answer your question without these fixes.
comment on: http://stackoverflow.com/q/51957162
score: 0
type: Comment

http://stackoverflow.com/q/52067655
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/91086222
has body: Immediately after the super() function is called, it creates a duplicate WidgetClass instance. My understanding of the super() I've used is that it refers to the EditImageLayout class to inherit from. To this end I've tried to implement different variations of the super() but admittedly I'm only guessing at this stage. Updated to full working, I've cut out a few hundred lines Run as > OK > Select an Image > Open > Crop (dual instances start running here) App_R3App.py from kivy.uix.boxlayout import BoxLayout from kivy.uix.floatlayout import FloatLayout from kivy.lang import Builder from kivy.app import App from kivy.uix.screenmanager import ScreenManager, Screen from kivy.uix.widget import Widget from kivy.graphics import Line, Color from kivy.properties import NumericProperty, ObjectProperty, StringProperty, ListProperty from kivy.uix.image import Image import io from kivy.core.image import Image as CoreImageKivy from kivy.uix.bubble import Bubble from kivy.core.window import Window __version__ = '0.1' class FirstScreen(Screen): pass class SecondScreen(Screen): def hl(self, image_address): self.new_image_address = image_address # for the sake of this self.callback_image(self.new_image_address, image_address, "Auto-cropped image") def callback_image(self, new_image_address_tmp, image_address_tmp, title): if new_image_address_tmp: third_screen = self.manager.get_screen("_third_screen_") new_image_address_tmp = [k.replace("\\", "/") for k in new_image_address_tmp] third_screen.callback_image(new_image_address_tmp[0], image_address_tmp[0], title) class ThirdScreen(Screen, BoxLayout): # class attribute references image_size = (0, 0) image_pos = (0, 0) image_address = "" new_image_address = "" title = "Upload" rect_box = ObjectProperty(None) t_x = NumericProperty(0.0) t_y = NumericProperty(0.0) x1 = y1 = x2 = y2 = NumericProperty(0.0) def __init__(self, **kwargs): super(ThirdScreen, self).__init__(**kwargs) pass def callback_image(self, new_image_address, image_address, t…
has comment: http://stackoverflow.com/comment/91086166
has comment: http://stackoverflow.com/comment/91086626
has comment: http://stackoverflow.com/comment/91086519
tagged with: python
tagged with: kivy
has answer: http://stackoverflow.com/a/52086473
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91086157
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/91086191
has title: Kivy - duplicate class instance on super()
score: 0
has comment: http://stackoverflow.com/comment/91086215
upvote count: 1
has comment: http://stackoverflow.com/comment/91086645
has comment: http://stackoverflow.com/comment/91086077
answer count: 1
has comment: http://stackoverflow.com/comment/91086568
accepted answer: http://stackoverflow.com/a/52086473

http://stackoverflow.com/q/52107914
has answer: http://stackoverflow.com/a/52108267
has body: I have a fairly simple question but can't find a clean pandas solution to it. Given a list of dates in a series like below: LoadedDate 0 2016-02-18 1 2016-02-19 2 2016-02-20 3 2016-02-23 4 2016-02-24 5 2016-02-25 6 2016-02-26 7 2016-02-27 8 2016-03-01 9 2016-03-02 10 2016-03-03 11 2016-03-04 12 2016-03-05 13 2016-03-08 14 2016-03-09 15 2016-03-10 16 2016-03-11 17 2016-03-12 18 2016-03-15 19 2016-03-16 20 2016-03-17 21 2016-03-18 22 2016-03-19 23 2016-03-22 24 2016-03-23 25 2016-03-24 26 2016-03-25 27 2016-03-30 28 2016-03-31 29 2016-04-01 30 2016-04-02 31 2016-04-05 32 2016-04-06 33 2016-04-07 34 2016-04-08 35 2016-04-09 36 2016-04-12 37 2016-04-13 38 2016-04-14 39 2016-04-15 40 2016-04-16 41 2016-04-19 42 2016-04-20 43 2016-04-21 44 2016-04-22 45 2016-04-23 46 2016-04-27 47 2016-04-28 48 2016-04-29 49 2016-04-30 50 2016-05-02 51 2016-05-03 52 2016-05-04 I'd like to pull the last/max date of each month. So the output would be: LastDate 0 2016-02-27 1 2016-03-31 2 2016-04-29 3 2016-05-04 I tried df.set_index('LoadedDate').groupby(pd.Grouper(freq='M')).max() but it returned the max calendar date, not the actual max loaded date of my series. Thanks.
possible better answer: http://stackoverflow.com/a/52108267
tagged with: date
type: AnsweredQuestion
downvote count: 0
has answer: http://stackoverflow.com/a/52107984
type: Question
tagged with: pandas
accepted answer: http://stackoverflow.com/a/52107984
tagged with: python
score: 1
favorite count: 0
answer count: 2
has title: Pandas - From list of dates, get the last date in each month
upvote count: 1

http://stackoverflow.com/comment/91030090
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/52039155
has text: @grshankar, did you use it for whole sentences? In my case, in one sentence there can be both Russian and English words.

http://stackoverflow.com/a/51979759
has body: If you haven't a session logged_in before logging in and it is deleted after logging out You should try : @app.route('/') def main(): if session.get('logged_in'): return redirect(url_for('search')) else: return redirect(url_for('login'))
type: Answer
answers question: http://stackoverflow.com/q/51979451
upvote count: 1
downvote count: 1
score: 0

http://stackoverflow.com/q/52106978
tagged with: wrapper
linked to: http://stackoverflow.com/q/31994879
has body: I wrote a C extesion for Python and the module is compiled in a .so file successfully. However when I am trying to use the wrapped C function in Python side (a test code in python that calls the wrapped C function) I get the following ImportError ImportError: /home/username/newModule.cpython-36m-x86_64-linux-gnu.so: undefined symbol: dgetri_ I am pretty sure that undefined symbol: dgetri_ in the import error is because the generated .so file did not find link to LAPACK library. So my question is as following, How do I compile c extension code for python when the wrapped C function depends on LAPACK library to generate module in .so format? Currently I am compiling the C code using python's utils.core module. I think I need to compile the C code from command line to link LAPACK but do not exactly know which are the appropriate commands to use? Any help is appreciated.
favorite count: 0
has answer: http://stackoverflow.com/a/61010044
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/52134387
score: 3
linked to: http://stackoverflow.com/q/40363111
upvote count: 3
linked to: http://stackoverflow.com/q/44710838
has title: How to compile C extension for Python where C function uses LAPACK library?
type: Question
has answer: http://stackoverflow.com/a/52132359
downvote count: 0
tagged with: http://stackoverflow.com/tag/c
answer count: 3

http://stackoverflow.com/comment/90923616
type: Comment
type: QuestionComment
has text: Hi, Can you please post the correct link? and in future please make sure you post the correct link.
comment on: http://stackoverflow.com/q/51981323
score: 0

http://stackoverflow.com/q/52044119
tagged with: python
favorite count: 0
answer count: 0
upvote count: 2
type: UnansweredQuestion
score: 2
has title: Running tensorboard as python subprocess
has body: I was trying to start tensorboard from a python subprocess and return the url of the service. It works fine when i redirect the output to a file and read from there. But I was trying to read the same from the stream instead of redirecting output to some file. But its not working. Please advice. def run_tensorboard(): cmd = "tensorboard --logdir retrain_logs --port 0 &amp; " p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=None, shell=True) out = p.communicate() print (out[0]) run_tensorboard()
type: Question
downvote count: 0
tagged with: tensorboard

http://stackoverflow.com/comment/91093000
score: 0
type: AnswerComment
has text: @says then just remove `elif` block
type: Comment
comment on: http://stackoverflow.com/a/52068512

http://stackoverflow.com/q/51988800
has title: Comparing and sorting two lists
type: Question
downvote count: 0
tagged with: sorting
favorite count: 0
has comment: http://stackoverflow.com/comment/90929154
answer count: 3
has answer: http://stackoverflow.com/a/51989153
tagged with: python
has answer: http://stackoverflow.com/a/51989032
tagged with: list
has comment: http://stackoverflow.com/comment/90927267
upvote count: 3
has body: I have two following lists: indexList = [5,3,2,2,7,1] valueList = [1,2,3,4,5,6] I want to sort the two together, so that the output is: indexList = [1,2,2,3,5,7] valueList = [6,3,4,2,1,5] Then, I want to fill-in the missing indices and their corresponding values as "0": indexList = [1,2,2,3,4,5,6,7] valueList = [6,3,4,2,0,1,0,5] Lastly, I want to remove repeated indices and sum their values: indexList = [1,2,3,4,5,6,7] valueList = [6,7,2,0,1,0,5] Would there be a built-in module to perform such task? Could any one guide me with piece of wisdom?
accepted answer: http://stackoverflow.com/a/51989032
tagged with: collections
has comment: http://stackoverflow.com/comment/90927270
type: AnsweredQuestion
score: 3
possible better answer: http://stackoverflow.com/a/51989053
tagged with: duplicates
has comment: http://stackoverflow.com/comment/90935915
linked to: http://stackoverflow.com/q/20145842
has answer: http://stackoverflow.com/a/51989053

http://stackoverflow.com/q/52109321
linked to: http://stackoverflow.com/q/19398385
answer count: 1
has comment: http://stackoverflow.com/comment/91169313
tagged with: referrer
tagged with: beautifulsoup
tagged with: selenium-chromedriver
has comment: http://stackoverflow.com/comment/91172981
type: UnansweredQuestion
tagged with: web-scraping
tagged with: python
has body: I can browse page https://www.xiami.com/artist/O9fc383 in browser, but when I parse it by chrome driver, I got different source as below so that I can't scrape that page, what can I do? There is no this form for source in browser. ... &lt;form action="//www.xiami.com:443/artist/O9fc383/_____tmd_____/verify/" id="nc-verify-form" method="GET"&gt; ... &lt;script&gt; var referrer=document.referrer; if (referrer &amp;&amp; referrer.indexOf("__tmd__")===-1 ){ localStorage.x5referer = document.referrer; }else{ localStorage.x5referer = window.location.href; } &lt;/script&gt;
score: 0
has comment: http://stackoverflow.com/comment/91169775
type: Question
has answer: http://stackoverflow.com/a/52109381
has title: Why python scraping result is different from in browser

http://stackoverflow.com/q/51982966
has comment: http://stackoverflow.com/comment/94038236
tagged with: tensorflow
type: Question
has body: I can't figure out how to use the Tensorflow Hub embedding column (hub.text_embedding_column) in a Keras model converted to a tf.Estimator. Using the embedding in a Keras model is achievable if I do not convert the model to an estimator. For example, with some dummy data defined as so: x_train = ['the quick brown fox', 'jumps over a lazy'] x_eval = ['the quick brown fox', 'jumps over a lazy'] y_train = [0, 1] y_eval = [0, 1] Then, I can use the following code to train a keras model without errors embed = hub.Module('https://tfhub.dev/google/nnlm-en-dim128/1') def _embed(x): return embed(tf.squeeze(tf.cast(x, tf.string))) # workaround for keras x_train = np.array(x_train, dtype=object)[:, np.newaxis] x_eval = np.array(x_eval, dtype=object)[:, np.newaxis] input_text = tf.keras.layers.Input(shape=(1,), dtype=tf.string) embedding = tf.keras.layers.Lambda(_embed, output_shape=(128,))(input_text) pred = tf.keras.layers.Dense(1, activation='sigmoid')(dense) model = tf.keras.Model(inputs=input_text, outputs=pred) model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy']) model.summary() with tf.Session() as sess: sess.run([tf.global_variables_initializer(), tf.tables_initializer()]) model.fit(x_train, y_train, epochs=1, validation_data=(x_eval, y_eval)) However, if I try to convert it to an estimator using tf.keras.estimator.model_to_estimator, all of a sudden I cannot train the model anymore. embedding = hub.text_embedding_column('text', 'https://tfhub.dev/google/nnlm-en-dim128/1') features = {'text': x_train} labels = y_train[:, np.newaxis] input_fn = tf.estimator.inputs.numpy_input_fn(features, labels, shuffle=False) embedding_input = tf.keras.layers.Input(shape=(128,), dtype=tf.float32, name='text') logits = tf.keras.layers.Dense(1, activation='softmax', name='logits')(embedding_input) model = tf.keras.Model(inputs=embedding_input, outputs=logits) model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy']) model.summary() est…
tagged with: tensorflow-estimator
score: 0
answer count: 1
has comment: http://stackoverflow.com/comment/94086424
tagged with: keras
type: UnansweredQuestion
has title: TFHub Embedding feature column in Tensorflow Estimator
tagged with: python
has answer: http://stackoverflow.com/a/53634616
tagged with: tensorflow-hub

http://stackoverflow.com/comment/91010501
comment on: http://stackoverflow.com/q/52029253
score: 0
type: Comment
has text: You mention that you installed NLTK into the Anaconda's env but you also mention that you used `sudo`. I am not familiar with Anaconda but it doesn't sound right to me as `sudo` will take you out of your environment so you should be installing into the system python. Try running `pip install nltk` from pycharm's terminal without using sudo. Also, you can check what python/pip is used by using the `which` command. `which python` and `which pip` should be in the same folder.
type: QuestionComment

http://stackoverflow.com/q/51959978
score: -1
tagged with: pydicom
has comment: http://stackoverflow.com/comment/90963599
answer count: 1
has comment: http://stackoverflow.com/comment/90964203
favorite count: 0
has body: I am trying to anonymize accession numbers with a fake custom AN with pydicom: def an_callback(ds, data_element): if data_element.tag == Tag(0x00080050): data_element.value = '0000000000' ds.walk(an_callback) I would like to pass a custom value instead of '0000000' to the call back function. I suppose I could use a global variable, but I would like to avoid that to reduce unwarranted bugs. Is there a different way that does not use global variables? edit: I thought walk was a special python function, but it was just a method of ds, here is the code. You can change the code here for callback to also include an optional parameter. callback(self, data_element, replace_value=None) def walk(self, callback, recursive=True): """Iterate through the DataElements and run `callback` on each. Visit all DataElements, possibly recursing into sequences and their datasets. The callback function is called for each DataElement (including SQ element). Can be used to perform an operation on certain types of DataElements. E.g., `remove_private_tags`() finds all private tags and deletes them. DataElement`s will come back in DICOM order (by increasing tag number within their dataset). Parameters ---------- callback A callable that takes two arguments: * a Dataset * a DataElement belonging to that Dataset recursive : bool Flag to indicate whether to recurse into Sequences. """ taglist = sorted(self.keys()) for tag in taglist: with tag_in_exception(tag): data_element = self[tag] callback(self, data_element) # self = this Dataset # 'tag in self' below needed in case callback deleted # data_element if recursive and tag in self and data_element.VR == "SQ": sequence = data_element.value for dataset in sequence: dataset.walk(callback)
downvote count: 2
tagged with: python
has comment: http://stackoverflow.com/comment/90963156
has comment: http://stackoverflow.com/comment/90962888
linked to: http://stackoverflow.com/q/11462314
type: AnsweredQuestion
has title: How to pass a value to callback for anonymization without global variables?
upvote count: 1
has answer: http://stackoverflow.com/a/51962929
accepted answer: http://stackoverflow.com/a/51962929
type: Question

amazon-vpc
type: Tag
tag name: amazon-vpc
tags question: http://stackoverflow.com/q/52046518

http://stackoverflow.com/comment/91057738
type: Comment
has text: How about `f2` calls `f` instead of using the same code?
score: 1
type: QuestionComment
comment on: http://stackoverflow.com/q/52053685

http://stackoverflow.com/q/52101568
type: UnansweredQuestion
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/91162902
score: 1
has comment: http://stackoverflow.com/comment/91173294
has comment: http://stackoverflow.com/comment/91173452
type: Question
tagged with: encoding
downvote count: 0
tagged with: unicode
has comment: http://stackoverflow.com/comment/91173521
answer count: 1
has body: I'm retrieving some date from a website via lxml xpath: page = requests.get(url) tree = html.fromstring(page.content) titles_arr = tree.xpath("//span[@class='lister-item-header']/span/a/text()") Some of the titles have German Umlaute (e.g. üöä) so I thought of encoding the text returned like so: for title in titles_arr: title = title.encode('utf-8') but it still consists of like Der Herr der Ringe - Die Rückkehr des Königs instead of their respective unicode character. What am I doing wrong? Thanks
has title: Encode UTF-8 not working when retrieving Xpath text
favorite count: 0
has answer: http://stackoverflow.com/a/52121051

http://stackoverflow.com/q/52100694
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91152261
type: Question
has comment: http://stackoverflow.com/comment/91152442
has title: Iterate by value over many lists
has body: I have a bunch of interables (whose entries represent positions on genomes) that are sorted. I would like to process them simultaneously such that all of them that have data at a particular position are processed, whereas those that do not are skipped. A rather clunky solution is import sys it1 = iter([0, 1, 3, 5]) it2 = iter([0, 2, 4, 5]) it3 = iter([3, 5, 7]) def do_stuff(objects, values): print("iterables [%s] have value %s" % (objects, values[0])) def iterate_many(iterables): cur_ele = [next(i) for i in iterables] is_finished = [False for i in iterables] while not all(is_finished): lowest_val = min(cur_ele) lowest_obj = [e for e in cur_ele if e == lowest_val] to_increment = [i for i, e in enumerate(cur_ele) if e == lowest_val and not is_finished[i]] yield do_stuff(to_increment, lowest_obj) for i in to_increment: try: cur_ele[i] = next(iterables[i]) except StopIteration: is_finished[i] = True cur_ele[i] = sys.maxsize which results in In [76]: for i in iterate_many( [it1, it2, it3]): pass iterables [[0, 1]] have value 0 iterables [[0]] have value 1 iterables [[1]] have value 2 iterables [[0, 2]] have value 3 iterables [[1]] have value 4 iterables [[0, 1, 2]] have value 5 iterables [[2]] have value 7 Is there an easier/ more pythonic way of accomplishing this goal?
has comment: http://stackoverflow.com/comment/91152371
answer count: 1
downvote count: 0
favorite count: 0
tagged with: python
score: 2
has answer: http://stackoverflow.com/a/52100878
tagged with: python-3.x
upvote count: 2
has comment: http://stackoverflow.com/comment/91174293

http://stackoverflow.com/q/51997171
has comment: http://stackoverflow.com/comment/90944190
upvote count: 4
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51997389
downvote count: 0
has comment: http://stackoverflow.com/comment/90943934
favorite count: 0
type: Question
tagged with: pandas
has comment: http://stackoverflow.com/comment/90943908
has comment: http://stackoverflow.com/comment/90943645
has answer: http://stackoverflow.com/a/51998632
answer count: 2
tagged with: python
has answer: http://stackoverflow.com/a/51997389
tagged with: vectorization
has title: Pandas: vectorization with function on two dataframes
possible better answer: http://stackoverflow.com/a/51998632
score: 4
has body: I'm having trouble with implementing vectorization in pandas. Let me preface this by saying I am a total newbie to vectorization so it's extremely likely that I'm getting some syntax wrong. Let's say I've got two pandas dataframes. Dataframe one describes the x,y coordinates of some circles with radius R, with unique IDs. &gt;&gt;&gt; data1 = {'ID': [1, 2], 'x': [1, 10], 'y': [1, 10], 'R': [4, 5]} &gt;&gt;&gt; df_1=pd.DataFrame(data=data1) &gt;&gt;&gt; &gt;&gt;&gt; df_1 ID x y R 1 1 1 4 2 10 10 5 Dataframe two describes the x,y coordinates of some points, also with unique IDs. &gt;&gt;&gt; data2 = {'ID': [3, 4, 5], 'x': [1, 3, 9], 'y': [2, 5, 9]} &gt;&gt;&gt; df_2=pd.DataFrame(data=data2) &gt;&gt;&gt; &gt;&gt;&gt; df_2 ID x y 3 1 2 4 3 5 5 9 9 Now, imagine plotting the circles and the points on a 2D plane. Some of the points will reside inside the circles. See the image below. All I want to do is create a new column in df_2 called "host_circle" that indicates the ID of the circle that each point resides in. If the particle does not reside in a circle, the value should be "None". My desired output would be &gt;&gt;&gt; df_2 ID x y host_circle 3 1 2 1 4 3 5 None 5 9 9 2 First, define a function that checks if a given particle (x2,y2) resides inside a given circle (x1,y1,R1,ID_1). If it does, return the ID of the circle; else, return None. &gt;&gt;&gt; def func(x1,y1,R1,ID_1,x2,y2): ... dist = np.sqrt( (x1-x2)**2 + (y1-y2)**2 ) ... if dist &lt; R: ... return ID_1 ... else: ... return None Next, the actual vectorization. I'm sorta lost here. I think it should be something like df_2['host']=func(df_1['x'],df_1['y'],df_1['R'],df_1['ID'],df_2['x'],df_2['y']) but that just throws errors. Can someone help me? One final note: My actual data I'm working with is VERY large; tens of millions of rows. Speed is crucial, hence why I'm trying to make vectorization work.
has comment: http://stackoverflow.com/comment/90943700

http://stackoverflow.com/a/52077658
answers question: http://stackoverflow.com/q/52077389
has comment: http://stackoverflow.com/comment/91107449
score: 0
type: Answer
has comment: http://stackoverflow.com/comment/91106196
has body: Pytest let you add an XFail decorator to decide if you want your test to fail on a specific exception: @pytest.mark.xfail(raises= IndexError) def test_function(): test_here You can read more about it here Edit: you might want to add the strict=true param as well, like this: @pytest.mark.xfail(raises= IndexError, strict=True) def test_function(): test_here This will fail the suite if this requirement is not met AKA the test didnt fail on IndexError (the default for XFail tests is not to fail the suite even if they dont throw the error)

http://stackoverflow.com/a/52021672
has comment: http://stackoverflow.com/comment/90993762
accepted answer of: http://stackoverflow.com/q/52021601
type: Answer
answers question: http://stackoverflow.com/q/52021601
has body: According to the documentation for numpy.Random.randn The dimensions of the returned array, should be all positive. If no argument is given a single Python float is returned. You're mistaking the arguments that control the dimensions of the array(s) for the upper and lower bounds of your random numbers. Since an array can't have a negative index, using negative numbers for the dimensions of the array isn't allowed. You weren't clear on what you were trying to accomplish in your question, but it seems like you want an array of random numbers between an upper and lower boundary. Instead, your current implementation is creating a 2 dimensional array that's 2x2, 4x4, etc.
score: 0
type: AcceptedAnswer

http://stackoverflow.com/a/51985551
accepted answer of: http://stackoverflow.com/q/51985371
type: Answer
answers question: http://stackoverflow.com/q/51985371
has body: You could use this - all(isinstance(i, int) for i in lis) This will give you True if all the elements of list are integer, then you can modify your code to test against strings and integers if all(isinstance(i, int) for i in lis): return list(reversed(lis)) # return reversed list elif all(isinstance(i, str) for i in lis): return [i.upper() for i in lis] # change to uppercase and return the list return lis # return list as is
upvote count: 5
type: AcceptedAnswer
downvote count: 0
score: 5

http://stackoverflow.com/a/51980438
has body: First split values of column by first :, add counter by cumcount and reshape by unstack: df = df['col'].str.split(':', expand=True, n=1) df.columns = ['a','b'] df1 = (df.set_index(['a',df.groupby('a').cumcount()])['b'] .unstack() .T .rename_axis(None, axis=1) .reindex(columns=df['a'].unique())) print (df1) Name College Name 0 Bob Boston 1 Ready IIT KGP
upvote count: 1
type: Answer
accepted answer of: http://stackoverflow.com/q/51978567
answers question: http://stackoverflow.com/q/51978567
downvote count: 0
score: 1
type: AcceptedAnswer

http://stackoverflow.com/q/52040389
has comment: http://stackoverflow.com/comment/91031182
has body: I have the following C++ code: // Load image from vector cv::Mat image = imread(filenames[i]); // option = black if (arg == "black" | arg == "all") { // Extracting colors - BGR (black backround) // Blue inRange(image, Scalar(190, 0, 0), Scalar(255, 50, 50), blue); // Green inRange(image, Scalar(0, 190, 0), Scalar(50, 255, 50), green); // Red inRange(image, Scalar(0, 0, 190), Scalar(50, 50, 255), red); // White inRange(image, Scalar(235, 235, 235), Scalar(255, 255, 255), white); // Silver inRange(image, Scalar(180, 180, 190), Scalar(200, 200, 220), silver); // bitwise OR mask mask = blue|green|red|white|silver; } // option = wooden else { // Extracting colors - BGR (wooden backround) // Blue inRange(image, Scalar(190, 0, 0), Scalar(255, 50, 50), blue); // Green inRange(image, Scalar(0, 190, 0), Scalar(50, 255, 50), green); // Red inRange(image, Scalar(0, 0, 190), Scalar(50, 50, 255), red); // White inRange(image, Scalar(235, 235, 235), Scalar(255, 255, 255), white); // Silver inRange(image, Scalar(190, 190, 200), Scalar(220, 220, 230), silver); // Black inRange(image, Scalar(0, 0, 0), Scalar(40, 40, 40), black); // bitwise OR mask mask = blue|green|red|white|silver|black; } // Store mask points into a vector vector&lt;Point&gt; pts; findNonZero(mask, pts); which I want to translate to Python. I am done with almost every part but not the bitwise OR mask part. I tried the following: mask = np.logical_or.reduce((mask == blue, mask == green, mask == red, mask == white, mask == silver)) however it did not work for me. What's the Python equivalent of this operation?
has comment: http://stackoverflow.com/comment/91031355
type: Question
score: 0
tagged with: python
answer count: 1
has title: Python Bitwise OR
tagged with: c++
has answer: http://stackoverflow.com/a/52040608
has comment: http://stackoverflow.com/comment/91031190
has comment: http://stackoverflow.com/comment/91031260
tagged with: logical-operators
accepted answer: http://stackoverflow.com/a/52040608
type: AnsweredQuestion

http://stackoverflow.com/a/52000273
has comment: http://stackoverflow.com/comment/90949645
score: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/124572361
type: AcceptedAnswer
downvote count: 1
type: Answer
answers question: http://stackoverflow.com/q/52000077
has comment: http://stackoverflow.com/comment/90949907
accepted answer of: http://stackoverflow.com/q/52000077
has comment: http://stackoverflow.com/comment/124741555
has body: Given you are asking the OS if a single file exists, it does not need to do any algorithmic logic, or go down your path... I don't see how it could be anything else than O(1).

http://stackoverflow.com/comment/90993932
comment on: http://stackoverflow.com/q/52021737
has text: `frame_name.pack.forget` doesn't call the `forget` method; you need parentheses for that: `frame_name.pack.forget()`. (Also, `forget` doesn't destroy anything, so at the very least, your comments and debugging output are misleading.)
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52029604
type: Question
score: 1
has answer: http://stackoverflow.com/a/52029640
answer count: 2
tagged with: arrays
downvote count: 0
has body: I'm trying to find best way to comparise two two-dimensional arrays and write elements which there aren't in first array. In case of one-dimensional array all is easy: a = [1, 2] b = [1, 2, 3] newArray = list(set(b) - set(a)) newArray in this case will be [3] Difficults in this case. For example, I have: a = [[1, 2, 3], [1, 2, 5], [4, 6, 9]] b = [[1, 2, 3], [1, 4, 5], [2, 6, 5]] and I want to get newArray = [[1, 4, 5], [2, 6, 5]], but if I try newArray = list(set(b) - set(a)) it leads to error TypeError: unhashable type: 'list' How I can realize as same as in case of one-dimensional array? Length of arrays may be different.
has title: Comparison between two two-dimensionla arrays
favorite count: 0
possible better answer: http://stackoverflow.com/a/52029638
has answer: http://stackoverflow.com/a/52029638
tagged with: multidimensional-array
tagged with: python
accepted answer: http://stackoverflow.com/a/52029640
type: AnsweredQuestion
upvote count: 1

http://stackoverflow.com/q/52060869
score: 2
type: AnsweredQuestion
tagged with: multi-index
accepted answer: http://stackoverflow.com/a/52061854
type: Question
has body: I have a nested multi-index dataframe with 3 levels and I want to select the 1st and 3rd level without selecting the 2nd level. Is it possible to do that? My current code looks like this (updated). now I am getting TypeError: unhashable type: 'slice' for panda which I am not sure why. 'D' and 'E' are the columns that I want to select from the 3rd level. df1_1 = data['A'].loc['B',:,'D','E']
tagged with: dataframe
tagged with: pandas
downvote count: 0
answer count: 1
favorite count: 0
has title: How to skip a column level in a multi index dataframe?
has answer: http://stackoverflow.com/a/52061854
upvote count: 2
tagged with: python

http://stackoverflow.com/a/57584247
score: 0
type: Answer
answers question: http://stackoverflow.com/q/51979903
has body: switching from from pip._vendor import requests to import requests solved this issue for me. If it doesnt solve it for you, you should check the version of pip u are using, apparently i can reproduce this issue when im using pip 10+, so try downgrading to pip 9.

http://stackoverflow.com/q/52061762
accepted answer: http://stackoverflow.com/a/52076104
has comment: http://stackoverflow.com/comment/91074624
tagged with: python
has comment: http://stackoverflow.com/comment/91073979
has title: MongoDB lookup get referenced object id and advice for reference
type: AnsweredQuestion
upvote count: 3
tagged with: pymongo
has comment: http://stackoverflow.com/comment/91073826
type: Question
has comment: http://stackoverflow.com/comment/91074485
has comment: http://stackoverflow.com/comment/91074822
has comment: http://stackoverflow.com/comment/91074056
has answer: http://stackoverflow.com/a/52076104
has comment: http://stackoverflow.com/comment/91073950
tagged with: mongodb
has body: I'm using PyMongo and MongoDB 4.0.1. For the example I'll call my collections User and Car. So my user can get only one car (One to One relationship) User ---- _id : ObjectId("2b2543b24713ea82ce3ae21f") Firstname : John Lastname : Doe Car : ObjectId("5b854bb806a77a06ce321f1f") Car ---- _id : ObjectId("5b854bb806a77a06ce321f1f") Model : Tesla Motor When I do this query : db.user.aggregate( {$unwind: "$car"}, {$lookup: { from:"car", localField: "car", foreignField: "_id", as: "car" }} ) the output show me that car property will be an array of cars with one object... { "_id" : ObjectId("2b2543b24713ea82ce3ae21f"), "firstname" : "John", "lastname" : "Doe" , "car" : [ { "_id" : ObjectId("5b854bb806a77a06ce321f1f"), "model" : "Tesla Motor" }] } It's possible to get just one object and not an array ? Another question about references. Lot of different Users can get the same car. It is good in No SQL database to reference the object id or it's better to create all car fields in the User collection ? Because I have to update all different data. For example if there is a change on the Car I think it's easier to update just one document in the Car collection than update 50 rows in the user collection. Do you think I'm right ?
has comment: http://stackoverflow.com/comment/91074767
score: 3
answer count: 1
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/91074370
tagged with: aggregation-framework
has comment: http://stackoverflow.com/comment/91074441

http://stackoverflow.com/q/52080597
score: 0
has title: WebDriverException : unhandled inspector error with code "-3200"
answer count: 1
has body: i'm currently working on an app (python/django/redis) to track and register movement of grains on a farm. My main app is working fine, i'm now trying to have my last page working. The goal of the page is for the user to load it on his samsung tab while in reach of a network, then go in the field to gather some data that get register in the localStorage. Once he is finished he goes back in reach of the network and press the loading button. When the button is pressed it send a post request, telling the view it need to gather the data from the localStorage and put it in a Redis key. Here is the code of the view : def creationField(request): if request.method == 'POST': driver = webdriver.Chrome() url='XXX.X.X.XX:XXXX/XXXXXXX/XXXXXXX' driver.get(url) storage = LocalStorage(driver) for i in range(1,50) : keyCubage = 'Wagon_'+ str(i) + '_cubageWagon' keyLimite = 'Wagon_'+ str(i) + '_limiteWagon' keyCiterne = 'Wagon_'+ str(i) + '_numCiterne' keyPBM = 'Wagon_'+ str(i) + '_pbmWagon' keyTar = 'Wagon_'+ str(i) + '_tarWagon' cubageWagon = storage.get(keyCubage) limiteWagon = storage.get(keyLimite) numCiterne = storage.get(keyCiterne) pbmWagon = storage.get(keyPBM) tarWagon = storage.get(keyTar) if (cubageWagon == None or limiteWagon == None or numCiterne == None or pbmWagon == None or tarWagon == None): result = "Break" break else: result = "REDIS WORK" r = redis.StrictRedis(host=settings.REDIS_AD, port=settings.REDIS_PORT, db='14') key = 'Wagon_' + str(i) r.hmset(key, {'Cubage': cubageWagon, 'limite': limiteWagon, 'numCiterne': numCiterne, 'pbmWagon': pbmWagon, 'tarWagon': tarWagon}) return render(request, 'creationField.html', locals()) LocalStorage class : class LocalStorage: def __init__(self, driver) : self.driver = driver def __len__(self): return self.driver.execute_script("return window.localStorage.length;") def items(self) : return self.driver.execute_script( \ "var ls = window.localStorage, items = {}; " \ "for (var i = 0, k; i &lt; ls.length; ++i) " \ " items[k = ls…
has comment: http://stackoverflow.com/comment/91173041
tagged with: python
tagged with: selenium-webdriver
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52111337
accepted answer: http://stackoverflow.com/a/52111337
tagged with: webdriver
type: Question

http://stackoverflow.com/comment/91122448
score: 0
type: Comment
has text: @JonClements Thank you!
type: AnswerComment
comment on: http://stackoverflow.com/a/52085669

http://stackoverflow.com/comment/90988071
has text: No. Are there any logs I can provide?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52018761

http://stackoverflow.com/a/52228017
has body: Finally figured out how to pass dynamic values to the ENV widget. And it was really easy after all. For people using Jenkins Allure plugin: We run our jobs on Windows machines (Windows Batch Command), passing some build parameters to a python test runner. Then in post build actions were calling the Allure Report. Results Path is reports/$BUILD_TAG $BUILD_TAG is an available environment variable (look for link under Windows batch command) So to get your report populated with environment variables or build parameters, simply create another Windows Batch Command after you run your test with something like the following: cd reports/%BUILD_TAG% ( echo BUILD=%build% echo ENVIRONMENT=%env% )&gt;environment.properties This will create an environment.properties file on the fly with your build info. Once your job gets to Post-build Actions (ie Allure report) it will generate all your raw json with your environment.properties. Waa Laa! Note: This is configured for Windows at the moment. In the process of getting jobs run, reports generated on Linux boxes. Change 'Windows Batch Command' to 'Execute shell' and configure for Linux commands. Should be straightforward.
upvote count: 1
answers question: http://stackoverflow.com/q/52030518
score: 1
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/131408006

http://stackoverflow.com/comment/125289318
has text: Please do not recommend pytz anymore: It is broken, deprecated and adds an external dependency. Use zoneinfo instead.
score: 1
comment on: http://stackoverflow.com/a/70745186
type: AnswerComment
type: Comment

http://stackoverflow.com/q/52108369
tagged with: python
has comment: http://stackoverflow.com/comment/91194940
answer count: 0
type: UnansweredQuestion
upvote count: 1
type: Question
has title: Python is reading rows from a CSV file out of order on Windows 7 corporate laptop - what could be the issue?
has comment: http://stackoverflow.com/comment/91202288
downvote count: 0
tagged with: salesforce
score: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/91169427
tagged with: http://stackoverflow.com/tag/csv
tagged with: windows
has body: I have a Python script that is creating a CSV file named 'reader.csv' with queried data from Salesforce for staging purposes. It then sends the data, reads the data from 'reader.csv' row by row and writes this row to our output file. For some context, it needs to use a staging file to manipulate the array indexes in each row based off of certain values to place them elsewhere in the output file (grabbing the Mortgage Status Date values and placing that same date in accordance to the column headers). On a Windows 7 corporate machine, the script is reading the array from each row in the 'reader.csv' file out of order... which means it's writing to the output file out of order. It has been tested on several Macs, a newer Windows 10 machine, and even a Raspberry Pi running an old Linux distro... and it all works perfectly. Yet, when we run the script on a Windows 7 machine, it reads the data from the staging file out of order and then writes it out of order in the output file. Here is my code that extracts the data and then writes it to the corresponding CSV files (alongside the transform method I'm using to manipulate the dictionary: def sf_extract(sf_object, query): """ Queries Salesforce objects and returns the data in an OrderedDict """ # Define the job and object, then query the data job = sf.create_query_job(sf_object, contentType='CSV') batch = sf.query(job, query) sf.close_job(job) # Waits to make sure the query has been fetched while not sf.is_batch_done(batch): time.sleep(10) # Decode the results for result in sf.get_all_results_for_query_batch(batch): data = unicodecsv.DictReader(result, encoding='utf-8') return data def csv_writer(sf_object, data): """ Creates a 'Reader' file, transforms the data, then writes the transformed data to an output file """ file_name = "contact_product_data " + str(year_month_day) + ".csv" # Opens a CSV file with open("reader.csv", 'a+', encoding='utf-8', newline='') as in_file: # Grabs each item (record dictionary) from the data …

http://stackoverflow.com/comment/91152128
type: Comment
has text: I'm working on just that. Because of the number of moving parts it is proving to be complicated.
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/52088331

http://stackoverflow.com/q/51970383
type: Question
has comment: http://stackoverflow.com/comment/90891252
tagged with: jenkins-pipeline
score: 0
has title: Convert Jenkins pipeline script code into Python
linked to: http://stackoverflow.com/q/24297889
tagged with: python
has comment: http://stackoverflow.com/comment/90892534
has body: I need some assistance to convert some Jenkins pipeline script code to Python. Reason for converting this code is that I have ssh to a remote host using Febric in Jenkins pipeline and I need to run pipeline script inside Febric which is Python based. Below is the sample code which I need to convert. Thanks git branch: 'develop', credentialsId: ‘xxxx-xxxx-xxxx-xxx’, poll: false, url: 'ssh://git@xxxx.yyyy.net:port/path/project.git' def nodeHome = tool name: 'NodeJS 8.9.4', type: 'jenkins.plugins.nodejs.tools.NodeJSInstallation' env.PATH = "${nodeHome}/bin:${env.PATH}" try { dir(‘project/test’) { sh(“docker ps -a”) } } catch { // catch error } finally { // finally }
answer count: 0
tagged with: jenkins
type: UnansweredQuestion

http://stackoverflow.com/comment/91079946
comment on: http://stackoverflow.com/q/52064496
score: 1
has text: `ret=re.sub(r"^.*\^", r"", readlines)` works fine, please clarify.
type: Comment
type: QuestionComment

jupyter
tags question: http://stackoverflow.com/q/51968109
type: Tag
tags question: http://stackoverflow.com/q/52053383
tags question: http://stackoverflow.com/q/52074673
tags question: http://stackoverflow.com/q/52014798
tags question: http://stackoverflow.com/q/52091407
tags question: http://stackoverflow.com/q/52048801
tags question: http://stackoverflow.com/q/52085070
tags question: http://stackoverflow.com/q/52053698
tag name: jupyter
tags question: http://stackoverflow.com/q/52078276
tags question: http://stackoverflow.com/q/52092842
tags question: http://stackoverflow.com/q/52037267
tags question: http://stackoverflow.com/q/52061097

http://stackoverflow.com/comment/91148011
type: QuestionComment
comment on: http://stackoverflow.com/q/52098712
has text: I do not know what is telnet, but I usually connect to that server using ssh, it works fine. I can also accses database there
score: 0
type: Comment

http://stackoverflow.com/a/52068759
type: Answer
score: 2
upvote count: 2
has body: The sentinel is only set to False when there isn't an exception. Make sure to set it to False in your except block as well. To recover gracefully from an error, you probably don't want to wrap every file access in the same try/except block. Rather, you want to have a small try/except block catching an individual file operation, and if that fails you can apply your error handling code (e.g. retrying or logging and continuing to the next file).
answers question: http://stackoverflow.com/q/52068724
has comment: http://stackoverflow.com/comment/91087844
accepted answer of: http://stackoverflow.com/q/52068724
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/91004280
type: Comment
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/52025795
has text: You've posted too much code, which lowers the quality of this question. Please try to remove everything that isn't necessary to reproduce the problem in order to create a [mcve].

http://stackoverflow.com/q/52036176
tagged with: python
score: 2
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/91025651
accepted answer: http://stackoverflow.com/a/52039568
upvote count: 2
has comment: http://stackoverflow.com/comment/91028162
has comment: http://stackoverflow.com/comment/91029118
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91024333
linked to: http://stackoverflow.com/q/7777913
tagged with: opengl
tagged with: pyopengl
type: Question
has comment: http://stackoverflow.com/comment/91027692
has comment: http://stackoverflow.com/comment/91028107
has answer: http://stackoverflow.com/a/52039568
answer count: 1
downvote count: 0
has title: PyOpenGL - Get depth map of drawn image
favorite count: 0
has body: I have drawn a specific scene using from a specific point of view (using view and projection matrices). I used VBOs of triangles and so one. I can get the RGB of the image using: data = glReadPixels(0, 0, width, height, GL_RGB, GL_UNSIGNED_BYTE) data = np.frombuffer(data, dtype=np.uint8).reshape(width, height, 3)[::-1] cv2.imwrite(r"c:\temp\image1.png", data) But getting the depth map gets some strange result that consists mostly of 255: data2 = glReadPixels(0, 0, width, height, GL_DEPTH_COMPONENT, GL_UNSIGNED_BYTE) data2 = np.frombuffer(data2, dtype=np.uint8).reshape(width, height)[::-1] cv2.imwrite(r"c:\temp\image2.png", data2) I tried replacing GL_UNSIGNED_BYTE -> GL_FLOAT and uint8 -> float32 But that didn't help
has comment: http://stackoverflow.com/comment/91028019
has comment: http://stackoverflow.com/comment/91028178

http://stackoverflow.com/q/52014156
upvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/90980322
tagged with: dataframe
tagged with: pandas
accepted answer: http://stackoverflow.com/a/52014391
answer count: 1
downvote count: 0
has title: Repeating particular row of pandas dataframe
favorite count: 0
has answer: http://stackoverflow.com/a/52014391
has body: I want to repeat a specific row of pandas data frame for a given number of times. For example, this is my data frame df= pd.DataFrame({ 'id' : ['1','1', '2', '2','2','3'], 'val' : ['2015_11','2016_2','2011_9','2011_11','2012_2','2018_2'], 'data':['a','a','b','b','b','c'] }) print(df) Here, "Val" column contains date in string format. It has a specific pattern 'Year_month'. For the same "id", I want the rows repeated the number of times that is equivalent to the difference between the given "val" column values. All other columns except the val column should have the duplicated value of previous row. The output should be:
tagged with: python
type: AnsweredQuestion
score: 1

http://stackoverflow.com/comment/91107152
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52077700
has text: @CDNthe2nd: did you copy the HTML from your browser perhaps? Take into account that that reflects the current DOM, which can have been altered by Javascript code! When I use your first sample, I get ` ` included, so the `class` test works. Your code prints the ` ` element, and that shows the class is *not* there, so you didn't use the same HTML.

http://stackoverflow.com/comment/91343941
type: Comment
has text: Honestly the heuristic for `gamma` in that paper seems to be more of a WAG that worked for a given data set. `gamma >>1` is very quickly going to get you a binary `label_distributions` matrix (with only 1s and 0s) and if any row gets driven to all 0's (becasue one point is far from any others) your method will fail as you've described.
comment on: http://stackoverflow.com/a/52144825
type: AnswerComment
score: 0

http://stackoverflow.com/comment/91157266
comment on: http://stackoverflow.com/a/52102409
type: AnswerComment
has text: Yes, thank you it is much appreciated! Is there a way to do the same thing but not have any parentheses?
type: Comment
score: 0

http://stackoverflow.com/comment/90912066
comment on: http://stackoverflow.com/q/51980776
type: Comment
score: 0
has text: Python has "universal newlines support". Basically *all* of `\n`, `\r` and `\n\r` are considered a newline. If you open the file in text-mode python will convert those 3 line-endings into just `\n`. If you have to interpret the text differently you want to open the file in binary mode and handle lines by hand.
type: QuestionComment

http://stackoverflow.com/a/51997994
has comment: http://stackoverflow.com/comment/91039176
has comment: http://stackoverflow.com/comment/91042679
type: Answer
has comment: http://stackoverflow.com/comment/91044833
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/91044704
has body: With keras.layers.LSTM(10), you need to include the input data shape: keras.layers.LSTM(10, input_shape = (input.shape[1], input.shape[2])). Keras is expecting the input data shaped as [instances, time, predictors] and since you don't have any additional predictors, you may need to reshape your input data to input.reshape(input.shape[0], input.shape[1], 1). Keras will infer the data shapes for the next layers, but the first layer needs the input shape defined.
answers question: http://stackoverflow.com/q/51972364
has comment: http://stackoverflow.com/comment/91038862
accepted answer of: http://stackoverflow.com/q/51972364
has comment: http://stackoverflow.com/comment/91035889
upvote count: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/91042355

http://stackoverflow.com/q/52094338
has title: Internal Server Error in django and uwsgi + nginx
has comment: http://stackoverflow.com/comment/91243528
tagged with: python
has comment: http://stackoverflow.com/comment/91139115
has comment: http://stackoverflow.com/comment/91139108
has body: I deployed a Django application on server. I used nginx and uwsgi as web server. I didn't have any problem first, but I see "Internal Server Error" when I add rest_framework to project. I guess It has problem with rest_framework but I don't know its reason. I think you should know when I remove rest_framework from project, It's working. I should say when I run project with python manage.py runserver, It's working. I guess there are any problems with nginx or uwsgi. I put my settings below: settings.py import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'SECRET_KEY' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False ALLOWED_HOSTS = ["*"] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'tagulous', 'django_render_partial', 'ckeditor', 'ckeditor_uploader', 'allauth', 'allauth.account', 'allauth.socialaccount', # 'easy_thumbnails', # 'filer', 'mptt', # 'anymail', 'core.apps.CoreConfig', 'blog.apps.BlogConfig', 'sitebuilder.apps.SitebuilderConfig', 'rest_framework', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'boofeh.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'sitebuilder','templates'), os.path.join(BASE_DIR, 'sitebuilder','templates', 'allauth')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processo…
has comment: http://stackoverflow.com/comment/91138756
score: 2
type: AnsweredQuestion
upvote count: 2
has comment: http://stackoverflow.com/comment/91145896
accepted answer: http://stackoverflow.com/a/52169316
has comment: http://stackoverflow.com/comment/91139232
tagged with: django
has comment: http://stackoverflow.com/comment/91139111
tagged with: uwsgi
has comment: http://stackoverflow.com/comment/91139248
type: Question
tagged with: nginx
has comment: http://stackoverflow.com/comment/91141102
has comment: http://stackoverflow.com/comment/91139396
downvote count: 0
answer count: 1
has answer: http://stackoverflow.com/a/52169316
has comment: http://stackoverflow.com/comment/91196788
favorite count: 0
has comment: http://stackoverflow.com/comment/91139825
has comment: http://stackoverflow.com/comment/91139991

http://stackoverflow.com/a/51985687
has body: You need to install requests, pip install requests if you want to use the following code: # -*- coding: utf-8 -*- import concurrent.futures import requests import queue import threading # URL Pool URLS = [ # Put your urls here ] # Time interval (in seconds) INTERVAL = 5 * 60 # The number of worker threads MAX_WORKERS = 4 # You should set up request headers # if you want to better evade anti-spider programs HEADERS = { 'Accept': '*/*', 'Accept-Encoding': 'gzip, deflate', 'Accept-Language': 'en-US,en;q=0.9', 'Cache-Control': 'max-age=0', 'Connection': 'keep-alive', #'Host': None, 'If-Modified-Since': '0', #'Referer': None, 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.62 Safari/537.36', } ############################ def handle_response(response): # TODO implement your logics here !!! raise RuntimeError('Please implement function `handle_response`!') # Retrieve a single page and report the URL and contents def load_url(session, url): #print('load_url(session, url={})'.format(url)) response = session.get(url) if response.status_code == 200: # You can refactor this part and # make it run in another thread # devoted to handling local IO tasks, # to reduce the burden of Net IO worker threads return handle_response(response) def ThreadPoolExecutor(): return concurrent.futures.ThreadPoolExecutor(max_workers=MAX_WORKERS) # Generate a session object def Session(): session = requests.Session() session.headers.update(HEADERS) return session # We can use a with statement to ensure threads are cleaned up promptly with ThreadPoolExecutor() as executor, Session() as session: if not URLS: raise RuntimeError('Please fill in the array `URLS` to start probing!') tasks = queue.Queue() for url in URLS: tasks.put_nowait(url) def wind_up(url): #print('wind_up(url={})'.format(url)) tasks.put(url) while True: url = tasks.get() # Work executor.submit(load_url, session, url) threading.Timer(interval=INTERVAL, function=wind_up, args=(url,)).…
has comment: http://stackoverflow.com/comment/91364699
has comment: http://stackoverflow.com/comment/91355364
type: Answer
answers question: http://stackoverflow.com/q/51977594
has comment: http://stackoverflow.com/comment/91356524
accepted answer of: http://stackoverflow.com/q/51977594
has comment: http://stackoverflow.com/comment/91356768
score: 0
type: AcceptedAnswer

http://stackoverflow.com/q/51998046
has comment: http://stackoverflow.com/comment/90945587
has body: I am trying to Combine all printed string get from text file in to one list My Textfile: https://drive.google.com/open?id=18tYvYs43vA7ib3br1h1VD75OUU5ho1u8 My Full Code: allinstall = open("save_all_install.txt", "r",encoding="UTF-8") search_words = ["'DisplayName'"] for line in allinstall: if any(word in line for word in search_words): # Get the front Display Name Part k=line.split('\n')[0] #Get the Position I want for excat display name print(k[17:-5]) list = k[17:-5].split(',') # How do I modified here? list.extend(list) print(list) Original Windows Driver Package - Intel Corporation (iaStorA) HDC (04/10/2017 14.8.16.1063) Windows Driver Package - ASUS (ATP) Mouse (06/17/2015 6.0.0.66) Windows Driver Package - Intel (MEIx64) System (10/03/2017 11.7.0.1045) Windows Driver Package - ASUS (HIDSwitch) System (08/18/2015 1.0.0.5) Expected Result [Windows Driver Package - Intel Corporation (iaStorA) HDC (04/10/2017 14.8.16.1063),Windows Driver Package - ASUS (ATP) Mouse (06/17/2015 6.0.0.66),Windows Driver Package - Intel (MEIx64) System (10/03/2017 11.7.0.1045),Windows Driver Package - ASUS (HIDSwitch) System (08/18/2015 1.0.0.5)]
upvote count: 0
has title: Combine all printed string get from text file in to one list
accepted answer: http://stackoverflow.com/a/51998253
answer count: 1
favorite count: 0
tagged with: python-3.x
tagged with: python
score: -2
type: AnsweredQuestion
tagged with: list
has comment: http://stackoverflow.com/comment/90945502
downvote count: 2
has answer: http://stackoverflow.com/a/51998253
type: Question

http://stackoverflow.com/comment/90932057
score: 0
type: Comment
type: QuestionComment
has text: That sucks, but I don't think there is an obviously better solution. A regex is going to be painful to debug if you don't get it exactly right immediately, and probably less efficient than simply splitting the string into successively smaller parts and picking out the ones you want.
comment on: http://stackoverflow.com/q/51991089

http://stackoverflow.com/comment/91090519
type: AnswerComment
type: Comment
has text: @blhsing It seems like you stopped reading halfway through my comment, and didn't read any of the followups. Starting with "More generally, it works on total orderings, and on partial orderings where everything is either the same as a total ordering or an exception; it does not necessarily work on weird NaN-style orderings. If that's what the OP wants, then yeah, you probably can't use it."
comment on: http://stackoverflow.com/a/52046137
score: 0

http://stackoverflow.com/comment/91078487
comment on: http://stackoverflow.com/a/52052837
type: Comment
has text: My question wasn't really about prediction accuracy but rather how the coefficient estimations between Scikit-Learn and Statsmodels differ in the context of logistic regression. I believe I found the answer in Cross-Validated (see below).
type: AnswerComment
score: 0

http://stackoverflow.com/comment/90884935
comment on: http://stackoverflow.com/q/51966962
score: 0
has text: @jalazbe that gives me the following error: `Command "python setup.py egg_info" failed with error code 1 in /private/tmp/pip-install-juotsd7s/MySQL-python/` in the terminal
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52080683
has answer: http://stackoverflow.com/a/52080794
has comment: http://stackoverflow.com/comment/91112095
linked to: http://stackoverflow.com/q/22391433
has title: add group by back to data frame
type: Question
has comment: http://stackoverflow.com/comment/91111431
has body: I have a dataframe in Pandas as below which is storing name of Team won and Name of stadium where it won as below d={"Winner":["Team1","Team2","Team3","Team1","Team2","Team1"], "Stadium":["S1","S2","S3","S1","S2","S1"]} score=pd.DataFrame.from_dict(d) Now I have performed some calculation with group by on above data frame to find count of each team and match won at a stadium as : score.groupby(by=["Stadium","Winner"]).size().reset_index() Now, I want to add these count values back to my data frame. I am facing issue with multiple group by columns. Any help.
score: 0
tagged with: pandas-groupby
tagged with: pandas
answer count: 1
tagged with: jupyter-notebook
duplicate of: http://stackoverflow.com/q/22391433
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/q/51997029
downvote count: 0
answer count: 1
score: 1
favorite count: 0
has title: How to convert a list of lists, containing lists, into DataFrame
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/51997210
type: AnsweredQuestion
type: Question
has body: Hi I have currently been trying to convert a list of lists of lists into a dataframe. Please see the example below: data = [[[1, 1, 1], [2, 2, 2], [3, 3, 3]], [[4, 4], [5, 5], [6, 6]], [[7], [8], [9]]] and I would like to have a result like this 1 2 3 1 2 3 1 2 3 4 5 6 4 5 6 7 8 9 Could anyone please give me a suggestion or solution? or is there any package being able to handle this problem?
accepted answer: http://stackoverflow.com/a/51997210
tagged with: pandas

http://stackoverflow.com/a/51989713
has comment: http://stackoverflow.com/comment/90939644
type: Answer
score: 1
has body: Is this what your are looking for: import numpy as np pct_fee = np.linspace(0.5, 1.5, num=3) capital = np.linspace(50, 150.0, num=len(pct_fee)) perf_fee = np.linspace(10.0, 20.0, num=len(pct_fee)) returns = np.linspace(5.0, 15.0, num=len(pct_fee)) pct_fee_grid, capital_grid, perf_fee_grid, returns_grid = np.meshgrid(pct_fee, capital, perf_fee, returns) total_fees_grid = capital_grid*returns_grid*perf_fee_grid + capital_grid*pct_fee_grid print(total_fees_grid.shape) # (3, 3, 3, 3)
accepted answer of: http://stackoverflow.com/q/51989237
answers question: http://stackoverflow.com/q/51989237
upvote count: 1
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/a/52051665
has comment: http://stackoverflow.com/comment/131025473
downvote count: 1
score: 17
upvote count: 18
has comment: http://stackoverflow.com/comment/95453497
answers question: http://stackoverflow.com/q/52043378
has body: I found the solution, about how to set proxy authentication globally: import requests import urllib2 import re from requests.auth import HTTPProxyAuth s = requests.Session() proxies = { "http": "http://185.165.193.208:8000", "https": "https://185.165.193.208:8000" } auth = HTTPProxyAuth("gRRT7n", "NMu8g0") s.proxies = proxies s.auth = auth # Set authorization parameters globally ext_ip = s.get('http://checkip.dyndns.org') print ext_ip.text BR, Federico
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/52043378
has comment: http://stackoverflow.com/comment/135249621
type: Answer

http://stackoverflow.com/q/52020410
tagged with: class
tagged with: runtime-error
answer count: 3
has answer: http://stackoverflow.com/a/52020460
accepted answer: http://stackoverflow.com/a/52020460
favorite count: 0
tagged with: constructor
has comment: http://stackoverflow.com/comment/90991213
has answer: http://stackoverflow.com/a/52020432
has title: Python Class() takes no argument error, using self in constructor
tagged with: python
type: AnsweredQuestion
upvote count: 20
has answer: http://stackoverflow.com/a/52020576
has body: When I run this script it returns the error Car() takes no arguments. I'm aware of the need for self parameter and I've included them in all the areas I can think of putting one. How can this error be corrected? class Car(): def __intit__(self, make, model, year): self.make = make self.model = model self.year = year def get_descriptive_name(self): long_name = str(self.year), + &quot; &quot; + self.make + &quot; &quot; + self.model return long_name.title() my_new_car = Car('Chevy', 'sonic', 2015) print(my_new_car.get_descriptive_name())
has comment: http://stackoverflow.com/comment/90991206
downvote count: 1
score: 19
type: Question
possible better answer: http://stackoverflow.com/a/52020432

http://stackoverflow.com/comment/90866461
has text: @DanielPryden Also, unlike Latin-1, cp1252 is a superset of ASCII where `\x80` is `'€'`, instead of a nonprinting control character, so… I probably should have suggested that one first.
type: Comment
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/51957971

http://stackoverflow.com/q/52038874
answer count: 4
downvote count: 0
has comment: http://stackoverflow.com/comment/91028159
has comment: http://stackoverflow.com/comment/91028521
tagged with: google-search-api
linked to: http://stackoverflow.com/q/32680081
has answer: http://stackoverflow.com/a/52869103
linked to: http://stackoverflow.com/q/44076804
tagged with: google-api-php-client
has comment: http://stackoverflow.com/comment/91029725
has comment: http://stackoverflow.com/comment/91028289
type: Question
has answer: http://stackoverflow.com/a/55753108
has comment: http://stackoverflow.com/comment/91028075
has answer: http://stackoverflow.com/a/78179672
score: 10
has answer: http://stackoverflow.com/a/64639387
upvote count: 10
has comment: http://stackoverflow.com/comment/91028409
favorite count: 0
has title: ModuleNotFoundError: No module named 'google'
tagged with: google-api
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91036682
has body: Once I am trying to use google search api it's showing me an error: Traceback (most recent call last): File "C:\Users\Maor Ben Lulu\Desktop\Maor\Python\google\google_Bot.py", line 1, in <module> from google import google ModuleNotFoundError: No module named 'google' My code : from google import google import urllib.request import time from bs4 import BeautifulSoup def google_scrape(url): thepage = urllib.request.urlopen(url) soup = BeautifulSoup(thepage, "html.parser") # print(soup.prettify()) return soup.prettify() ### Rest of the code I did: pip install google But still doesn't work.
tagged with: python

http://stackoverflow.com/q/52082144
type: AnsweredQuestion
tagged with: dataframe
tagged with: numeric
type: Question
tagged with: split
score: 2
answer count: 1
downvote count: 0
accepted answer: http://stackoverflow.com/a/52082243
favorite count: 0
tagged with: python
has body: Many thanks for your helping, I have big problem that I have data frame like below: Name | Book | Location A | Mobile| Hai Long St. 123 B | Sim | Aha 123/456,78;9 I would like to separate like below: Name | Book | Location A | Mobile| 123 B | Sim | 123 B | Sim | 456 B | Sim | 78 B | Sim | 9 How can I do that in python, I don't have any idea for this one. Thank you for you support.
tagged with: extract
upvote count: 2
has answer: http://stackoverflow.com/a/52082243
has title: Extract numeric value in 1 column and add it in new index under parsed index

http://stackoverflow.com/q/51973998
tagged with: lxml
answer count: 1
tagged with: beautifulsoup
tagged with: python-3.x
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51994610
has title: How to add new xml attributes to a set of xml documents?
type: Question
has answer: http://stackoverflow.com/a/51994610
has body: I am normalizing into a pandas dataframe a bunch of xml documents from a directory. However, In order to do it correctly I think it is easier to assign to each xml document an id, for later concatenating all the documents in a single dataframe. Therefore, I tried to add a numerical id as follows: for filepath in glob(os.path.join('../data/trainingFiles/', '*.xml')): with open(filepath) as f: xml_doc = BeautifulSoup(f.read(), 'lxml') for i, sentences in enumerate(xml_doc.find_all("sentence")): sentences['pandas_id'] = str(i) print(sentences) However, the above code is adding to all the sentence attributes different numerical ids inside the same document. How can I assign a different id to each document (i.e. I would like to add the same id to all the elements inside a document)?.. is there any way of carrying a reference of which document I am adding the pandas id attribute?
score: 0

http://stackoverflow.com/comment/91022972
comment on: http://stackoverflow.com/a/52034494
score: 0
type: AnswerComment
has text: But anyway, I can't see anything here that would cause your problem. However, you can make that code more efficient. Don't delete the canvas image item & create a new one. Just update the `photo` attribute of the existing image item.
type: Comment

http://stackoverflow.com/a/52086223
downvote count: 0
has comment: http://stackoverflow.com/comment/91123854
type: Answer
has comment: http://stackoverflow.com/comment/91123165
has comment: http://stackoverflow.com/comment/91123634
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/52086175
has comment: http://stackoverflow.com/comment/91123842
has body: Call groupby with a lambda and iterate over the group object to separate them out into a list of DataFrames: df_list = [g for _, g in df.groupby(by=lambda x: x[:3], axis=1)] If you want a mapping of {prefix : dataFrame} instead, you can create a dictionary: df_dict = {k: g for k, g in df.groupby(by=lambda x: x[:3], axis=1)}
accepted answer of: http://stackoverflow.com/q/52086175
type: AcceptedAnswer

http://stackoverflow.com/comment/91026424
has text: But I need to provide the same input "label_batch" for the generator network? So i need to add labels to g_loss = discriminator_and_classifier_on_generator.train_on_batch( X_train[index * BATCH_SIZE:(index + 1) * BATCH_SIZE, :, :, :], [image_batch, np.ones((100, 1, 64, 64)), label_batch])
type: Comment
comment on: http://stackoverflow.com/a/52036334
score: 1
type: AnswerComment

http://stackoverflow.com/a/52110176
score: 0
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/52109791
type: Answer
has body: You need same types of columns e.g. str: B.columns = B.columns.astype(str) Or int: A.columns = A.columns.astype(int) Then your solution working nice, only added ignore_index=True for avoid duplicated index: X = A.append(B, ignore_index=True)
accepted answer of: http://stackoverflow.com/q/52109791

http://stackoverflow.com/comment/91077240
score: 0
has text: Can you give us an example of links you do want? You'll need to refine your selector.
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/52063354

http://stackoverflow.com/q/52084744
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/55154808
linked to: http://stackoverflow.com/q/49219341
tagged with: python
has title: How to run nbconvert on notebook in google colaboratory
type: Question
has body: I have a simple jupyter notebook, say foo.ipynb. I wish simply to run nbconvert in the usual way: on my local machine I would execute !jupyter nbconvert foo.ipynb in the notebook itself, or jupyter notebook foo.ipynb in a shell. On Google Colaboratory, this does not work. Of course this is because foo.ipynb is not running locally on the drive, but the usual methods to connect Drive and Colab are not working in this case. Question: is running nbconvert on a Colab notebook possible from within a Colab notebook (as in !jupyter nbconvert foo.ipynb), and if so, how? I have tried: (The Colab File Menu options don't do the necessary export, which is why I need nbconvert. Downloading to a local machine and running nbconvert is also not an option here.) The simplest attempt to link to the file directly (when authenticated) !jupyter nbconvert 'https://colab.research.google.com/drive/2pexUcovcblu1Api0F0NezyhZyN2MEMWLhs5ujm?authuser=2 This SO post: Google Colab: how to read data from my google drive? But again no luck, since it can’t seem to find the file and nbconvert only takes a filename. Other approaches suggested in SO posts, including: Is it possible to import my own modules into a google-colaboratory notebook? , Import data into Google Colaboratory , How to run a downloaded Jupyter notebook on Google Colaboratory? How can I accomplish nbconvert on a colab notebook, within the notebook? I can verify that nbconvert is available on colab; it's just not able to find the file under any of the above approaches (so far as I have been able).
score: 5
downvote count: 0
tagged with: google-colaboratory
linked to: http://stackoverflow.com/q/46986398
linked to: http://stackoverflow.com/q/48961866
answer count: 1
tagged with: jupyter-notebook
favorite count: 0
linked to: http://stackoverflow.com/q/48376580
tagged with: nbconvert
upvote count: 5

http://stackoverflow.com/comment/91067150
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52056933
has text: then he obviously has no idea what he's talking about because loops and functions are completely unrelated! functions just get into the game if you write the same loop over and over again.
score: 0

http://stackoverflow.com/q/52033549
score: -3
type: Question
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/9758450
downvote count: 3
has answer: http://stackoverflow.com/a/52033626
duplicate of: http://stackoverflow.com/q/9758450
answer count: 2
has comment: http://stackoverflow.com/comment/91017158
accepted answer: http://stackoverflow.com/a/52033626
upvote count: 0
has body: I have a csv file mentioned as below screen shot ... and i want to convert the whole file in the below format in python.
tagged with: tuples
possible better answer: http://stackoverflow.com/a/52033572
has title: i have table formatted data and wanted to convert into tuple format
tagged with: pandas
tagged with: http://stackoverflow.com/tag/csv
has answer: http://stackoverflow.com/a/52033572
tagged with: python
has comment: http://stackoverflow.com/comment/91017164
favorite count: 0

http://stackoverflow.com/comment/90911919
score: 0
type: Comment
has text: Works like a charm! :) Thanks!
comment on: http://stackoverflow.com/a/51981033
type: AnswerComment

http://stackoverflow.com/a/52081608
has comment: http://stackoverflow.com/comment/91145243
accepted answer of: http://stackoverflow.com/q/52081341
has comment: http://stackoverflow.com/comment/91113714
answers question: http://stackoverflow.com/q/52081341
has comment: http://stackoverflow.com/comment/91145501
has comment: http://stackoverflow.com/comment/91145278
has comment: http://stackoverflow.com/comment/91145434
upvote count: 4
has body: The C++ code needs rework: the goto statement and index increase is equivalent to a continue instruction (you almost never need goto in a C/C++ program, and definitely not here, the original C++ code which is "emulating" continue because the author didn't know that it existed): for (int j = 0; j &lt; circle_radius_vec.size(); ++j) { .. // If ROI is outside of image skip circle if(roi_corner_x &lt; 0){continue;} Note that now you don't need to increase manually the index, as continue skips to the next iteration, calling the ++j of your loop. (the other issue of the incrementation+goto is that if the special case happens at the end of the array, then you can read outside the bounds of the array: undefined behaviour) Now, you can transpose that directly in python: you have 2 options: Either you go with indices (like your C++ code does) for index in range(size): ... if some_condition: continue or just iterate on elements (more pythonic, because it doesn't use indices): for a in the_list: # a is the current element of the list, not the index ... if some_condition: continue In both cases, the for loop controls the iteration. You just tell python to skip to the next iteration with continue, just like in the "new" C++ code.
type: AcceptedAnswer
downvote count: 0
score: 4
has comment: http://stackoverflow.com/comment/91113756
type: Answer

http://stackoverflow.com/q/52087698
tagged with: amazon-ec2
accepted answer: http://stackoverflow.com/a/52088019
has comment: http://stackoverflow.com/comment/91125924
tagged with: postgresql
has title: Relation does not exist django migrations
has body: I'm deploying a django application on an EC2 instance and have the following models.py: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) foto = models.CharField(max_length=200, default="static/batman-for- def __str__(self): return str(self.user.first_name) + " Profile" @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.profile.save() When I login using the django user, I get the following error: ProgrammingError at /admin/login/ relation "profiles_profile" does not exist LINE 1: ..."."profiles_profile" FROM "profiles_... coming from: /home/ubuntu/chimpy/profiles/models.py in save_user_profile instance.profile.save() I've looked into the postgres database and I can't find a table called Profile so I guess my migrations failed, when I run python manage.py showmigrations it shows: admin [X] 0001_initial [X] 0002_logentry_remove_auto_add auth [X] 0001_initial [X] 0002_alter_permission_name_max_length [X] 0003_alter_user_email_max_length [X] 0004_alter_user_username_opts [X] 0005_alter_user_last_login_null [X] 0006_require_contenttypes_0002 [X] 0007_alter_validators_add_error_messages [X] 0008_alter_user_username_max_length [X] 0009_alter_user_last_name_max_length contenttypes [X] 0001_initial [X] 0002_remove_content_type_name sessions [X] 0001_initial but nothing about the other tables (including the profile one). I also want to mention that when I create a super user in the terminal I get the following error: django.db.utils.ProgrammingError: relation "profiles_profile" does not exist LINE 1: INSERT INTO "profiles_profile" ("user_id", "foto", "exchange... what am I doing wrong? Thanks. Edit: my settings.py include the following: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sess…
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/91125995
type: AnsweredQuestion
type: Question
has answer: http://stackoverflow.com/a/52088019
tagged with: amazon-web-services
score: 0
answer count: 1

http://stackoverflow.com/comment/91078455
type: Comment
type: QuestionComment
has text: It *does* work with an instance, but you've failed to *create* an instance...
comment on: http://stackoverflow.com/q/52063759
score: 0

http://stackoverflow.com/a/51978609
has body: I think that jsonpickle will take care of what you call determininstic endocing. Example import jsonpickle class Monopoly(object): def __init__(self): self.boardwalk_price = 500 @property def boardwalk(self): self.boardwalk_price += 50 return self.boardwalk_price m = Monopoly() serialized = jsonpickle.encode(m) Take a look at print (serialized) {"py/object": "__main__.Monopoly", "boardwalk_price": 500} Now, let's decode d = jsonpickle.decode(serialized) print (d) &lt;__main__.Monopoly object at 0x7f01bc093278&gt; d.boardwalk_price 500 For comparing objects,Python uses identifiers. class MyClass(object): def __init__(self, a, b): self.a = a self.b = b c1 = MyClass(1, 2) c2 = MyClass(1, 2) If you take a look at id id(c1) 140154854189040 id(c2) 140154854190440 c1 == c2 False You can override eq operator def __eq__(self, x): if isinstance(x, number): return self.number == x.number return False
answers question: http://stackoverflow.com/q/51978421
score: 0
type: Answer
has comment: http://stackoverflow.com/comment/137357339

http://stackoverflow.com/comment/91184700
type: QuestionComment
has text: @api55 I have but it only effects the background color
comment on: http://stackoverflow.com/q/52107379
score: 0
type: Comment

http://stackoverflow.com/comment/91005646
has text: Please post a full error backtrace. Also, please edit your question instead of posting it as a comment.
comment on: http://stackoverflow.com/q/52016656
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/90993306
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52021254
score: 0
has text: @abarnert, yes, this code repriduce my problem. I added full text of my error.

http://stackoverflow.com/a/52044846
has comment: http://stackoverflow.com/comment/91040732
has comment: http://stackoverflow.com/comment/91041118
type: Answer
accepted answer of: http://stackoverflow.com/q/52044684
upvote count: 6
has body: unstack + stack + reindex x.set_index(['user','movie']).rating.unstack().\ reindex(columns=y).\ stack(dropna=False).\ reset_index(name='rating') Out[40]: user movie rating 0 1 100 1.0 1 1 200 4.0 2 1 300 3.0 3 1 400 NaN 4 2 100 5.0 5 2 200 3.0 6 2 300 NaN 7 2 400 NaN 8 3 100 NaN 9 3 200 NaN 10 3 300 2.0 11 3 400 NaN
answers question: http://stackoverflow.com/q/52044684
score: 6
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/a/52046252
has comment: http://stackoverflow.com/comment/132865414
upvote count: 7
downvote count: 1
has body: There is a known bug with using Sort Imports on __init__.py files. Here is the full solution to put in vscode's .vscode/settings.json: "python.sortImports.args": ["-ns", "__init__.py", "-l", "100"],
answers question: http://stackoverflow.com/q/52046251
type: Answer
score: 6

http://stackoverflow.com/comment/91148275
comment on: http://stackoverflow.com/q/52098893
type: QuestionComment
type: Comment
has text: Possible duplicate of [Find all files in a directory with extension .txt in Python](https://stackoverflow.com/questions/3964681/find-all-files-in-a-directory-with-extension-txt-in-python)
score: 0

http://stackoverflow.com/comment/91120825
type: QuestionComment
has text: The `min(..)` does not care about the key, it sorts the tuples like tuples are sorted *by default*.
score: 0
comment on: http://stackoverflow.com/q/52085276
type: Comment

http://stackoverflow.com/q/52048498
score: 0
has body: I am reading a csv and I want to write to another output csv only the rows that have a specific value in a column. This is my code: import csv import pandas as pd with open('contribs_01.csv', 'r') as file: csv_reader = csv.DictReader(file) with open('01_output.csv', 'w') as new_file: select_fields = ['contributorPersentTypeCd', 'contributorNameLast', 'contributorNameFirst', 'contributorStreetCity', 'contributorStreetStateCd', 'contributorStreetPostalCode', 'contributorOccupation', 'contributorEmployer', 'filerName', 'contributionAmount'] csv_writer = csv.DictWriter(new_file, fieldnames=select_fields, extrasaction='ignore') csv_writer.writeheader() for line in csv_reader: if pd.np.where(csv_writer.contributorPersentTypeCd.str.contains('INDIVIDUAL'): csv_writer.writerow(line) This is the error I get: File "01_donor_read.py", line 17 if pd.np.where(csv_writer.contributorPersentTypeCd.str.contains('INDIVIDUAL'): ^ SyntaxError: invalid syntax
type: Question
has comment: http://stackoverflow.com/comment/91047961
has title: python - read row and write it to file if it contains a specific value in a column
tagged with: http://stackoverflow.com/tag/csv
has comment: http://stackoverflow.com/comment/91109299
has comment: http://stackoverflow.com/comment/91048611
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/91047833
answer count: 0

http://stackoverflow.com/comment/91090376
has text: @VivekKumar Is there any other formula or package can solve this?
score: 0
comment on: http://stackoverflow.com/q/52070293
type: Comment
type: QuestionComment

http://stackoverflow.com/a/51967770
answers question: http://stackoverflow.com/q/51959760
accepted answer of: http://stackoverflow.com/q/51959760
type: AcceptedAnswer
score: 0
type: Answer
has body: You can use Client.get_channel to resolve the channel even if you don't have a reference to the server. I assume below that you always want to send the message to a specific channel no matter where it comes from. discord.py also has special handling of keyword only arguments that allows them to capture the remaining unprocessed text of a message, instead of being split into arguments. In your example, bc(args, message), message would only capture a single word or force you to wrap the message in quotes. @bot.command(pass_context=True) async def bc(ctx, *, message): channel = bot.get_channel("474316889435275264") await bot.send_message(channel, message)

http://stackoverflow.com/comment/91156224
has text: a few things, your body variable should be ```body = ''' New Business Names: {} Affiliate: r2thek Website Link: https://www.sosnc.gov/online_services/search/by_title/_Business_Registration '''``` then do: `msg.attach(MIMEText(body.format(NEW_COMPANIES, 'html'))`
comment on: http://stackoverflow.com/a/52084979
score: 1
type: AnswerComment
type: Comment

http://stackoverflow.com/a/52097863
answers question: http://stackoverflow.com/q/52097582
has comment: http://stackoverflow.com/comment/91146029
has comment: http://stackoverflow.com/comment/91146627
downvote count: 0
type: Answer
has body: very simplified answer: my_colors =['blue', 'yellow', 'red', 'green'] # replace with hex values for i in range(4): photo(my_colors[i]) right(90) photo function then needs to be adjusted to take a keyword, which could look like: def photo(my_color):, and where you use colors in your function, you just call it color(my_color) but of course you need to think about where you will turn after each loop and if you will need to move forward as well.
score: 3
upvote count: 3
has comment: http://stackoverflow.com/comment/91146763
has comment: http://stackoverflow.com/comment/91146088
has comment: http://stackoverflow.com/comment/91146871

http://stackoverflow.com/q/52107249
tagged with: python
score: 3
upvote count: 3
has body: Trying to deal with missing data, I wrote the following model and ran it. The output is given below. Why does the training step on NaN expected values, which are masked by loss_0_where_nan (and the history shows that the loss is indeed evaluated to 0.0), nonetheless introduce NaN weights in the weight matrices of both hidden and max_min_pred? I first thought this might be some weighting of individual parameter learning with output values, which I thought might be specific to the Adadelta optimizer. But it also happens for SGD. import keras from keras.models import Model from keras.optimizers import Adadelta from keras.losses import mean_squared_error from keras.layers import Input, Dense import tensorflow as tf import numpy def loss_0_where_nan(loss_function, msg=""): def filtered_loss_function(y_true, y_pred): with_nans = loss_function(y_true, y_pred) nans = tf.is_nan(with_nans) filtered = tf.where(nans, tf.zeros_like(with_nans), with_nans) filtered = tf.Print(filtered, [y_true, y_pred, nans, with_nans, filtered], message=msg) return filtered return filtered_loss_function input = Input(shape=(3,)) hidden = Dense(2)(input) min_pred = Dense(1)(hidden) max_min_pred = Dense(1)(hidden) model = Model(inputs=[input], outputs=[min_pred, max_min_pred]) model.compile( optimizer=Adadelta(), loss=[loss_0_where_nan(mean_squared_error, "aux: "), loss_0_where_nan(mean_squared_error, "main: ")], loss_weights=[0.2, 1.0]) def random_values(n, missing=False): for i in range(n): x = numpy.random.random(size=(2, 3)) _min = numpy.minimum(x[..., 0], x[..., 1]) if missing: _max_min = numpy.full((len(x), 1), numpy.nan) else: _max_min = numpy.maximum(_min, x[..., 2]).reshape((-1, 1)) # print(x, numpy.array(_min).reshape((-1, 1)), numpy.array(_max_min), sep="\n", end="\n\n") yield x, [numpy.array(_min).reshape((-1, 1)), numpy.array(_max_min)] model.fit_generator(random_values(2, False), steps_per_epoch=2, verbose=False) print("With missing") history = model.fit_generator(random_values(1, Tru…
type: Question
has title: NaN in the expected values, even though masked, introduces NaN in weight matrix
tagged with: missing-data
tagged with: keras
has answer: http://stackoverflow.com/a/52136692
answer count: 1
downvote count: 0
tagged with: nan
favorite count: 0
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/52106360

http://stackoverflow.com/q/52028495
has title: Using Lambda function in sorted
score: 0
answer count: 3
has body: regular unsorted dictionary &gt;&gt;&gt; d = {'banana': 3, 'apple': 4, 'pear': 1, 'orange': 2} dictionary sorted by key &gt;&gt;&gt; OrderedDict(sorted(d.items(), key=lambda t: t[0])) dictionary sorted by value &gt;&gt;&gt; OrderedDict(sorted(d.items(), key=lambda t: t[1])) How lambda function is working in the above lines. what is t[0], t[1]?
has answer: http://stackoverflow.com/a/52028647
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/52028646
has comment: http://stackoverflow.com/comment/91007326
has answer: http://stackoverflow.com/a/52028638
type: Question

http://stackoverflow.com/q/52111376
type: Question
has answer: http://stackoverflow.com/a/79358521
upvote count: 5
tagged with: javascript
has body: I'm working on some research issue which requires me to acquire the exact stack trace when certain JavaScript alters DOM tree. I managed to achieve satisfactory result using MutationObserver combined with console.trace API（sample code is shown below）within Chrome browser, but when I tried to automate this process with selenium webdriver, the extracted log does not contains any stack trace information. var callback = function(mutationsList) { mutationsList.forEach(function (mutation) { switch(mutation.type) { case "attributes": var rect = mutation.target.getBoundingClientRect(); console.log(JSON.stringify(rect)); console.trace(); break; } }); }; new MutationObserver(callback).observe(node, { attributes: true, childList: true }); I also tried to substitute console.trace() API with Error.stack, but within the callback defined by MutationObserver, the outputed stack trace is completely different from that generated by console.trace(). Is there any proper way to get the correct stack trace from chrome to selemium?
score: 5
answer count: 1
downvote count: 0
favorite count: 0
type: UnansweredQuestion
tagged with: python
has title: How to get console.trace() result from Chrome webdriver with selenium?
tagged with: selenium-chromedriver
tagged with: google-chrome
tagged with: webdriver

http://stackoverflow.com/comment/91170100
has text: Try using pd.merge
comment on: http://stackoverflow.com/q/52109791
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/90972269
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/52009449
score: 0
has text: that allows me to open it with open /path/to/hyper.app...but how can I pass a command

http://stackoverflow.com/q/52048653
accepted answer: http://stackoverflow.com/a/52048674
tagged with: not-operator
has title: What's more efficient in Python: `key not in list` or `not key in list`?
answer count: 2
possible better answer: http://stackoverflow.com/a/52049028
tagged with: contains
downvote count: 0
has answer: http://stackoverflow.com/a/52048674
tagged with: in-operator
tagged with: sequence
favorite count: 0
has body: Just found out that both syntax ways are valid. Which is more efficient? element not in list Or: not element in list ?
has answer: http://stackoverflow.com/a/52049028
tagged with: python
duplicate of: http://stackoverflow.com/q/8738388
score: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91048932
upvote count: 2
type: Question

http://stackoverflow.com/q/51958350
type: Question
has answer: http://stackoverflow.com/a/51958459
has comment: http://stackoverflow.com/comment/90867091
has comment: http://stackoverflow.com/comment/90867289
has title: I'm trying to make a connect four game in Python. This is my code for printing the board. Running results in a list index out of range error
has answer: http://stackoverflow.com/a/51958430
has body: Here is my code so far: grid = [["0","1","2","3","4","5","6"], ['.', '.', '.', '.', '.', '.', '.'], ['.', '.', '.', '.', '.', '.', '.'], ['.', '.', '.', '.', '.', '.', '.'], ['.', '.', '.', '.', '.', '.', '.'], ['.', '.', '.', '.', '.', '.', '.'], ['.', '.', '.', '.', '.', '.', '.']] itemNumber = 0 for listItem in range(len(grid)): line = "" elementNumber = 0 for element in range(listItem): elementNumber = elementNumber + 1 elementNumber = int(elementNumber) listItem = grid[[itemNumber][elementNumber]] line = line + str(listItem) print(line) itemNumber = itemNumber + 1 Running the code gives a list index out of range error on line 20. I don't understand why this is happening. In addition, could anyone help me with finding a way to check if there is a win diagonally? I also need help with keeping the code running if someone, say, enters a column that doesn't exist. Any help would be greatly appreciated, and a huge thanks to any contributors in advance.
score: 0
has comment: http://stackoverflow.com/comment/90867366
answer count: 3
has answer: http://stackoverflow.com/a/51958476
has comment: http://stackoverflow.com/comment/90867780
has comment: http://stackoverflow.com/comment/90867593
tagged with: python
tagged with: python-3.x
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90867794

http://stackoverflow.com/comment/90985877
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52017849
has text: Then you probably need to sort the df by `Time` before trying this

http://stackoverflow.com/q/52065842
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/115429862
tagged with: python-3.x
upvote count: 25
has comment: http://stackoverflow.com/comment/92516234
tagged with: python
has answer: http://stackoverflow.com/a/52065942
score: 25
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/113068217
type: Question
linked to: http://stackoverflow.com/q/9942594
downvote count: 0
accepted answer: http://stackoverflow.com/a/52065942
has body: I wrote a python3 script that does some web scraping and stores some information on a CSV file. The script works fine on my computer. The problem happens when I try to run the script on a docker container. The error seems to be on this part of my code (simplified further for the purposes of this question). # default CSV module import csv # this is how an ACTUAL row looks like in my program, included it in case it was important row = {'title': 'Electrochemical sensor for the determination of dopamine in presence of high concentration of ascorbic acid using a Fullerene-C60 coated gold electrode', 'url': 'https://onlinelibrary.wiley.com/doi/abs/10.1002/elan.200704073', 'author': 'Goyal, Rajendra Nath and Gupta, Vinod Kumar and Bachheti, Neeta and Sharma, Ram Avatar', 'abstract': 'A fullerene‐C60‐modified gold electrode is employed for the determination of dopamine in the excess of ascorbic acid using square‐wave voltammetry. Based on its strong catalytic function towards the oxidation of dopamine and ascorbic acid, the overlapping voltammetric …', 'eprint': 'http://www.academia.edu/download/3909892/Dopamene.pdf', 'publisher': 'Wiley Online Library', 'year': '2008', 'pages': '757--764', 'number': '7', 'volume': '20', 'journal': 'Electroanalysis: An International Journal Devoted to Fundamental and Practical Aspects of Electroanalysis', 'ENTRYTYPE': 'article', 'ID': 'goyal2008electrochemical'} # the CSV writer object writer = csv.DictWriter("file.csv", fieldnames=[a, b, c], dialect='toMYSQL') # this is the source of the problem! writer.writerow(row) I understand the containers have only the bare bones and that means that maybe the encoding the script uses is not supported. Thus, I added this to the start of my script: (bellow the usual she-bang) # coding=utf-8 These are the locales on my docker: $ locale -a C C.UTF-8 POSIX en_US.utf8 es_CR.utf8 I have way more on my PC, but that shouldn't change much since en_US.utf8 covers all English stuff and es_CR.utf8 covers all Span…
tagged with: docker
has title: Python, Docker - 'ascii' codec can't encode character
tagged with: http://stackoverflow.com/tag/csv

http://stackoverflow.com/q/52056933
has comment: http://stackoverflow.com/comment/91064739
has answer: http://stackoverflow.com/a/52061471
possible better answer: http://stackoverflow.com/a/52057081
tagged with: pandas
accepted answer: http://stackoverflow.com/a/52061471
tagged with: python
has comment: http://stackoverflow.com/comment/91072102
favorite count: 0
has body: Can anyone help me to understand how I would create a function with def whatever() instead of using a for loop. I'm trying to do thing more Pythonically but don't really understand how to apply a function well instead of a loop. For instance, I have a loop below that works well and gives the output I would like, is there a way to do this with a function? seasons = leaguesFinal['season'].unique() teams = teamsDF['team_long_name'].unique() df = [] for i in seasons: season = leaguesFinal['season'] == i season = leaguesFinal[season] for j in teams: team_season_wins = season['win'] == j team_season_win_record = team_season_wins[team_season_wins].count() team_season_loss = season['loss'] == j team_season_loss_record = team_season_loss[team_season_loss].count() df.append((j, i, team_season_win_record, team_season_loss_record)) df = pd.DataFrame(df, columns=('Team', 'Seasons', 'Wins', 'Losses')) The output looks as follows: Team Seasons Wins Losses 0 KRC Genk 2008/2009 15 14 1 Beerschot AC 2008/2009 11 14 2 SV Zulte-Waregem 2008/2009 16 11 3 Sporting Lokeren 2008/2009 13 9 4 KSV Cercle Brugge 2008/2009 14 15
has comment: http://stackoverflow.com/comment/91067150
has comment: http://stackoverflow.com/comment/91064455
downvote count: 2
upvote count: 1
has comment: http://stackoverflow.com/comment/91064444
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91090605
score: -1
tagged with: loops
has comment: http://stackoverflow.com/comment/91066943
type: Question
has title: Python: replace for loop with function
answer count: 2
tagged with: for-loop
has answer: http://stackoverflow.com/a/52057081
tagged with: function

http://stackoverflow.com/a/52052154
has comment: http://stackoverflow.com/comment/91087628
score: 0
answers question: http://stackoverflow.com/q/52049369
has body: Import functions from sql like this: from pyspark.sql import functions as F Then you can use F.collect_set("field_name")
type: Answer

http://stackoverflow.com/a/52092751
answers question: http://stackoverflow.com/q/52080471
has body: You can easily list consumer groups with kafka-python. Just send a ListGroupsRequest to any of the brokers in your cluster. For example: from kafka import BrokerConnection from kafka.protocol.admin import * import socket bc = BrokerConnection('localhost', 9092, socket.AF_INET) bc.connect_blocking() list_groups_request = ListGroupsRequest_v1() future = bc.send(list_groups_request) while not future.is_done: for resp, f in bc.recv(): f.success(resp) for group in future.value.groups: print(group)
type: Answer
has comment: http://stackoverflow.com/comment/115968106
upvote count: 6
downvote count: 1
accepted answer of: http://stackoverflow.com/q/52080471
score: 5
type: AcceptedAnswer

http://stackoverflow.com/a/52096337
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/91143494
score: 4
type: Answer
answers question: http://stackoverflow.com/q/52095444
has body: Could you try : MERGE (n:item{type:"detergent") ON CREATE SET n.count=1 ON MATCH SET n.count=n.count+1 ON CREATE : when the node doesn't exist ON MATCH : when the node is found in the graph Hope helping.
accepted answer of: http://stackoverflow.com/q/52095444
upvote count: 4

http://stackoverflow.com/q/52111372
score: 0
tagged with: pyqt
answer count: 1
tagged with: python-3.x
type: UnansweredQuestion
tagged with: python
tagged with: qtableview
has title: Change color of rows depending on user input in a QTableView
tagged with: pyqt5
type: Question
has body: I'll start by explaining my goal. An e-commerce order containing several products are loaded into a qtableview. The user of the program will scan the ean codes of the products and if the ean code exist in the qtableview, the row should change colour to green or yellow. If the quantity of one product is greater than 1, the colour should turn yellow untill the quantity of scanned products equal the quantity in the order, The overall goal is to make a quick and easy way to make sure correct products are placed in the correct order. I have found a lot of answers of how to change colours of row permanently, but not how to change colours based on user input and changing values in the model. Example of what i want to achieve.
has answer: http://stackoverflow.com/a/52121088

http://stackoverflow.com/comment/90933246
comment on: http://stackoverflow.com/q/51991764
score: 0
has text: yes libfile is a file name and I want the complete realpath of that. My understanding was the Path function should be able to resolve the realpath of a file in python
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52097744
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91146477
tagged with: netcdf
type: Question
tagged with: int
score: 0
upvote count: 1
answer count: 1
downvote count: 1
has body: I am working with some NetCDF files. In order to produce readable plots, I wish to smooth daily data over long time periods. I did this small function for that: def mov_avg(x,window,min_count=None,axis=-1): import bottleneck as bn yy=np.ma.filled(np.ma.fix_invalid(x),np.nan) yyF=np.ma.masked_all(yy.shape) xtmp=bn.move_mean(yy,window,min_count=min_count,axis=axis) wd1=(window-1)/2 ndim = len(yy.shape) #print xtmp.shape,ndim,axis,window,wd1 if ndim ==1 : #print wd1,-wd1,wd-1 yyF[wd1:-wd1]=np.ma.fix_invalid(xtmp[window-1:]) elif ndim == 2: if axis==-1 or axis==1: yyF[:,wd1:-wd1]=np.ma.fix_invalid(xtmp[:,window-1:]) elif axis==0: yyF[wd1:-wd1,:]=np.ma.fix_invalid(xtmp[window-1:,:]) return yyF unfortunately when I use this function on one of my variable times series as in the following code: for station in stations: for variable in variables: os.chdir(inbasedir + variable + "_albedomodis2/") albmerge = "%s/%s_%s_merged.nc"%(inbasedir + variable + "_albedomodis2/",station,variable) albnc = Dataset(albmerge, 'r+') obs = albnc.variables[variable + '_obs'][:,0,0] obs_smooth = mov_avg(obs,7) I got the following error message: TypeError Traceback (most recent call last) &lt;ipython-input-10-025f4573f745&gt; in &lt;module&gt;() 12 ctessel_alb = albnc.variables[variable + '_ctessel'][:,0,0] 13 ---&gt; 14 obs_smooth = mov_avg(obs,7) 15 16 &lt;ipython-input-3-c01b37a40c9a&gt; in mov_avg(x, window, min_count, axis) 10 if ndim ==1 : 11 #print wd1,-wd1,wd-1 ---&gt; 12 yyF[wd1:-wd1]=np.ma.fix_invalid(xtmp[window-1:]) 13 14 elif ndim == 2: /home/david/anaconda3/lib/python3.6/site-packages/numpy/ma/core.py in __setitem__(self, indx, value) 3351 elif not self._hardmask: 3352 # Set the data, then the mask -&gt; 3353 _data[indx] = dval 3354 _mask[indx] = mval 3355 elif hasattr(indx, 'dtype') and (indx.dtype == MaskType): TypeError: slice indices must be integers or None or have an __index__ method Yes obviously my data is not integer... Does anyone knows how to overcome this error?
has comment: http://stackoverflow.com/comment/91145720
favorite count: 0
has comment: http://stackoverflow.com/comment/91145705
tagged with: python
has answer: http://stackoverflow.com/a/52098519
accepted answer: http://stackoverflow.com/a/52098519
has title: TypeError: slice indices must be integers or None or have an __index__ method on float number time series

http://stackoverflow.com/comment/91106291
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52072074
has text: If you use the Inspect on Chrome you can change the options value
score: 0

http://stackoverflow.com/comment/91021199
type: QuestionComment
has text: @KillPinguin i updated the question with the result of the prints
comment on: http://stackoverflow.com/q/52035388
score: 0
type: Comment

http://stackoverflow.com/q/52049184
has comment: http://stackoverflow.com/comment/91049134
answer count: 1
downvote count: 0
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/52049358
tagged with: python
upvote count: 3
has title: Python table scrape
has comment: http://stackoverflow.com/comment/91049091
type: AnsweredQuestion
score: 3
accepted answer: http://stackoverflow.com/a/52049358
has body: I'm trying to scrape the "Major Stock Indexes table" from https://markets.wsj.com/ and would like to save it to a folder on my desktop. This is what I have so far: import urllib.request import json import re html = urllib.request.urlopen("https://markets.wsj.com/").read().decode('utf8') json_data = re.findall(r'pws_bootstrap:(.*?)\s+,\s+country\:', html, re.S) data = json.loads(json_data[0]) filename = "C:\Users\me\folder\sample.csv" f = open(filename, "w") for numbers in data['chart']: for obs in numbers['Major Stock Indexes']: f.write(str(obs['firstCol']) + "," + str(obs['dataCol']) + "," + str(obs['dataCol priceUp']) + str(obs['dataCol lastb priceUp']) + "\n") print(obs.keys()) I'm getting the error: IndexError: list index out of range Any ideas what might fix my issue?
type: Question

http://stackoverflow.com/comment/91049373
has text: try this : `cv2.cvtColor(cv2.imread("file_name.PNG",cv2.IMREAD_UNCHANGED),cv2.COLOR_BGRA2RGBA)`
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52048578

http://stackoverflow.com/comment/90883838
score: 0
type: AnswerComment
has text: there are only spaces between the numbers
type: Comment
comment on: http://stackoverflow.com/a/51966592

http://stackoverflow.com/a/52091524
has comment: http://stackoverflow.com/comment/91140023
has comment: http://stackoverflow.com/comment/91139744
has comment: http://stackoverflow.com/comment/91133700
has comment: http://stackoverflow.com/comment/91132896
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52091407
score: 1
has comment: http://stackoverflow.com/comment/91133136
answers question: http://stackoverflow.com/q/52091407
has comment: http://stackoverflow.com/comment/91133932
has comment: http://stackoverflow.com/comment/91139427
has comment: http://stackoverflow.com/comment/91140027
has comment: http://stackoverflow.com/comment/91133638
has comment: http://stackoverflow.com/comment/91133080
upvote count: 1
has comment: http://stackoverflow.com/comment/91133250
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/91133606
has comment: http://stackoverflow.com/comment/91133360
has comment: http://stackoverflow.com/comment/91132856
type: Answer
has body: Your prediction variable is an argmax evaluation, which will give you the index of the highest score. Going with a softmax instead should result in the desired output, since softmax transforms your scores into something that can be interpreted as probabilities: X = tf.placeholder(tf.float32, [None, n_steps, n_inputs]) y = tf.placeholder(tf.float32, [None,n_outputs]) probabilities=tf.nn.softmax(y) You can still throw an argmax on top of the probabilities at a later stage to extract the most likely class

http://stackoverflow.com/comment/90938164
score: 0
type: Comment
type: AnswerComment
has text: not writeable sounds like you have a lock on the file
comment on: http://stackoverflow.com/a/51994172

http://stackoverflow.com/a/61681497
downvote count: 0
has body: In Scikit Learn, you can use Polynomial Features to first transform your training data to have more degrees of freedom. After that, you can use Ridge Regression to fit your training data.
type: Answer
upvote count: 3
answers question: http://stackoverflow.com/q/51972637
score: 3

http://stackoverflow.com/comment/91010074
score: 0
type: Comment
type: QuestionComment
has text: Without trying to be difficult, I honestly don't see what it means to say 3 + Poisson is particularly "like Poisson" any more than any other distribution. Many of the values in the Poisson in the question are below 3, so shifting them along will make something that does not look like any Poisson.
comment on: http://stackoverflow.com/q/52029622

http://stackoverflow.com/comment/90962156
type: Comment
type: QuestionComment
has text: `a list` is a SyntaxError, no?
score: 2
comment on: http://stackoverflow.com/q/52006098

http://stackoverflow.com/comment/91011050
has text: @ImportanceOfBeingErnest works perfectly, thanks
score: 0
type: Comment
comment on: http://stackoverflow.com/q/52029797
type: QuestionComment

http://stackoverflow.com/a/52073327
type: Answer
score: 1
has body: Horizontal alignment is done via horizontalalignment or its alias ha, plt.xticks(..., rotation = -45, ha="left")
upvote count: 1
accepted answer of: http://stackoverflow.com/q/52073276
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/52073276

http://stackoverflow.com/comment/91159788
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52104327
score: 0
has text: Possible duplicate of ['numpy.ndarray' object has no attribute 'count'](https://stackoverflow.com/questions/42751662/numpy-ndarray-object-has-no-attribute-count)

http://stackoverflow.com/comment/91263823
comment on: http://stackoverflow.com/q/52063264
score: 0
type: Comment
type: QuestionComment
has text: How do you determine that the background image would not be updated? When I run the code both images are updated. This may become more apparent when setting `vmax=100`.

http://stackoverflow.com/comment/91031394
score: 0
type: QuestionComment
has text: ok I figured out the problem, it was the row after all the data that something the new person saving this excel file did different that it included rows that already don't have any data in the dataframe, so I just deleted the row in the excel with that was blank at the end and it fixed it
type: Comment
comment on: http://stackoverflow.com/q/52040142

http://stackoverflow.com/q/51993725
has comment: http://stackoverflow.com/comment/90937267
has answer: http://stackoverflow.com/a/51993750
has title: Why does the length of calendar not equal 12
has comment: http://stackoverflow.com/comment/90937335
possible better answer: http://stackoverflow.com/a/51993791
type: Question
upvote count: 4
answer count: 2
accepted answer: http://stackoverflow.com/a/51993750
favorite count: 0
has body: I'm new to python and was trying to create a list of month names. I noticed something odd: len(calendar.month_name) == 12 False Can anyone explain to me why the length of month names is not 12? Thanky you for any advice!
tagged with: python
has comment: http://stackoverflow.com/comment/90937290
has comment: http://stackoverflow.com/comment/90937151
has answer: http://stackoverflow.com/a/51993791
type: AnsweredQuestion
score: 2
downvote count: 2

http://stackoverflow.com/q/51999736
tagged with: python
score: 1
upvote count: 1
type: Question
tagged with: dataframe
has answer: http://stackoverflow.com/a/51999765
tagged with: pandas
answer count: 1
downvote count: 0
favorite count: 0
type: UnansweredQuestion
has body: I have a pandas dataframe which is as follows: s = index_df[(index_df['id2'].values == result[z][3])] print s.iloc[:, [0]] which will give me the result id1 36 14559 I'm trying to store the value 14559 into a variable with the following: value = s.iloc[:, [0]] But it keeps giving me an error: ValueError: Incompatible indexer with DataFrame Any idea how i could solve this? EDIT: My dataframe are declared as follows: result: result=[(fuzz.WRatio(n, n2),n2,sdf.index[x],bdf.index[y]) for y, n2 in enumerate(Col2['CSGNE_NAME']) if fuzz.WRatio(n, n2)&gt;80 and len(n2) &gt;= 2 ] And this is how i declare and append to the dataframe: index_df = pd.DataFrame(columns=['id1','id2', 'score']) index_df = index_df.append({'id1':result[z][2], 'id2':result[z][3], 'score':result[z][0]}, ignore_index=True)
has title: Pandas dataframe trying to retrieve integer in dataframe

http://stackoverflow.com/q/52095919
linked to: http://stackoverflow.com/q/29351822
has answer: http://stackoverflow.com/a/52096162
type: UnansweredQuestion
tagged with: python
type: Question
tagged with: smtplib
answer count: 2
has answer: http://stackoverflow.com/a/52096047
tagged with: smtp
score: 0
has body: I'm trying to use SMTPLIB in python to send a message, however I get an error message. I'm positive that the e-mail and passwords used are correct. I have tried to send this with and without signing in via web browser. I have allowed less secure sources from the SENDERS email as the following stackoverflow article states : Error sending email: raise SMTPAuthenticationError(code, resp). I have substituted words instead of actual emails and passwords in the below code: import smtplib server = smtplib.SMTP('smtp.gmail.com', 587) server.starttls() server.login("senderemail", "senderemailpassword") msg = "Hello!" server.sendmail("senderemail", "recieveremail", msg) server.quit() Error message: Traceback (most recent call last): File "D:\Hussain\Hussain's computing\Python\emailingtest.py", line 5, in &lt;module&gt; server.login("senderemail", "senderpassword") File "C:\Users\Hammad\AppData\Local\Programs\Python\Python37-32\lib\smtplib.py", line 730, in login raise last_exception File "C:\Users\Hammad\AppData\Local\Programs\Python\Python37-32\lib\smtplib.py", line 721, in login initial_response_ok=initial_response_ok) File "C:\Users\Hammad\AppData\Local\Programs\Python\Python37-32\lib\smtplib.py", line 642, in auth raise SMTPAuthenticationError(code, resp) smtplib.SMTPAuthenticationError: (534, b'5.7.14 &lt;https://accounts.google.com/signin/continue?sarp=1&amp;scc=1&amp;plt=AKgnsbvT\n5.7.14 ULHSk5VkFjTMqIX_jl5P4GMOarejb0s0WpOqP5RRrWPijD_2GRXQ--JBo5t2r_5pz-ysoY\n5.7.14 Eqv-0GUXB4v321WRxe2uRR1FlFqSTWy-qwXSDmXkkWqwah1akDIy4iw73_mach6-KntI0A\n5.7.14 HLVsfpyrYaTDdeJd54pUPlCEI5W9kZiv48-Ir2-NhbL_rqHrg3OrC-432Uc90Rskt9qNd0\n5.7.14 vAm9r3GQr8jUxrYIgj9YUP0h8xr8HKFFDQSX_RcuTn2lSrXIuy&gt; Please log in via\n5.7.14 your web browser and then try again.\n5.7.14 Learn more at\n5.7.14 https://support.google.com/mail/answer/78754 h7-v6sm8163217wrs.3 - gsmtp') It would be very helpful if someone could fix my code.
tagged with: python-3.7
has title: SMTP acting weirdly
tagged with: python-3.x

http://stackoverflow.com/comment/91104370
type: AnswerComment
comment on: http://stackoverflow.com/a/52054613
score: 0
type: Comment
has text: @EliKorvigo Yup. OP, indexing queries are O(1) at the ends and O(n/2) in the middle. However, for a length 50 deque, I wouldn't worry about that. We're talking 2 -- 4 nanoseconds (5 -- 10%) difference on my system.

http://stackoverflow.com/comment/90933347
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51991675
has text: Thanks @Aran-Fey I was able to understand the mistake in my code because of the hint you provided. For future reference, the issue was that the recursive code was yielding values and I am not yielding those. After your hint, I checked https://stackoverflow.com/questions/8991840/recursion-using-yield and was able to solve. Thanks.
score: 0

http://stackoverflow.com/comment/91128512
score: 1
has text: Possible duplicate of [Is floating point math broken?](https://stackoverflow.com/questions/588004/is-floating-point-math-broken)
comment on: http://stackoverflow.com/q/52089195
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/91212791
has text: @today, may I make a request for the future? If you're going to suggest another site, please let the poster know not to cross-post. You can suggest they delete the copy here before they post elsewhere. Hopefully this will provide a better experience for all. Thank you for listening!
type: QuestionComment
type: Comment
score: 1
comment on: http://stackoverflow.com/q/52020748

http://stackoverflow.com/q/51997027
score: 1
accepted answer: http://stackoverflow.com/a/54275391
tagged with: tensorflow
type: Question
tagged with: google-colaboratory
linked to: http://stackoverflow.com/q/50229091
answer count: 1
downvote count: 0
favorite count: 0
tagged with: jupyter-notebook
has body: I am using the new Google Colaboratory, and I ran a block of code repeatedly that utilized a tf.InteractiveSession before I realized that tf.InteractiveSession.close() was never called. I modified the code and added a sess.close(). Now whenever I run the same code block, I get the following warning: /usr/local/lib/python3.6/dist-packages/tensorflow/python/client/session.py:1645: UserWarning: An interactive session is already active. This can cause out-of-memory errors in some cases. You must explicitly call InteractiveSession.close() to release resources held by the other session(s). warnings.warn('An interactive session is already active. This can ' Whoops. How can I release resources held by the previous sessions I spawned? Even after adding the sess.close() command, this warning persists. I assume I am only closing the active session at this point. I tried refreshing the page, but no luck. Yeah, in case you can't tell I'm not very familiar with the inner workings (including memory management and state persistence) of Jupyter notebooks. This question is very similar to: Is it necessary to close session after tensorflow InteractiveSession()? but I need to know how to actually close the zombie processes, which isn't covered in this answer.
has title: I forgot to close a tf.InteractiveSession, how do I kill any left over processes?
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/54275391
type: AnsweredQuestion

http://stackoverflow.com/a/51992852
type: Answer
score: 0
has comment: http://stackoverflow.com/comment/90935988
has comment: http://stackoverflow.com/comment/90935824
has body: I think this does what you want: import re my_list = ["The Term' means 125 years commencing on and including 01 October 2015.", "125 years commencing on 25th December 1996", "the term of 999 years from the 1st January 2011", ] for item in my_list: new_item = re.sub("\d+\syears", "", item) print(new_item) results: The Term' means commencing on and including 01 October 2015. commencing on 25th December 1996 the term of from the 1st January 2011 Note, you will end up with some extra white space (maybe you want that)? But you could also add this to 'clean' that up: new_item = re.sub("\s+", " ", new_item) because I love regexes: new_item = re.sub("^\s+|\s+$", "", new_item) new_item = new_item.strip()
has comment: http://stackoverflow.com/comment/90935678
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/51989179
answers question: http://stackoverflow.com/q/51989179

http://stackoverflow.com/a/52080180
has body: This library has been written by professional coders, So the problem probably is the version of your python or most likely the library that you downloaded.Your python version is probably 2 because of the syntax in your question and the library must be written in 3. So it is much better to use pip service to get your libraries. Or You can just run this code : import pip pip.main(["install","tweepy"]) In both ways you can get a version of that library that you can use. With all that I recommend installing the python 3.
score: 0
has comment: http://stackoverflow.com/comment/91111221
has comment: http://stackoverflow.com/comment/91111131
has comment: http://stackoverflow.com/comment/91111090
has comment: http://stackoverflow.com/comment/91110387
type: Answer
answers question: http://stackoverflow.com/q/52079801

http://stackoverflow.com/comment/91158142
score: 0
has text: that was it!!! i found two directories lower that a group access for www-data was not granted. now it works! thanks.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52102025

http://stackoverflow.com/q/52101034
type: Question
score: 0
tagged with: tkinter-canvas
has title: Getting height of a canvas create window object python tkinter
tagged with: python-3.x
type: UnansweredQuestion
has body: I have a program where almost everything is placed in a canvas using frames and something like this : ` canvas = Canvas(root,width = 800, height = 800) frame = Frame(root) window = canvas.create_window(10, 10, anchor = "nw", window = frame) And some widgets inside that frame. My question is, how can I get width and height of canvas.create_window when print(canvas.bbox(window) returns (10, 115, 11, 116) and the coordinates where I put it are 10,115, despite the widgets where already in the frame? Thanks
tagged with: python
has comment: http://stackoverflow.com/comment/91192926
tagged with: tkinter
answer count: 0
has comment: http://stackoverflow.com/comment/91153493

http://stackoverflow.com/a/52005562
accepted answer of: http://stackoverflow.com/q/52005525
has comment: http://stackoverflow.com/comment/101616689
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/52005525
type: Answer
upvote count: 2
has body: First cast to strings and then filter by boolean indexing: df = df[(df.astype(str) != '?').all(axis=1)] #alternative solution #df = df[~(df.astype(str) == '?').any(axis=1)] print (df) X Y Z 1 1 2 3 3 4 4 4 Or compare numpy array: df = df[(df.values != '?').all(axis=1)] Details: Compare all converted strings by astype with change condition to !=: print (df.astype(str) != '?') X Y Z 0 True True False 1 True True True 2 False False True 3 True True True 4 False True True And then check if all True values per row: print ((df.astype(str) != '?').all(axis=1)) 0 False 1 True 2 False 3 True 4 False dtype: bool
score: 2
has comment: http://stackoverflow.com/comment/90982728

http://stackoverflow.com/q/51980366
type: Question
has body: I am using matplotlib.pyplot to plot a graph from a Dataframe. I want to show the height of the bar upon each rectangle and am using Text(). For normalising the y-axis, I have taken the log. Below is my code, I am getting error Image size of 1005x132589 pixels is too large. It must be less than 2^16 in each direction When I am not using plt.yscale('log') then the code is working fine. According to some suggestions, I have restarted my kernel too, but still getting this issue. Any suggestions regarding this is welcomed. My Code: # data collected to list. list_alarms = df_region.alarmName # list_east = df_region.EAST list_west = df_region.WEST list_north = df_region.NORTH list_south = df_region.SOUTH # X-ticks customization N = len(list_alarms) xpos = np.arange(N) # this json file is used to update the style of the plot. s = json.load(open('style.json')) rcParams.update(s) # Graph customize plt.rcParams['figure.figsize'] = (15,8) plt.xlabel('AlarmNames at different Regions') plt.ylabel('Frequency for alarms in MNG-PAN devices') plt.title('Alarm Generated by MNG-PAN Device at different Regions') plt.xticks(xpos, list_alarms, rotation = 280) # bar1 = plt.bar(xpos - 0.3,list_east, width = 0.2, label = 'EAST', color = '#3154C8') bar2 = plt.bar(xpos - 0.1, list_west, label = 'WEST', color = '#FF9633') bar3 = plt.bar(xpos + 0.1, list_north, label = 'NORTH', color ='#12B794') bar4 = plt.bar(xpos + 0.3, list_south, label = 'SOUTH', color ='#EF6FE3') plt.yscale('log') plt.legend() def autolabel(rects): for rect in rects: height = rect.get_height() if height &lt; 10000: plt.text(rect.get_x() + rect.get_width()/2., 1.05*height, '%d'%int(height), ha = 'center', va = 'bottom', rotation = 90, fontsize=9) # # autolabel(bar1) autolabel(bar2) autolabel(bar3) autolabel(bar4) plt.show() I am using Jupyter Notebook, Pandas, Python3.
has answer: http://stackoverflow.com/a/62850335
has title: Image size of 1005x132589 pixels is too large. It must be less than 2^16 in each direction
downvote count: 0
has answer: http://stackoverflow.com/a/61164459
score: 47
has answer: http://stackoverflow.com/a/67709486
upvote count: 47
tagged with: pandas
answer count: 7
favorite count: 0
has answer: http://stackoverflow.com/a/63281376
linked to: http://stackoverflow.com/q/11067368
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/78161958
tagged with: python
has answer: http://stackoverflow.com/a/52218203
tagged with: matplotlib
has answer: http://stackoverflow.com/a/56783144

http://stackoverflow.com/a/52005599
score: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/52005295
has comment: http://stackoverflow.com/comment/90961386
type: Answer
has body: You are using a string as an integer here items.remove(items['1']), remove does not work like that. Check this Difference between del, remove and pop on lists
has comment: http://stackoverflow.com/comment/90961855
answers question: http://stackoverflow.com/q/52005295

http://stackoverflow.com/q/52102437
has comment: http://stackoverflow.com/comment/91235885
has comment: http://stackoverflow.com/comment/91264817
tagged with: anaconda
type: Question
has comment: http://stackoverflow.com/comment/91264755
has comment: http://stackoverflow.com/comment/91235812
answer count: 1
downvote count: 0
tagged with: kenlm
has answer: http://stackoverflow.com/a/52213314
favorite count: 0
has comment: http://stackoverflow.com/comment/91379431
has body: When trying to install the python wrapper of kenlm from pip within an anaconda environment, I get the error: (lm_1b) adamg:lm_1b adamg$ pip install https://github.com/kpu/kenlm/archive/master.zip Collecting https://github.com/kpu/kenlm/archive/master.zip Cache entry deserialization failed, entry ignored Downloading https://github.com/kpu/kenlm/archive/master.zip - 4.4MB 51.1MB/s Installing collected packages: kenlm Running setup.py install for kenlm ... error Complete output from command /Users/adamg/anaconda2/envs/lm_1b/bin/python -u -c "import setuptools, tokenize;__file__='/private/var/folders/2l/hd8b8vx566ld71lfd8hjglbc0000gn/T/pip-9yzty3hd-build/setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record /var/folders/2l/hd8b8vx566ld71lfd8hjglbc0000gn/T/pip-aff_d2b8-record/install-record.txt --single-version-externally-managed --compile: running install running build running build_ext building 'kenlm' extension creating build creating build/temp.macosx-10.9-x86_64-3.6 creating build/temp.macosx-10.9-x86_64-3.6/util creating build/temp.macosx-10.9-x86_64-3.6/lm creating build/temp.macosx-10.9-x86_64-3.6/util/double-conversion creating build/temp.macosx-10.9-x86_64-3.6/python clang -Wno-unused-result -Wsign-compare -Wunreachable-code -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -I/Users/adamg/anaconda2/envs/lm_1b/include -arch x86_64 -I/Users/adamg/anaconda2/envs/lm_1b/include -arch x86_64 -I. -I/Users/adamg/anaconda2/envs/lm_1b/include/python3.6m -c util/pool.cc -o build/temp.macosx-10.9-x86_64-3.6/util/pool.o -O3 -DNDEBUG -DKENLM_MAX_ORDER=6 -std=c++11 In file included from util/pool.cc:1: In file included from ./util/pool.hh:4: /Users/adamg/anaconda2/envs/lm_1b/bin/../include/c++/v1/cassert:21:10: fatal error: 'assert.h' file not found #include &lt;assert.h&gt; ^~~~~~~~~~ 1 error generated. error: command 'clang' failed with exit status 1 -----------------------…
has comment: http://stackoverflow.com/comment/91236047
tagged with: python
upvote count: 6
has comment: http://stackoverflow.com/comment/91235842
accepted answer: http://stackoverflow.com/a/52213314
score: 6
has comment: http://stackoverflow.com/comment/91377993
has title: Cannot install kenlm package in anaconda environment
has comment: http://stackoverflow.com/comment/91235955
type: AnsweredQuestion

http://stackoverflow.com/q/51981916
favorite count: 0
has body: In the following code why same symbol * shows different behavior for matrices and arrays? Why doesn't it show element-wise multiplication in case of matrices? a= np.arange(2*3).reshape(2,3) print(a) b= np.array([[0,0,0],[1,1,1]]) print(b) c= a*b print(c) d=np.matrix([[1,2],[3,4]]) e= np.matrix([[0,0],[1,1]]) f= d*e print("d: ",d,"e: ",e) print(f)
type: UnansweredQuestion
tagged with: python
upvote count: 3
has answer: http://stackoverflow.com/a/51982109
type: Question
has title: Why same symbol shows element wise multiplication for array and matrix like multiplication for matrics?
tagged with: numpy
score: 3
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/90935189

http://stackoverflow.com/comment/91091679
comment on: http://stackoverflow.com/q/52070528
type: QuestionComment
has text: Before appending successors, you should check if they are in `CLOSED` (that's the raison d'être of that varaible.
type: Comment
score: 0

http://stackoverflow.com/comment/91002303
has text: thanks for accepting, but I think I can propose a better answer finally. I'll try to in a few days @Thiplol
type: AnswerComment
comment on: http://stackoverflow.com/a/52011531
type: Comment
score: 0

http://stackoverflow.com/q/51983391
type: Question
tagged with: python
tagged with: large-data
upvote count: 2
linked to: http://stackoverflow.com/q/38895768
has title: Preprocess huge data with a custom data generator function for keras
answer count: 1
has body: Actually I'm building a keras model and I have a dataset in the msg format with over 10 million instances with 40 features which are all categorical. For the moment i'm using just a sample of it since reading all the dataset and encoding it is impossbile to fit into the memory. Here a part of the code i'm using: import pandas as pd from category_encoders import BinaryEncoder as be from sklearn.preprocessing import StandardScaler def model(): model = Sequential() model.add(Dense(120, input_dim=233, kernel_initializer='uniform', activation='selu')) model.add(Dense(12, kernel_initializer='uniform', activation='sigmoid')) model.compile(SGD(lr=0.008),loss='mean_squared_error', metrics=['accuracy']) return model def addrDataLoading(): data=pd.read_msgpack('datum.msg') data=data.dropna(subset=['s_address','d_address']) data=data.sample(300000) # taking a sample of all the dataset to make the encoding possible y=data's_address','d_address' x=data.drop(['s_address','d_address'],1) encX = be().fit(x, y) numeric_X= encX.transform(x) encY=be().fit(y,y) numeric_Y=encY.transform(y) scaler=StandardScaler() X_all=scaler.fit_transform(numeric_X) x_train=X_all[0:250000,:] y_train=numeric_Y.iloc[0:250000,:] x_val=X_all[250000:,:] y_val=numeric_Y.iloc[250000:,:] return x_train,y_train,x_val,y_val x_train,y_train,x_val,y_val=addrDataLoading() model.fit(x_train, y_train,validation_data=(x_val,y_val),nb_epoch=20, batch_size=200) So my question is how to use a custom data generator function to read and process all the data I have and not just a sample, and then use fit_generator() function to train my model? EDIT This is a sample of the data: netData I think that taking different samples from the data results in different encoding dimensions. For this sample there's 16 different categories: 4 addresses (3 bit), 4 hostnames (3 bit ), 1 subnetmask (1 bit), 5 infrastructures (3 bit ), 1 accesszone(1 bit ), so the binary encoding will give us 11 bit and the new dimension of the data is 11 …
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51989379
score: 2
downvote count: 0
tagged with: keras
favorite count: 0

http://stackoverflow.com/a/52058264
downvote count: 0
has body: Here's one NumPy based solution - def extend_arrs(x,y,frame): # Convert to arrays frame = np.asarray(frame) x = np.asarray(x) y = np.asarray(y) l = frame[-1]-frame[0] + 1 id_ar = np.zeros(l,dtype=int) id_ar[frame-frame[0]] = 1 idx = id_ar.cumsum()-1 return np.r_[frame[0]:frame[-1]+1],x[idx], y[idx] Sample run - In [164]: x Out[164]: [80.1, 80.2, 80.1, 80.2, 80.3] In [165]: y Out[165]: [40.1, 40.2, 40.1, 40.2, 40.3] In [166]: frame = [5,6,8,11,13] In [167]: extend_arrs(x,y,frame) Out[167]: (array([ 5, 6, 7, 8, 9, 10, 11, 12, 13]), array([80.1, 80.2, 80.2, 80.1, 80.1, 80.1, 80.2, 80.2, 80.3]), array([40.1, 40.2, 40.2, 40.1, 40.1, 40.1, 40.2, 40.2, 40.3])) # Output in tabular format for quick reference In [168]: np.c_[extend_arrs(x,y,frame)] Out[168]: array([[ 5. , 80.1, 40.1], [ 6. , 80.2, 40.2], [ 7. , 80.2, 40.2], [ 8. , 80.1, 40.1], [ 9. , 80.1, 40.1], [10. , 80.1, 40.1], [11. , 80.2, 40.2], [12. , 80.2, 40.2], [13. , 80.3, 40.3]])
type: Answer
answers question: http://stackoverflow.com/q/52057927
score: 3
upvote count: 3

http://stackoverflow.com/comment/90897780
type: Comment
type: QuestionComment
has text: Would you please post a link to the data?
comment on: http://stackoverflow.com/q/51972637
score: 0

http://stackoverflow.com/comment/91072651
comment on: http://stackoverflow.com/q/52060936
score: 0
type: Comment
type: QuestionComment
has text: `c2` are not characters in your string, `\xc2` is a character

http://stackoverflow.com/comment/90941799
has text: I made the edit with the code now.
type: Comment
comment on: http://stackoverflow.com/a/51995943
score: 0
type: AnswerComment

http://stackoverflow.com/comment/91083237
score: 0
type: Comment
has text: @JeremyCollier Doh! Yes, apologies, I missed this bit out! Typing too fast I think XD Glad it helped and worked. I've edited my question to take include the model parameter, could you please mark it off as the correct answer when you get a chance! :D
comment on: http://stackoverflow.com/a/52065849
type: AnswerComment

http://stackoverflow.com/a/52047865
has comment: http://stackoverflow.com/comment/91082062
has comment: http://stackoverflow.com/comment/91122314
has body: Well If you want to do it on a click of a button, you can make the button part of an html form and have it post to your flask application: @app.route('/update') def val(): return render_template("index.html",data=data) This would work, considering the value you want to pass to the html is called data. To display the data passed through, your html should look like this: &lt;p&gt;{{data}}&lt;/p&gt; Instead of updating the modbus value every two seconds, you could do it only when the button is clicked like so: @app.route('/update') def val(): #code to get the value return render_template("index.html",data=data) This way everytime you click the form button to get a new value, then the data is read from the database. Instead of using another file as an import and using datetime, this would make sure that your program not only saves memory but still returns the desired value. In the now method, you should write to a txt file as such: #get the data f = open("mod.txt", w+) f.write(data) f.close Then when you recive the button click in the flask app: @app.route('/update') def val(): f = open("mod.txt",r) data = f.read() f.close() return render_template("index.html",data=data) To make sure that the other program is running you can do this: if __name__ == '__main__': execfile('modbusreginfo.py') app.run(host= 'localhost', port=5000, debug=False, threaded=True) If you want to make the page reload every 2 seconds so there is no button click you can add this to your html: &lt;meta http-equiv="Refresh" content="2"&gt;
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/91047843
has comment: http://stackoverflow.com/comment/91122562
has comment: http://stackoverflow.com/comment/91097230
has comment: http://stackoverflow.com/comment/91046992
type: Answer
answers question: http://stackoverflow.com/q/52047489
has comment: http://stackoverflow.com/comment/91122418
has comment: http://stackoverflow.com/comment/91110733
has comment: http://stackoverflow.com/comment/91081890
has comment: http://stackoverflow.com/comment/91046846
has comment: http://stackoverflow.com/comment/91118864
accepted answer of: http://stackoverflow.com/q/52047489
upvote count: 2
score: 2
has comment: http://stackoverflow.com/comment/91082168

http://stackoverflow.com/a/52075218
has body: You are attempting to fit again your classifier with your test data: y_pred = classifier.fit(X_test) which is of course not possible without passing also the labels (hence the error for missing y); I assume that what you actually want to do is to get predictions for your test data, in which case you shoud use predict, and not fit: y_pred = classifier.predict(X_test)
has comment: http://stackoverflow.com/comment/91100024
upvote count: 2
has comment: http://stackoverflow.com/comment/91153203
has comment: http://stackoverflow.com/comment/91100064
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/52075125
score: 2

http://stackoverflow.com/comment/90991668
comment on: http://stackoverflow.com/q/52020651
score: 1
has text: Which operating system and package manager are you using? It depends.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91016054
score: 0
type: Comment
type: QuestionComment
has text: Can you also post your serializers and your entire view code?
comment on: http://stackoverflow.com/q/52031799

http://stackoverflow.com/a/51977044
score: 1
answers question: http://stackoverflow.com/q/51976878
type: Answer
upvote count: 1
has body: DOWNLOAD_DELAY is a Scrapy setting: The amount of time (in secs) that the downloader should wait before downloading consecutive pages from the same website. This can be used to throttle the crawling speed to avoid hitting servers too hard. time.sleep is a Python library function that can add a delay to your code. Scrapy can download multiple items at the same time (see CONCURRENT_ITEMS or CONCURRENT_REQUESTS_PER_IP, for example). The DOWNLOAD_DELAY will add a delay between requests to a target and take care of the sleeping logic between requests. Using time.sleep would require handling a lot of the logic yourself i.e. while (more requests): make_a_request(...) time.sleep(2 seconds) etc. Using DOWNLOAD_DELAY is preferred because you're letting Scrapy do what it does best. But the meaning of the delay can change depending on other settings (such as CONCURRENT_REQUESTS_PER_IP): [I]f CONCURRENT_REQUESTS_PER_IP is non-zero, download delay is enforced per IP, not per domain.
downvote count: 0

logging
tags question: http://stackoverflow.com/q/52001694
tags question: http://stackoverflow.com/q/52057356
tags question: http://stackoverflow.com/q/52098131
tags question: http://stackoverflow.com/q/51986961
tags question: http://stackoverflow.com/q/52105854
tag name: logging
tags question: http://stackoverflow.com/q/52086417
tags question: http://stackoverflow.com/q/52086974
tags question: http://stackoverflow.com/q/51961643
tags question: http://stackoverflow.com/q/51976776
tags question: http://stackoverflow.com/q/52050755
tags question: http://stackoverflow.com/q/52061465
tags question: http://stackoverflow.com/q/52005076
tags question: http://stackoverflow.com/q/52056020
tags question: http://stackoverflow.com/q/52020503
tags question: http://stackoverflow.com/q/52007482
tags question: http://stackoverflow.com/q/52005019
tags question: http://stackoverflow.com/q/52012564
tags question: http://stackoverflow.com/q/51998753
tags question: http://stackoverflow.com/q/52062224
type: Tag
tags question: http://stackoverflow.com/q/52072144

http://stackoverflow.com/comment/91144475
comment on: http://stackoverflow.com/q/52094320
has text: Aren't latitude and longitude meant to be considered together? Give two points (x1,y1) and (x2,y2), why do you iterate over (x1,y1), (x1,y2), (x2,y1), (x2,y2)?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52051667
linked to: http://stackoverflow.com/q/18449360
favorite count: 0
has answer: http://stackoverflow.com/a/52051912
has comment: http://stackoverflow.com/comment/91053518
tagged with: python
type: AnsweredQuestion
upvote count: 0
tagged with: syntax
duplicate of: http://stackoverflow.com/q/33990673
has body: I need to create empty arrays inside an array in order to fill each one of them differently in a loop later on but I couldn't figure out the correct syntax. I tried something like this: verilerimiz = [arrayname1[], arrayname2[], arrayname3[], arrayname4[], arrayname5[]] Bu it gives a syntax error. I really appreciate some help.
type: Question
accepted answer: http://stackoverflow.com/a/52051801
possible better answer: http://stackoverflow.com/a/52051912
has answer: http://stackoverflow.com/a/52051697
score: -2
tagged with: arrays
has comment: http://stackoverflow.com/comment/91053568
has comment: http://stackoverflow.com/comment/91053522
linked to: http://stackoverflow.com/q/33990673
has answer: http://stackoverflow.com/a/52051801
downvote count: 2
answer count: 3
has title: Writing an arrays inside an array in python

http://stackoverflow.com/comment/90869376
has text: @klaus Just... define the function and snap it to the class like you're changing one of it's attributes. It's as straightforward as it gets.
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/51959176
type: Comment

signals-slots
tags question: http://stackoverflow.com/q/51989969
type: Tag
tag name: signals-slots

http://stackoverflow.com/q/51994754
answer count: 1
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51995291
tagged with: pycharm
tagged with: http://stackoverflow.com/tag/json
has title: pycharm run command not escaping properly
has body: I'm trying to run airflow in docker via pycharm. Everything works fine when I run unit tests. When I try to do a cli command, though, it seems to be interpreting my arguments... strangely. Here is what I pass to airflow at the command line via pycharm: trigger_dag etl_pipeline --conf '{"client":"popsicle"}' The script path refers to airflow itself, so this should be equivalent to calling: airflow &lt;above command&gt; When airflow loads up it throws the following trace: Traceback (most recent call last): File "/opt/.pycharm_helpers/pydev/pydevd.py", line 1668, in &lt;module&gt; main() File "/opt/.pycharm_helpers/pydev/pydevd.py", line 1662, in main globals = debugger.run(setup['file'], None, None, is_module) File "/opt/.pycharm_helpers/pydev/pydevd.py", line 1072, in run pydev_imports.execfile(file, globals, locals) # execute the script File "/opt/.pycharm_helpers/pydev/_pydev_imps/_pydev_execfile.py", line 18, in execfile exec(compile(contents+"\n", file, 'exec'), glob, loc) File "/opt/project/venv/bin/airflow", line 27, in &lt;module&gt; args.func(args) File "/usr/local/lib/python3.6/site-packages/airflow/bin/cli.py", line 199, in trigger_dag execution_date=args.exec_date) File "/usr/local/lib/python3.6/site-packages/airflow/api/client/local_client.py", line 27, in trigger_dag execution_date=execution_date) File "/usr/local/lib/python3.6/site-packages/airflow/api/common/experimental/trigger_dag.py", line 49, in trigger_dag run_conf = json.loads(conf) File "/usr/local/lib/python3.6/json/__init__.py", line 354, in loads return _default_decoder.decode(s) File "/usr/local/lib/python3.6/json/decoder.py", line 339, in decode obj, end = self.raw_decode(s, idx=_w(s, 0).end()) File "/usr/local/lib/python3.6/json/decoder.py", line 357, in raw_decode raise JSONDecodeError("Expecting value", s, err.value) from None json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0) When I set a debugger at the point which is breaking, I see that the string looks like this…
type: Question
tagged with: airflow
score: 0
has answer: http://stackoverflow.com/a/51995291

http://stackoverflow.com/comment/90956734
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52003643
has text: 1. Fix the indentation. 2. What do you expect `self.__name` in `__init__` to do? 3. The usage of Getters and Setters (as you implemented it) is quite uncommon in Python. 4. The second definition of the `employee` method overwrites the first. 5. The whole code looks like you're trying to write Java in Python.
score: 0

http://stackoverflow.com/comment/91068572
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52058437
has text: I am tempted to replace the while loop by a more pythonic writing, as for example `for _ in range(t):` if the iteration number is not needed inside the loop?
score: 0

http://stackoverflow.com/comment/91002022
comment on: http://stackoverflow.com/q/52016793
type: QuestionComment
type: Comment
has text: Interesting endeavor, but in the end StackOverflow is not an online debugger. The best way to tackle this is to add a lot of logging statements, logging the intermediate states of a few runs and compare them against correct encryption and/or decryption using a known good implementation.
score: 1

http://stackoverflow.com/comment/91107654
type: QuestionComment
type: Comment
has text: There are a few possible causes for this. Have you seen: https://stackoverflow.com/questions/9769496/celery-received-unregistered-task-of-type-run-example Setting the public IP of the instance is helpful in these situations too, if you can do that
comment on: http://stackoverflow.com/q/52077984
score: 0

http://stackoverflow.com/comment/90911936
comment on: http://stackoverflow.com/a/51980665
score: 1
type: AnswerComment
has text: @Painter Consider the text `hello`, if you'd like to match just the initial tag ``. The regex `<.*>` will match the whole text because `.*` will match `a>hello<a/`. If you use `<.*?>` instead the `.*?` matches only `a`. In this case instead of `<` and `>` you have 4 newlines. If you let `.*` with `re.DOTALL` you will endup putting many "middle blocks" into just the `.*`, by making it non-greedy using `.*?` you avoid this behaviour.
type: Comment

http://stackoverflow.com/a/52034462
accepted answer of: http://stackoverflow.com/q/52015855
type: AcceptedAnswer
score: 0
has body: Finally I got the solution after spending nearly 3 days, it was mxnet library which was causing problem. After trying different cuda toolkit and mxnet libraries following combination worked for me :- 1) Cuda Toolkit - 9.2 Mxnet lbrary : mxnet-cu92 version 1.2.0b20180525 (Failing for most of the recent versions ) 2) Cuda Toolkit - 8.0 Mxnet lbrary : mxnet-cu80 version 0.11.0 (Failing for most of the recent versions ) thanks
type: Answer
answers question: http://stackoverflow.com/q/52015855

http://stackoverflow.com/a/52071111
type: Answer
score: 2
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52070949
answers question: http://stackoverflow.com/q/52070949
upvote count: 2
type: AcceptedAnswer
has body: Use merge + np.where for a more succinct solution: v = df1.merge(df2, on=['Type']) v['Time'] = np.where(v['Speed'], v.pop('Fast'), v.pop('Slow')) Name Type Speed Time 0 a x 1 2 1 a y 0 5 2 a z 1 4
has comment: http://stackoverflow.com/comment/91233857

http://stackoverflow.com/q/52011463
tagged with: pip
has answer: http://stackoverflow.com/a/60408932
type: Question
has title: Make a program (aws cli) accessible for all users, installed by pip
has comment: http://stackoverflow.com/comment/90974206
tagged with: aws-cli
tagged with: ubuntu
has body: i installed aws-cli using sudo pip install awscli when i run awscli as current user it works but when i run try to run awscli as other user i get sudo -u jenkins aws Traceback (most recent call last): File "/usr/local/bin/aws", line 19, in &lt;module&gt; import awscli.clidriver File "/usr/local/lib/python2.7/dist-packages/awscli/clidriver.py", line 17, in &lt;module&gt; import botocore.session File "/usr/local/lib/python2.7/dist-packages/botocore/session.py", line 28, in &lt;module&gt; import botocore.client File "/usr/local/lib/python2.7/dist-packages/botocore/client.py", line 16, in &lt;module&gt; from botocore import waiter, xform_name File "/usr/local/lib/python2.7/dist-packages/botocore/waiter.py", line 13, in &lt;module&gt; import jmespath ImportError: No module named jmespath
score: 0
answer count: 1
accepted answer: http://stackoverflow.com/a/60408932
has comment: http://stackoverflow.com/comment/90980488
has comment: http://stackoverflow.com/comment/90991334
has comment: http://stackoverflow.com/comment/90993428
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90974760

http://stackoverflow.com/a/51997240
score: 0
type: Answer
answers question: http://stackoverflow.com/q/51995857
has body: While this sort of grouping may seem dangerous and haphazard at first, it turns out to be rather well behaved. The key here, is that when you pass a Series as a grouping object to DataFrame.groupby() it by default aligns the series on the indices. Typically, you would group a DataFrame by one of its own columns, in which case alignment on index is virtually guaranteed. But in this case, because both DataFrames have country as their index pandas appropriately aligns the values in life with the correct region and calculates the mean. The two DataFrames can even be ordered differently, and can have a different number of total elements, and calculations will behave properly. The following three examples should illustrate this point: Sample Data import pandas as pd df1 = pd.DataFrame({'Country': ['A', 'B', 'C', 'D', 'E'], 'val': [1, 2, 3, 4, 5]}) df2 = pd.DataFrame({'Country': ['E', 'D', 'C', 'B', 'A'], 'region': ['region1', 'region1', 'region2', 'region2', 'region2']}) df3 = pd.DataFrame({'Country': ['E', 'D', 'C', 'B'], 'region': ['region1', 'region1', 'region2', 'region2']}) df4 = pd.DataFrame({'Country': ['E', 'D', 'C', 'B', 'A', 'Z'], 'region': ['region1', 'region1', 'region2', 'region2', 'region2', 'region7']}) df1 = df1.set_index('Country') df2 = df2.set_index('Country') df3 = df3.set_index('Country') df4 = df4.set_index('Country') Case 1: Both DataFrames share the same indices, and are the same length, but they are not sorted in the same way. df1.groupby(df2.region).mean() # val #region #region1 4.5 #region2 2.0 Because the Series are first aligned on index, the average value of each region is still calculated correctly. region1 contains 'E' and 'D' which have a value of 4 and 5 Case 2: The grouping DataFrame is shorter in length and doesn't contain all of the countries in the DataFrame to be grouped df1.groupby(df3.region).mean() # val #region #region1 4.5 #region2 2.5 Again, the calculation works properly. 'A' has no region, so it's no longer included, and the …

mxnet
tags question: http://stackoverflow.com/q/51996906
tags question: http://stackoverflow.com/q/52008294
type: Tag
tags question: http://stackoverflow.com/q/52015855
tag name: mxnet
tags question: http://stackoverflow.com/q/52027323
tags question: http://stackoverflow.com/q/52045999

http://stackoverflow.com/comment/129982038
type: QuestionComment
type: Comment
has text: If your function returns a tuple of integers, the variables `a` and `b` will contain integers. No matter which type hints you'll use.
score: 0
comment on: http://stackoverflow.com/q/52082939

http://stackoverflow.com/comment/91019239
comment on: http://stackoverflow.com/a/52029841
score: 0
type: AnswerComment
type: Comment
has text: The clarification on the use of WebDriverWait and putting in a try: block helped. Works more stable now, and prints an error for each ticker failed to fetch instead of throwing an exception.

http://stackoverflow.com/a/52103411
has body: How about this: class Kid(): def __init__(self, name): self.name = name def __eq__(self, other): return self.name == other def __ne__(self, other): return not self.name == other def __hash__(self): return hash(self.name) def is_cool(kid): cool_kids = {"Jim","Bill","Nebuchadnezzar II"} return kid in cool_kids if __name__ == "__main__": print is_cool(Kid("Bob")) print is_cool(Kid("Jim")) print is_cool(Kid("Bill")) Result: False True True You need to override both __eq__ and __hash__, because both need to be satisfied from an element to be member of a hashtable. When Python evaluates if an element is a member of a hashtable, it first looks at whether hash matches, and if it does then it looks at equality. Overriding __ne__ is not necessary for this example, but it is a good practice to do so, you don't want equals and not equals to be out of sync.
accepted answer of: http://stackoverflow.com/q/52103163
answers question: http://stackoverflow.com/q/52103163
score: 1
has comment: http://stackoverflow.com/comment/91200351
upvote count: 1
type: AcceptedAnswer
type: Answer
has comment: http://stackoverflow.com/comment/91157962
downvote count: 0

http://stackoverflow.com/comment/91109240
has text: drwxr-xr-x 2 root root 4096 Aug 28 18:28 /home/django/media_cdn/
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/52064821
type: Comment

http://stackoverflow.com/a/52013908
answers question: http://stackoverflow.com/q/52013452
type: AcceptedAnswer
has body: I find the solution. It is not direct but quite simple. I changed os.system("python import_test.py") to os.system(sys.executable + ' import_test.py'). This makes the shell uses the Pycharm remote interpreter(miniconda3), not original.
accepted answer of: http://stackoverflow.com/q/52013452
type: Answer
score: 0

http://stackoverflow.com/comment/91184980
has text: Yes Sir, its working. Thanks a lot for the help. One more doubt, I want to have a separate column which will keep the ONLY Last value of "VALUE" column also. is it possible..?
type: AnswerComment
type: Comment
score: 1
comment on: http://stackoverflow.com/a/52109571

http://stackoverflow.com/a/52058615
type: AcceptedAnswer
downvote count: 0
type: Answer
upvote count: 3
has body: You are misunderstanding what super() does. super() does not alter the type of the self reference. super(..., self).method() will still pass in that self reference to the method being called, so self is, in all three cases, the Grandchild() instance. That means that in all cases, self.aux_func() follows the normal attribute resolution order, and for Grandchild() instances, self.aux_func() will always find Child.aux_func and call that. Put differently, the only lookup that is altered, is the attribute you look up on the super() object itself. If you need more such alterations, you need to use super() again, or you need to give your aux_func() functions different names per class. One way to do that is to make the methods class private. The latter can be done by naming your function with two underscores at the start (but not at the end). Such names are then altered at compile time to inject the class names in all places that it is referenced: class Parent: def __aux_func(self): # class private to Parent return "[parent aux]" def main_func(self): # any reference to __aux_func *in this class* will use # the Parent class-private version print("[parent main]" + self.__aux_func()) class Child(Parent): def __aux_func(self): # class private to Child return "[child aux]" def main_func(self): # any reference to __aux_func *in this class* will use # the Child class-private version print("[child main]" + self.__aux_func()) See the Reserved classes of identifiers documentation: __* Class-private names. Names in this category, when used within the context of a class definition, are re-written to use a mangled form to help avoid name clashes between “private” attributes of base and derived classes. and the Identifiers (Names) section: Private name mangling: When an identifier that textually occurs in a class definition begins with two or more underscore characters and does not end in two or more underscores, it is considered a private name of that class. Private names are transforme…
answers question: http://stackoverflow.com/q/52058400
score: 3
accepted answer of: http://stackoverflow.com/q/52058400

http://stackoverflow.com/comment/90999109
has text: The `TemplateView` (which is basically a `View` with `TemplateMixin`) does some extra magic: it for example has separate functions where one can change the context, engine, etc.: https://github.com/django/django/blob/master/django/views/generic/base.py#L108 It thus more "separates" logic into atomic subelements. Usually class-based views can be useful if you want for example to *subclass* behavior. Furthermore it is more declarative style.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52024378

http://stackoverflow.com/comment/91107965
has text: This was it. It wasn't that I needed to transform the point, but that I needed to change the projection being used in the creation of the axis.
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/52065654

http://stackoverflow.com/comment/90955876
has text: Just a quick bit of feedback as I didn't actually close down the tab yesterday, that is definitely not how to use a dict haha, it'd be better as a list (`d[(sheet.cell(r, 1).value), (sheet...` to `lst.append((sheet.cell(r, 1).value), (sheet...`). Also you may not know, instead of `for EmployeeID in excel_data`, you can also do `for FirstName, LastName, Email1, EmployeeID in excel_data`, which then makes it easier to read what is what :)
type: AnswerComment
comment on: http://stackoverflow.com/a/51993443
score: 0
type: Comment

http://stackoverflow.com/q/52074590
has answer: http://stackoverflow.com/a/52074591
tagged with: urllib
score: 9
type: Question
upvote count: 9
downvote count: 0
tagged with: ssl
has title: urllib.request.urlopen: SSL: CERTIFICATE_VERIFY_FAILED Error on Windows >=Vista (7/8/10/Server 2008) on Python >=3.4
has body: Trying to use Python 3 urlopen on many HTTPS sites on recent (>=Vista) Windows machines I get "SSL: CERTIFICATE_VERIFY_FAILED" errors when trying to do an urllib.request.urlopen on many sites (on some build machines even https://www.google.com/, but curiously never on https://www.microsoft.com/). &gt;&gt;&gt; import urllib.request &gt;&gt;&gt; urllib.request.urlopen("https://www.google.com/") Traceback (most recent call last): File "C:\Python35\lib\urllib\request.py", line 1254, in do_open h.request(req.get_method(), req.selector, req.data, headers) File "C:\Python35\lib\http\client.py", line 1106, in request self._send_request(method, url, body, headers) File "C:\Python35\lib\http\client.py", line 1151, in _send_request self.endheaders(body) File "C:\Python35\lib\http\client.py", line 1102, in endheaders self._send_output(message_body) File "C:\Python35\lib\http\client.py", line 934, in _send_output self.send(msg) File "C:\Python35\lib\http\client.py", line 877, in send self.connect() File "C:\Python35\lib\http\client.py", line 1260, in connect server_hostname=server_hostname) File "C:\Python35\lib\ssl.py", line 377, in wrap_socket _context=self) File "C:\Python35\lib\ssl.py", line 752, in __init__ self.do_handshake() File "C:\Python35\lib\ssl.py", line 988, in do_handshake self._sslobj.do_handshake() File "C:\Python35\lib\ssl.py", line 633, in do_handshake self._sslobj.do_handshake() ssl.SSLError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c :645) During handling of the above exception, another exception occurred: Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "C:\Python35\lib\urllib\request.py", line 163, in urlopen return opener.open(url, data, timeout) File "C:\Python35\lib\urllib\request.py", line 466, in open response = self._open(req, data) File "C:\Python35\lib\urllib\request.py", line 484, in _open '_open', req) File "C:\Python35\lib\urllib\request.py", line 444, in _call_chain result = func(*a…
answer count: 1
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion
tagged with: windows
tagged with: python
linked to: http://stackoverflow.com/q/19268548

http://stackoverflow.com/comment/90928133
type: Comment
has text: You replaced that tag with the _awk_ tag. The likely cause of the downvotes here is that you are asking other people to do your work for you without showing any efforts of your own.
comment on: http://stackoverflow.com/q/51987069
score: 1
type: QuestionComment

http://stackoverflow.com/comment/91046118
has text: Are units always 2-characters long?
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/52047532

http://stackoverflow.com/a/51985311
answers question: http://stackoverflow.com/q/51984799
has body: This code worked for me : output.writerow(row.replace('\"','').split(',')) Thank you so much for everyone.
upvote count: 1
type: Answer
downvote count: 0
score: 1

http://stackoverflow.com/comment/91083488
score: 0
type: Comment
type: QuestionComment
has text: BTW, it's better form to hardcode the list -- `['git', 'pull', 'origin', 'master']`, without the `shlex.split()` involvement. You'll be glad you went that route when you need to be able to substitute in values that can contain spaces without needing to worry about shell-equivalent escaping first.
comment on: http://stackoverflow.com/q/52065865

http://stackoverflow.com/comment/90934268
comment on: http://stackoverflow.com/q/51990714
type: QuestionComment
type: Comment
score: 1
has text: That's one way to do it. On the other hand metadata is not required to be bound to a particular engine. Reflection methods etc. optionally take a connectable as an argument. Not entirely sure, but I'd imagine that you could also reconfigure the metadata to use another connectable as bind.

http://stackoverflow.com/comment/91022249
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52035759
type: AnswerComment
has text: @JonClements oops my bad. missed the `s` I was using `writer.writerow(zip(x, y))` instead of `writer.writerows(zip(x, y))`

timer
tag name: timer
type: Tag
tags question: http://stackoverflow.com/q/51987810
tags question: http://stackoverflow.com/q/52056924
tags question: http://stackoverflow.com/q/51993957

http://stackoverflow.com/a/52058584
accepted answer of: http://stackoverflow.com/q/52058140
type: Answer
downvote count: 0
score: 1
has body: This is a textbook example of why you don't modify a list in-place. The culprit is this loop: for ii in list1: # removing numbers, out of range if ii &lt; 101101 or ii &gt;= 1000000: list1.remove(ii) The initial parts of list1 are all going to be 5 digits long, as you already noticed. List iterators step along by index. Let's take a look at what happens when you remove an element from a list of 5-digit numbers: Start with a list, and ii referencing the first number: 10001, 20002, 30003, 40004, ... ^ ii Remove ii from the list: 20002, 30003, 40004, ... ii -&gt; 10001 ii is still a valid reference, but not to an item in the list. The list has naturally shifted back by one element. Continue the loop to the next element: 20002, 30003, 40004, ... ^ ii Hopefully you can see how that skips adjacent elements that you want to filter out. You have a number of viable workarounds. Here are a few to get you started: Use a list comprehension to make a new list: list1 = [x for x in list1 if len(x) &gt; 5] Get rid of the offending loop entirely, and only append a string to the list on the first loop if it's longer than the retirement. Iterate backwards, so the shifts don't affect you: for ii in reversed(list1): if ii &lt; 101101 or ii &gt;= 1000000: list1.remove(ii) OR for ii in range(len(list1), -1, -1): if list1[ii] &lt; 101101 or list1[ii] &gt;= 1000000: del list1[ii] Personally, I'd recommend option 2 since it's the least hassle in the end. You don't even need to check the length of the string, just whether the number is greater than 99999.
upvote count: 1
answers question: http://stackoverflow.com/q/52058140
type: AcceptedAnswer

http://stackoverflow.com/q/52017297
tagged with: python
has comment: http://stackoverflow.com/comment/90986556
has comment: http://stackoverflow.com/comment/90989523
answer count: 0
type: UnansweredQuestion
score: 1
tagged with: image-processing
upvote count: 1
linked to: http://stackoverflow.com/q/4325733
tagged with: scipy
type: Question
has comment: http://stackoverflow.com/comment/90996771
has body: I have written a thing in python that takes an image as an input, and writes the output as a triangle tessellated version of the input image. For example this image of a kitten: gets transformed into this: But when I try to save the image, somehow I get a white border around it which I can't seem to get rid of. The code that takes care of saving the image is as follows: my_dpi=100 figSize = imageWidth / float(my_dpi), imageHeight / float(my_dpi) fig = plt.figure(figsize=figSize) ax = fig.add_axes([0, 0, 1, 1]) ax.invert_yaxis() for triangle, eColor, fColor in zip(tris.simplices, triColors, triColors): p = Polygon([tris.points[i] for i in triangle], closed=True, facecolor=fColor, edgecolor=eColor) ax.add_patch(p) ax.axis('tight') ax.set_axis_off() ax.get_xaxis().set_visible(False) ax.get_yaxis().set_visible(False) outfile_name = "%s-%s-%s.png" % (sys.argv[1].split('.')[0], str(tris.simplices.shape[0]), str(i)) fig.savefig(outfile_name, bbox_inches='tight', pad_inches=0, dpi=my_dpi) tris is just a triangulation object that comes from scipy's delaunay triangulation module. I use that to calculate the color of each triangle and add a polygon patch for each triangle in the for loop. The final set of patches gets written to an image when the figure is saved onto the file. Because of the white background of this website, you might not be able to see the white border, but if you open the output image link, the white border is clearly visible there. I've tried everything that I could think of but can't seem to get rid of this white border. Is there a special way to get rid of it if I'm saving the figure using polygon patches?
has comment: http://stackoverflow.com/comment/90984662
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/90989390
has comment: http://stackoverflow.com/comment/91100207
has comment: http://stackoverflow.com/comment/90995832
tagged with: image
has comment: http://stackoverflow.com/comment/90995994
has comment: http://stackoverflow.com/comment/90984624
downvote count: 0
has comment: http://stackoverflow.com/comment/91100340
favorite count: 0
has title: Unable to remove white border while saving figure in python matplotlib?

http://stackoverflow.com/q/52006499
tagged with: selenium-webdriver
tagged with: selenium-chromedriver
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90964976
accepted answer: http://stackoverflow.com/a/52009785
tagged with: selenium
upvote count: 1
downvote count: 1
type: Question
has answer: http://stackoverflow.com/a/52010500
has body: I ran the following commands to get my selenium grid / hub up and running: hub: java -jar selenium-server-standalone-3.14.0.jar -role hub node: java -jar selenium-server-standalone-3.14.0.jar -role node -hub http://localhost:4444/grid/register when I check the hub console, I see that my webdriver is registered, and ready to use... I connected to the hub via: driver = webdriver.Remote( command_executor='http://localhost:4444/wd/hub', desired_capabilities=DesiredCapabilities.CHROME) and it connects fine...however, if i don't have chromedriver (like if I was to do it w/o grid) downloaded and installed in $PATH, the application fails. Is this normal? I was under the impression, the whole point of selenium-grid and all this remote logic was to ensure that the individual drivers don't need to be installed on the "client" machine.
has title: Selenium grid not working without chromedriver local install
has comment: http://stackoverflow.com/comment/90963130
possible better answer: http://stackoverflow.com/a/52010500
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/52009785
favorite count: 0
tagged with: python

http://stackoverflow.com/q/52084820
tagged with: python
has comment: http://stackoverflow.com/comment/91201982
has comment: http://stackoverflow.com/comment/91202129
answer count: 0
type: UnansweredQuestion
tagged with: oauth-2.0
tagged with: django
has title: Writing my own custom back-end in Django
type: Question
tagged with: django-oauth
has body: I am trying to build an application which consumes a third party API. I want to implement OAuth2 in my application using that API. Now, I am able to receive the authorization token, followed by an access token and refresh token. But, I am lost after this! How do I use those tokens to authenticate those users in my application? I could not find any tutorial regarding this. Please help me here. In a way, I want to know how python-social-auth implements the authentication back-end. That would also help, I guess. Thank you!
score: 0

http://stackoverflow.com/q/52098142
has body: Attaching the error that is generated....Someone please help *** Python 3.6.5 (v3.6.5:f59c0932b4, Mar 28 2018, 16:07:46) [MSC v.1900 32 bit (Intel)] on win32. *** *** Remote Python engine is active *** &gt;&gt;&gt; *** Remote Interpreter Reinitialized *** &gt;&gt;&gt; Traceback (most recent call last): File "J:\CODE\MINI\SignIn.py", line 24, in loginCheck con=cx_Oracle.connect('system/oracle@localhost:1521/xe') cx_Oracle.DatabaseError: DPI-1050: Oracle Client library must be at version 11.2 or higher Exit code: 0 &gt;&gt;&gt;
type: Question
has answer: http://stackoverflow.com/a/52098603
upvote count: 0
has title: Python cx_Oracle connection error......Attaching the error
score: -1
has comment: http://stackoverflow.com/comment/91147255
answer count: 1
favorite count: 0
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/91302209
downvote count: 1

http://stackoverflow.com/q/51968626
has body: I am encountering something a bit strange (to me) in tensorflow and was hoping someone could shed some light on the situation. I have a simple neural network that processes images. The cost function I am minimizing is the simple MSE. At first I implemented the following: cost = tf.square(DECONV - Y) which I then passed to my optimizer as follows: optimizer = tf.train.RMSPropOptimizer(learning_rate).minimize(cost) I was able to obtain great results with this implementation. However, as I tried to implement a regularizer, I realized that I wasn't passing a scalar value to the optimizer.minimize() but in fact passing a tensor of shape [batch, dim_x, dim_y]. I changed my implementation to the following: cost = tf.losses.mean_squared_error(Y, DECONV) as well as many variations of this like: cost = tf.reduce_mean(tf.square(tf.subtract(DECONV, Y))) etc. My issue is that with these new implementations of the MSE I am not able to even come close to the results I obtained using the original "wrong" implementation. Is the original way a valid way to train? If so, how can I implement regularizers? If not, what am I doing wrong with the new implementations? Why can't I replicate the results?
tagged with: python
tagged with: conv-neural-network
score: 1
upvote count: 1
tagged with: tensorflow
type: Question
has answer: http://stackoverflow.com/a/51970704
tagged with: deep-learning
answer count: 1
downvote count: 0
has title: Tensor Flow passing a tensor to optimizer minimize function trains better
favorite count: 0
type: UnansweredQuestion

http://stackoverflow.com/comment/90945426
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51997925
has text: If the timestamp is `pd.Timestamp('2018-01-01 12:15:00')` It must be `pd.Timestamp('2018-01-01 12:15:00')` not `pd.Timestamp('2018-01-01 12:30:00')`
type: AnswerComment

http://stackoverflow.com/q/52070514
has comment: http://stackoverflow.com/comment/91091050
has comment: http://stackoverflow.com/comment/91093869
has comment: http://stackoverflow.com/comment/91091428
has body: I am using pytesseract in the below code: def fnd(): for fname in list: x = None x = np.array([np.array(PIL.Image.open(fname))]) print x.size for im in x: txt = pytesseract.image_to_string(image=im).encode('utf-8').strip() open("Output.txt","a+").write(txt) with open("Output.txt") as openfile: for line in openfile: for part in line.split(): if "cyber" in part.lower(): print(line) return The list contains names of images from a folder (2408*3506 &amp; 300 res Gray-scaled). Unfortunately for around 35 images the total processing time is around 1400-1500 seconds. Is there a way I can reduce the processing time?
has comment: http://stackoverflow.com/comment/91090993
type: Question
has comment: http://stackoverflow.com/comment/91091140
upvote count: 3
answer count: 1
has comment: http://stackoverflow.com/comment/91091221
tagged with: ocr
favorite count: 0
has comment: http://stackoverflow.com/comment/91092582
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/91093368
tagged with: tesseract
score: 3
has comment: http://stackoverflow.com/comment/91091233
tagged with: python-tesseract
has title: Pytesseract is too slow. How can I make it process images faster?
downvote count: 0
has answer: http://stackoverflow.com/a/55525810

http://stackoverflow.com/comment/91135696
type: Comment
comment on: http://stackoverflow.com/a/52092468
has text: @ZeeBmChan: in that case tell your collegue that using SecureRandom is not how passwords are converted into keys (the implementation may change in different versions). Using a cryptographic hash or PBKDF is much more feasible (safe).
score: 0
type: AnswerComment

http://stackoverflow.com/a/51999209
score: 12
has comment: http://stackoverflow.com/comment/131792489
type: AcceptedAnswer
downvote count: 0
has body: Convert your string to datetime object. Ex: import datetime plus_one_hour = datetime.datetime.strptime("21:00:00", "%H:%M:%S") + datetime.timedelta(hours=2) print(plus_one_hour.strftime("%H:%M:%S")) Output: 23:00:00
type: Answer
has comment: http://stackoverflow.com/comment/90947501
answers question: http://stackoverflow.com/q/51999177
accepted answer of: http://stackoverflow.com/q/51999177
upvote count: 12

http://stackoverflow.com/comment/90883054
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51966516
score: 2
has text: What exactly are you trying to do? Is this a refresh for something? Maybe there is a better way than sending a keystroke.

http://stackoverflow.com/comment/91058776
comment on: http://stackoverflow.com/q/52053697
type: Comment
type: QuestionComment
has text: do you want your model to be updated after receiving each sample ?
score: 0

http://stackoverflow.com/a/52067650
answers question: http://stackoverflow.com/q/52067591
has body: You can apply the decorators to each method of your MyClassTestCase class individually, thereby specifying the order in which to evaluate the decorators for each method. Basically change: @mock.patch.object(MyMockClass, '_some_function', return_value=False) @mock.patch.object(MyMockClass, '_another_function', return_value=False) class MyClassTestCase(TestCase): def test_that_it_works(self, *args): # do test stuff To: class MyClassTestCase(TestCase): @mock.patch.object(MyMockClass, '_some_function', return_value=False) @mock.patch.object(MyMockClass, '_another_function', return_value=False) def test_that_it_works(self, mock_another, mock_some): # do test stuff
type: AcceptedAnswer
downvote count: 0
type: Answer
score: 1
upvote count: 1
accepted answer of: http://stackoverflow.com/q/52067591

http://stackoverflow.com/q/52107617
has body: I am trying to use vectorization on a pandas dataframe to create a new column. The dataframe is fairly huge(millions of records). I am showing a dummy example here. I am showing a non vecotorised version which works but is not very efficient. I am trying to implement the vectorised version while using the function(the actual function is fairly complicated than the one shown here). import pandas as pd import numpy as np df = pd.DataFrame({'Type':list('ABBC'), 'Set':list('ZZXY')}) df['color'] = np.where(df['Set']=='Z', 'green', 'red') def test(row): if row['color'] =='green': value='Green' elif row['color'] =='red': value=row['Type'] else: value=row['Set'] return value def test1(s,t,c): if c =='green': value='Green' elif c =='red': value=t else: value=s return value df['new_color']=df.apply(test,axis=1) #df['new_color']=test1(df.Set,df.Type,df.color) print(df) Set Type color new_color 0 Z A green Green 1 Z B green Green 2 X B red B 3 Y C red C Any help would be appreciated.
score: 0
tagged with: pandas
tagged with: python
type: UnansweredQuestion
type: Question
has answer: http://stackoverflow.com/a/52107641
answer count: 1
has title: Creating column in pandas using vectorization

http://stackoverflow.com/comment/91148985
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/52082123
has text: if `driver.get()` takes long, it means the page loads for a long time. It could be your network, browser, or any other number of causes, but not anything you could fix directly in your code. BTW you set `driver.set_page_load_timeout(10)` after getting the page, which is a bit too late, rather set it before the loop, after loading driver. So 2 things: 1 - Does it load for equally long time if you load it manually? 2 - I would pause the test and look at browser's network tab to see what is taking long time (e.g. DNS resolution...etc)
type: Comment

http://stackoverflow.com/comment/90946313
type: AnswerComment
comment on: http://stackoverflow.com/a/51994268
score: 0
type: Comment
has text: It's no problem at all. :-)

http://stackoverflow.com/comment/90917791
type: Comment
comment on: http://stackoverflow.com/a/51980640
type: AnswerComment
has text: thanks guys, it is solved now. Thanks to Bruno here.
score: 0

http://stackoverflow.com/q/52044392
tagged with: python-3.x
has body: How print tabs (long spaces) between 2 characters of a string, in Python using loops and not the "\t" tab? (or in loops, if possible") For Example : a="HELLO" so the output must be H E L L O
linked to: http://stackoverflow.com/q/36901
tagged with: python
tagged with: list
has comment: http://stackoverflow.com/comment/91040533
type: UnansweredQuestion
downvote count: 2
tagged with: loops
upvote count: 1
has comment: http://stackoverflow.com/comment/91039688
has comment: http://stackoverflow.com/comment/91039796
type: Question
linked to: http://stackoverflow.com/q/12786102
has comment: http://stackoverflow.com/comment/91039634
has answer: http://stackoverflow.com/a/52044426
score: -1
has answer: http://stackoverflow.com/a/52044463
has answer: http://stackoverflow.com/a/52044476
answer count: 3
tagged with: arrays
has title: How print tabs (long spaces) between 2 characters of a string, in Python
favorite count: 0

http://stackoverflow.com/comment/90901487
has text: doesn't work. Error: ImportError: cannot import name 'patterns'
comment on: http://stackoverflow.com/q/51975139
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/90938491
has text: @azonips I've edited the question, to include a solution to your problem!
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51969877

http://stackoverflow.com/a/51999345
type: AcceptedAnswer
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/90998005
accepted answer of: http://stackoverflow.com/q/51999096
has body: You want two or three characters at the start of the string followed by a dot and then maybe a space. As a regular expression this looks like ^\w{2,3}\. ?. Now you can use re.sub to replace this part with an empty string. cleaned_name = re.sub(r'(^\w{2,3}\. ?)', r'', name)
upvote count: 1
answers question: http://stackoverflow.com/q/51999096
score: 1

http://stackoverflow.com/comment/91156461
comment on: http://stackoverflow.com/a/52084685
has text: Thanks for the explanation! But doesn't Series's any return one of the matching items instead of bool result?
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/a/51964862
has body: THIS ANSWERS THE ORIGINAL VERSION OF THE QUESTION. In SQL, you can use window functions: select customerid, location, sum(price), (sum(price) / sum(sum(price)) over (partition by customerid) as ratio from t group by customerid, location;
upvote count: 2
has comment: http://stackoverflow.com/comment/90880051
type: Answer
score: 2
accepted answer of: http://stackoverflow.com/q/51964771
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/51964771
has comment: http://stackoverflow.com/comment/90882324

http://stackoverflow.com/a/52060277
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/91075470
has comment: http://stackoverflow.com/comment/91074859
accepted answer of: http://stackoverflow.com/q/52059893
has body: You could implement it like this: &gt;&gt;&gt; test = None &gt;&gt;&gt; test.strip() if test is not None else "fallback" 'fallback' In your code this would look like: def parse_project(self, response): yield { 'author': response.xpath('//a[@rel="author"]/text()').extract(), 'name': response.xpath('//strong[@itemprop="name"]/a/text()').extract(), 'tags': [x.strip() for x in response.xpath('//a[contains(@class, "topic-tag")]/text()').extract()], 'about': response.xpath('//*[@itemprop="about"]/text()').extract_first().strip(), 'lang_name': response.xpath('//span[@class = "lang"]/text()').extract(), 'lang_perc' : response.xpath('//span[@class = "percent"]/text()').extract(), 'stars': response.xpath('//a[contains(@aria-label, "starred")]/text()').extract_first().strip(), 'forks': response.xpath('//a[contains(@aria-label, "forked")]/text()').extract_first().strip(), 'commits': response.xpath('//a[contains(., "commits")]/span/text()').extract_first().strip(), 'contributors': response.xpath('//a[contains(., "contributor")]/span/text()').extract_first().strip() if response.xpath('//a[contains(., "contributor")]/span/text()').extract_first() is not None else None, 'last_commits': None }
upvote count: 1
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/52059893
type: Answer

http://stackoverflow.com/q/52077814
type: Question
score: 3
has title: How to extract only a specific part of url in Python and add its value as another column in df for every row?
tagged with: dataframe
has answer: http://stackoverflow.com/a/52078072
answer count: 2
tagged with: pandas
possible better answer: http://stackoverflow.com/a/52078072
downvote count: 0
has answer: http://stackoverflow.com/a/52077845
favorite count: 0
has comment: http://stackoverflow.com/comment/91105326
tagged with: python
type: AnsweredQuestion
has body: I have a df containing user and url looking like this. df User Url 1 http://www.mycompany.com/Overview/Get 2 http://www.mycompany.com/News 3 http://www.mycompany.com/Accountinfo 4 http://www.mycompany.com/Personalinformation/Index ... I want to add another column page that only takes the second part of the url, so I'd be having it like this. user url page 1 http://www.mycompany.com/Overview/Get Overview 2 http://www.mycompany.com/News News 3 http://www.mycompany.com/Accountinfo Accountinfo 4 http://www.mycompany.com/Personalinformation/Index Personalinformation ... My code below is not working. slashparts = df['url'].split('/') df['page'] = slashparts[4] The error I'm getting AttributeError Traceback (most recent call last) &lt;ipython-input-23-0350a98a788c&gt; in &lt;module&gt;() ----&gt; 1 slashparts = df['request_url'].split('/') 2 df['page'] = slashparts[1] ~\Anaconda\lib\site-packages\pandas\core\generic.py in __getattr__(self, name) 4370 if self._info_axis._can_hold_identifiers_and_holds_name(name): 4371 return self[name] -&gt; 4372 return object.__getattribute__(self, name) 4373 4374 def __setattr__(self, name, value): AttributeError: 'Series' object has no attribute 'split'
upvote count: 3
accepted answer: http://stackoverflow.com/a/52077845

http://stackoverflow.com/comment/90924470
comment on: http://stackoverflow.com/a/51986006
type: AnswerComment
score: 0
type: Comment
has text: @JRCX - Hmmm, I think problem is if missing some value like `df1 = pd.DataFrame({ 'First': ['A','A','B','B','C'], 'Second': ['B','C','C','D','D'], 'Value': [1,2,4,5,6]} )` pandas always create 2d matrix and added NaNs. I think it is normal for real data.

http://stackoverflow.com/a/52062861
score: 3
upvote count: 3
has body: You don't need to call next(). You are already iterating over the lines of the file, so, don't do anything, and the next line will come at the next iteration. elif clientid not in line: pass Unrelated to file reading: You if-elseif-else doesn't make sense. clientid in line is either true or false, so it doesn't make sense to have 3 conditions. Just remove the middle elif altogether`
answers question: http://stackoverflow.com/q/52062803
has comment: http://stackoverflow.com/comment/91076548
downvote count: 0
type: Answer

http://stackoverflow.com/a/52016247
type: Answer
upvote count: 3
score: 3
has body: Here is a code using solve_ivp interface from Scipy (instead of odeint) to obtain a numerical solution: import numpy as np from scipy.integrate import solve_ivp from scipy.integrate import cumtrapz import matplotlib.pylab as plt # Define the parameters as regular Python function: def k(s): return 1 def t(s): return 0 # The equations: dz/dt = model(s, z): def model(s, z): T = z[:3] # z is a (9, ) shaped array, the concatenation of T, N and B N = z[3:6] B = z[6:] dTds = k(s) * N dNds = -k(s) * T + t(s) * B dBds = -t(s)* N return np.hstack([dTds, dNds, dBds]) T0, N0, B0 = [1, 0, 0], [0, 1, 0], [0, 0, 1] z0 = np.hstack([T0, N0, B0]) s_span = (0, 6) # start and final "time" t_eval = np.linspace(*s_span, 100) # define the number of point wanted in-between, # It is not necessary as the solver automatically # define the number of points. # It is used here to obtain a relatively correct # integration of the coordinates, see the graph # Solve: sol = solve_ivp(model, s_span, z0, t_eval=t_eval, method='RK45') print(sol.message) # &gt;&gt; The solver successfully reached the end of the integration interval. # Unpack the solution: T, N, B = np.split(sol.y, 3) # another way to unpack the z array s = sol.t # Bonus: integration of the normal vector in order to get the coordinates # to plot the curve (there is certainly better way to do this) coords = cumtrapz(T, x=s) plt.plot(coords[0, :], coords[1, :]); plt.axis('equal'); plt.xlabel('x'); plt.xlabel('y'); T, N and B are vectors. Therefore, there are 9 equations to solve: z is a (9,) array. For constant curvature and no torsion, the result is a circle:
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/52014550
downvote count: 0
answers question: http://stackoverflow.com/q/52014550

http://stackoverflow.com/a/52083250
downvote count: 0
type: Answer
has body: new = [e*2 if i == 3 else e for k in someListofLists for i,e in enumerate(k)]
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/52083104

http://stackoverflow.com/a/52104565
answers question: http://stackoverflow.com/q/52094979
type: Answer
downvote count: 0
score: 1
has body: Python scripts can not be run online, however the major feature of recently-released PsychoPy version 3 is the ability to generate Javascript experiments that can be run online from the https://pavlovia.org server. You can, however, use the Pavlovia server to host and share Python experiment code files online, but that is just for storage and distribution: they can't be executed in the browser. See here for an announcement: https://discourse.psychopy.org/t/psychopy3-launch-event-online-experiments-and-new-experiment-server/4721 Questions at this level (i.e. not specific code problems) are better suited to be taken to the community at https://discourse.psychopy.org rather than here at StackOverflow, which is oriented towards answering code questions that other people might find useful.
accepted answer of: http://stackoverflow.com/q/52094979
upvote count: 1
type: AcceptedAnswer

http://stackoverflow.com/comment/90971677
type: Comment
comment on: http://stackoverflow.com/a/52010315
type: AnswerComment
has text: It's not helpful to talk about one particular implementation on one particular platform with such an unrealistic data set.
score: 0

http://stackoverflow.com/q/51972479
score: 23
has answer: http://stackoverflow.com/a/52086299
type: Question
downvote count: 0
linked to: http://stackoverflow.com/q/42391009
tagged with: google-cloud-vision
tagged with: google-cloud-platform
accepted answer: http://stackoverflow.com/a/52086299
answer count: 1
has comment: http://stackoverflow.com/comment/95573631
favorite count: 0
has title: Get Lines and Paragraphs, not symbols from Google Vision API OCR on PDF
tagged with: python
upvote count: 23
type: AnsweredQuestion
has body: I am attempting to use the now supported PDF/TIFF Document Text Detection from the Google Cloud Vision API. Using their example code I am able to submit a PDF and receive back a JSON object with the extracted text. My issue is that the JSON file that is saved to GCS only contains bounding boxes and text for "symbols", i.e. each character in each word. This makes the JSON object quite unwieldy and very difficult to use. I'd like to be able to get the text and bounding boxes for "LINES", "PARAGRAPHS" and "BLOCKS", but I can't seem to find a way to do it via the AsyncAnnotateFileRequest() method. The sample code is as follows: def async_detect_document(gcs_source_uri, gcs_destination_uri): """OCR with PDF/TIFF as source files on GCS""" # Supported mime_types are: 'application/pdf' and 'image/tiff' mime_type = 'application/pdf' # How many pages should be grouped into each json output file. batch_size = 2 client = vision.ImageAnnotatorClient() feature = vision.types.Feature( type=vision.enums.Feature.Type.DOCUMENT_TEXT_DETECTION) gcs_source = vision.types.GcsSource(uri=gcs_source_uri) input_config = vision.types.InputConfig( gcs_source=gcs_source, mime_type=mime_type) gcs_destination = vision.types.GcsDestination(uri=gcs_destination_uri) output_config = vision.types.OutputConfig( gcs_destination=gcs_destination, batch_size=batch_size) async_request = vision.types.AsyncAnnotateFileRequest( features=[feature], input_config=input_config, output_config=output_config) operation = client.async_batch_annotate_files( requests=[async_request]) print('Waiting for the operation to finish.') operation.result(timeout=180) # Once the request has completed and the output has been # written to GCS, we can list all the output files. storage_client = storage.Client() match = re.match(r'gs://([^/]+)/(.+)', gcs_destination_uri) bucket_name = match.group(1) prefix = match.group(2) bucket = storage_client.get_bucket(bucket_name=bucket_name) # List objects with the given prefix. blob_list = li…

http://stackoverflow.com/comment/90868653
score: 1
type: AnswerComment
has text: It will also add rows that would have been dropped but are not present in the original df.
comment on: http://stackoverflow.com/a/51959168
type: Comment

http://stackoverflow.com/a/52085000
score: 1
has comment: http://stackoverflow.com/comment/91120233
upvote count: 1
downvote count: 0
answers question: http://stackoverflow.com/q/52084899
has body: you can use random.choice to select from the alphabet and remove 1 letter each time: import random import string letters = string.ascii_uppercase values = dict.fromkeys(letters) for letter in values: choose = random.choice(letters) if choose in values.values(): continue # see note ** letters.remove(choose) values[letter] = choose for k, v in values.items(): values[v] = k ** this checks if the choice has already been assigned, if so, skip the key and continue. This will ensure A maps to B and B maps to A. At the end I add the skipped pairs back in but with the key/value swapped
has comment: http://stackoverflow.com/comment/91120204
type: Answer

http://stackoverflow.com/q/52005741
accepted answer: http://stackoverflow.com/a/52006081
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/90961505
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90961276
type: Question
answer count: 2
linked to: http://stackoverflow.com/q/48438569
upvote count: 12
downvote count: 0
has comment: http://stackoverflow.com/comment/90961359
has answer: http://stackoverflow.com/a/52013762
has title: How to have models.UUIDField field without dash
possible better answer: http://stackoverflow.com/a/52013762
has body: I tried to have models.UUIDField without dash, by using default=uuid.uuid4().hex (Instead of default=uuid.uuid4()) class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) api_key = models.UUIDField(default=uuid.uuid4().hex, editable=False, unique=True) subscription = models.IntegerField( choices=[(s.value, s.name) for s in Subscription], null=False, blank=False ) def __str__(self): return str(self.api_key) However, the resultant result still come with dash. django=# select * from users_profile; id | api_key | secret_key | subscription | user_id ----+--------------------------------------+------------+--------------+--------- 1 | 9da3546c-660c-46c6-adc4-6a13e6ee202b | | 0 | 1 2 | 9cbc3a68-7f50-4b18-9e61-7b009f22a0e8 | | 0 | 2 (2 rows) May I know how to have models.UUIDField field without dash?. I would like to store in database without dashes, and use it without dashes.
has answer: http://stackoverflow.com/a/52006081
favorite count: 0
score: 12

http://stackoverflow.com/q/52002357
has title: Connection to Oracle db (cx_Oracle) not working when scheduled from crontab but works as standalone
downvote count: 0
accepted answer: http://stackoverflow.com/a/52003977
tagged with: cron
type: AnsweredQuestion
tagged with: cx-oracle
tagged with: shell
score: 1
favorite count: 0
tagged with: python-3.x
type: Question
upvote count: 1
tagged with: python
answer count: 1
has body: I have a python (3.6) script that does some things with data retrieved from Oracle DB. Then I have a shell script for automation that execute the script. I than schedule the execution of such shell in crontab. If I execute the shell as standalone (sh shell.sh) it works perfectly fine, while when it runs as a crontab job connection to Oracle DB fails --> class 'cx_Oracle.DatabaseError' I'm trying to simplify the code I'm using, the Python script is as follow: #!/usr/bin/python3.6 # coding: utf-8 import pandas as pd import cx_Oracle try: conn = cx_Oracle.connect(username/pwd@hostname:port/db_name) query = """SELECT * FROM schema.table""" df = pd.read_sql(query, con = conn) except: print(sys.exc_info()[0]) raise sys.exit(1) The shell is doing something like this: #!/usr/bin/env bash if [something] then python3.6 pyscript.py fi The crontab -l result: * * * * * cd /root/workindirectory ; sudo sh shell.sh &gt;&gt; test.out Thank you all in advance for any help. EDIT: to specify that both shell and python scripts have 777 permissions
has answer: http://stackoverflow.com/a/52003977
linked to: http://stackoverflow.com/q/43794503

http://stackoverflow.com/a/52032578
has body: def numbers(n): #for m in range(n): # print(m) return range(n) def sets(n): r=[] for e in numbers(n): r.append([e]) return r print(sets(6)) Output: [[0], [1], [2], [3], [4], [5]] Pythonic way of solving your problem is as follows - One liner def create_list(n): return [[x] for x in range(n)] # Important one liner print(create_list(5))
type: Answer
answers question: http://stackoverflow.com/q/52032525
score: 1
upvote count: 1
downvote count: 0

http://stackoverflow.com/comment/91044676
type: Comment
type: QuestionComment
score: 2
has text: Lambda won't support in mounting a shared drive. If you can implement an API and expose it to the VPC where the Lambda can upload via the API, it should work. This will require to place the Lambda within the particular VPC.
comment on: http://stackoverflow.com/q/52046518

http://stackoverflow.com/comment/91098198
has text: It depends on what you want to do, obviously? Return an entirely different template or `Forbidden` response from the server, or just alter the view that you send.
type: QuestionComment
comment on: http://stackoverflow.com/q/52074040
score: 0
type: Comment

http://stackoverflow.com/a/51977808
has comment: http://stackoverflow.com/comment/90905841
score: 3
has body: I think you're asking how to create a sequence type—a type whose instances can be indexed with [], just like a list. The key to doing this is to implement one or more special methods, as described in Emulating container types in the docs. In particular, the special method that gets called for my_obj[1] is __getitem__. For a dead-simple example, let's create something that acts like a list of all of the lowercase English letters: class Letters: def __getitem__(self, index): return string.ascii_lowercase[index] And now: &gt;&gt;&gt; letters = Letters() &gt;&gt;&gt; letters[2] 'c' &gt;&gt;&gt; letters[-2] 'y' &gt;&gt;&gt; letters[3:6] 'def' However, this isn't really a complete sequence. For example: &gt;&gt;&gt; len(letters) TypeError: object of type 'Letters' has no len() &gt;&gt;&gt; reversed(letters) TypeError: object of type 'Letters' has no len() &gt;&gt;&gt; isinstance(letters, collections.abc.Sequence) False If you want to implement a complete sequence, the collections.abc module is useful, because all of the abstract base classes it provides are also mixin classes that fill in most of the implementation for you. For example, if we inherit Sequence, we can just define __getitem__ and __len__, and it'll give us implementations of __contains__, __iter__, __reversed__, index, and count for free: class Letters(collections.abc.Sequence): def __getitem__(self, index): return string.ascii_lowercase[index] def __len__(self): return 26 And now, everything that works on list, tuple, and range works on Letters: &gt;&gt;&gt; letters = Letters() &gt;&gt;&gt; len(letters) 26 &gt;&gt;&gt; reversed(letters) &lt;generator object Sequence.__reversed__ at 0x15f949f68&gt; &gt;&gt;&gt; print(*reversed(letters)) z y x w v u t s r q p o n m l k j i h g f e d c b a &gt;&gt;&gt; letters.index('s') 10 &gt;&gt;&gt; isinstance(letters, collections.abc.Sequence) True Also, I cheated a bit, creating a sequence that just delegates to a different sequence (ascii_lowercase) to do all the work.…
upvote count: 3
type: Answer
downvote count: 0
answers question: http://stackoverflow.com/q/51977733

http://stackoverflow.com/comment/91047136
has text: @T.Woody I agree with you, but isn't your way adding to big O?
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52048144

http://stackoverflow.com/comment/90867714
type: QuestionComment
has text: both one and two are already escaped. If you want to see it literally, then you must include both apostrophes eg. `"arst '{}' arst,\"you said\"".format(d). Since this has a mixture of both `'` and `"` then escape is necessary. If all the inside are `'` while the outside are `"` then there will be no need of escaping. Also if you all of them are the same, then it will converse one to the other so as it might be readable
score: 0
comment on: http://stackoverflow.com/q/51958604
type: Comment

http://stackoverflow.com/q/51976683
type: UnansweredQuestion
tagged with: pyqt5
upvote count: 1
downvote count: 1
tagged with: qtablewidget
has comment: http://stackoverflow.com/comment/90903963
has comment: http://stackoverflow.com/comment/90903596
has comment: http://stackoverflow.com/comment/90903772
has comment: http://stackoverflow.com/comment/90903718
type: Question
tagged with: pyqt
has comment: http://stackoverflow.com/comment/90903832
has title: QTableWidget: dragging and selecting outside the QTableWidgetItem area
favorite count: 0
score: 0
has body: I have a QTableWidget and I have scrolling enabled (click mouse and drag without releasing so the items can be selected). However, the dragging (and item selection) stops if I move my mouse outside the area where the QTableWidgetItems are. Is there an easy way to fix this? In the picture below I show where dragging stops I am using PyQt5 code: from PyQt5 import QtCore, QtGui, QtWidgets from PyQt5.QtGui import * from PyQt5.QtWidgets import * from PyQt5.QtCore import * import sys class Table(QTableWidget): def __init__(self, parent): super(Table, self).__init__(parent) self.setColumnCount(9) self.setRowCount(1) for r in range(1): for i in range(9): item = QTableWidgetItem(i) self.setItem(r, i, item) def main(): app = QApplication(sys.argv) window = QWidget() window.setGeometry(200,200,1200,400) tw = Table(window) twLayout = QVBoxLayout() twLayout.addWidget(tw) window.setLayout(twLayout) window.show() sys.exit(app.exec_()) if __name__ == '__main__': main()
tagged with: python
answer count: 0

http://stackoverflow.com/comment/98139090
score: 4
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/55399961
has text: I don't think `components` performs the `dt.components['days']*24` multiplication. It just returns the `hours` component from the `TimedeltaProperties` object.

http://stackoverflow.com/comment/90939644
type: Comment
score: 0
comment on: http://stackoverflow.com/a/51989713
has text: That's great thanks. I wasn't familiar with meshgrid.
type: AnswerComment

http://stackoverflow.com/q/52023058
upvote count: 2
has body: I wrote code to solve the following problem, however it fails on the last two test cases. My logic used to solve the problem seems sound, and even after having a coworker review it, we both cannot figure out why it would work for the first 8 test cases but not the last two (which were randomly generated). Problem: Given a string, return the position of the inputted string in a alphabetically sorted list of all the possible permutations of the characters in that string. For example, the permutations of ABAB are [AABB,ABAB,ABBA,BAAB,BABA,BBAA] where the position of ABAB in that list is 2. Logic I used to solve the problem: For larger inputs, it is impossible (inefficient) to generate a list of permutations, so the point is to find the position without generating the alphabetical list. This can be done by finding the frequency of the characters. For the above example, the first charcater in ABAB is A, so before = 0 and after = .5, and between = 6, so you decrease max by .5*6 which is 3, for a minn of 1 and maxx of 3, to leave only [AABB,ABAB,ABBA], the perms with A as the first character! Then the characters left are BAB. minn = 1 and maxx = 3, and between = 3. So for B, before would be .33 and after would be 0, so increase minn by 3*.33 for a minn of 2 and maxx of 3, which equals [ABAB,ABBA] the perms that have AB as the first two characters! Keep doing that for every character and it will find the input in the list. My Code: ## Imports import operator from collections import Counter from math import factorial from functools import reduce ## Main function, returns list position def listPosition(word): #turns string into list of numbers, A being 1, B being 2, and so on val = [ord(char) - 96 for char in word.lower()] #the result has to be between 1 and the number of permutations minn = 1 maxx = npermutations(word) #so we just increase the min and decrease the max based on the sum of freq #of the characters less than and greater than each character for indx in range(len(…
type: Question
has answer: http://stackoverflow.com/a/52023215
tagged with: algorithm
has comment: http://stackoverflow.com/comment/90996511
linked to: http://stackoverflow.com/q/588004
possible better answer: http://stackoverflow.com/a/52023215
has comment: http://stackoverflow.com/comment/90996642
has answer: http://stackoverflow.com/a/52023178
answer count: 2
downvote count: 0
has title: Python function for position of string in alphabetical list of permutations of it's characters
tagged with: permutation
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/90996523
has comment: http://stackoverflow.com/comment/90996457
tagged with: python
accepted answer: http://stackoverflow.com/a/52023178
score: 2
type: AnsweredQuestion

http://stackoverflow.com/comment/91015122
score: 1
has text: You could use the sines & cosines of 2 angles to calculate the tan of the difference between the 2 angles. However, tan(x)=tan(pi+x), so just using the tan you won't be able to tell the difference between 2 vectors that are close to each other and 2 vectors that point in almost opposite directions. But you can disambiguate that using the signs of your sines and cosines.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52031687

http://stackoverflow.com/comment/90928368
type: Comment
score: 1
type: QuestionComment
has text: Seems like `x` is a float, not an iterable (and so `in x`) fails. `x` is an element of `df['matrix']` so guessing one is of a different type.
comment on: http://stackoverflow.com/q/51989301

http://stackoverflow.com/q/51999623
score: 4
has title: Delete file with read-only permission, but write permission to parent folder
answer count: 1
linked to: http://stackoverflow.com/q/4829043
favorite count: 0
has comment: http://stackoverflow.com/comment/90948287
type: UnansweredQuestion
has body: My understanding is that, in order to delete a file, I need write permission to the parent folder (for Windows). I don't need write permission to the file itself. But os.remove gives me "[WinError 5] Access is denied". I can delete that file via the Windows explorer with my user. shutil.copy copies a file to a folder without problems, but running the script again gives a "[Errno 13] Permission denied", because the file is read-only and can not be overwritten. It makes no sense that I can create files but not delete those afterwards. Fix is to use shutil.copyfile, because then the destination file has no permissions and it can be overwritten in the next run, but then this won't work if the file already exists with the permissions. How do I delete a file with only read permissions but write permission to the parent folder? Python 3.3.2
tagged with: python
upvote count: 4
has comment: http://stackoverflow.com/comment/90949813
type: Question
has comment: http://stackoverflow.com/comment/90948227
has answer: http://stackoverflow.com/a/52046314
downvote count: 0

http://stackoverflow.com/comment/90975148
has text: MySQLdb is an abandoned project that just barely works with Python 3 and MySQL 5.5, so I'm not surprised that it has issues with this stuff. Is there a reason you're not using one of the supported, modern libraries (I think that's PyMySQL, mysqlclient, CMySQL, and MySQL Connector/Python)?
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/52011244

http://stackoverflow.com/q/51956657
possible better answer: http://stackoverflow.com/a/57395189
has title: Google Cloud SDK install failed UnicodeDecodeError: 'ascii' codec
has comment: http://stackoverflow.com/comment/90866075
linked to: http://stackoverflow.com/q/50486322
has comment: http://stackoverflow.com/comment/90899423
type: AnsweredQuestion
score: 3
linked to: http://stackoverflow.com/q/51620611
has comment: http://stackoverflow.com/comment/90912318
tagged with: windows-installer
has body: I got the following error when installing the Google Cloud SDK on my Windows 10 computer: ERROR: gcloud failed to load: 'ascii' codec can't decode byte 0xe1 in position 13: ordinal not in range(128) gcloud_main = _import_gcloud_main() import googlecloudsdk.gcloud_main from googlecloudsdk.calliope import cli from googlecloudsdk.calliope import backend from googlecloudsdk.calliope import parser_extensions from googlecloudsdk.core.updater import update_manager from googlecloudsdk.core.updater import installers from googlecloudsdk.core.credentials import store from googlecloudsdk.core.credentials import creds from googlecloudsdk.core.credentials import devshell as c_devshell from oauth2client import client from oauth2client import crypt from oauth2client import _openssl_crypt from OpenSSL import crypto from OpenSSL import crypto, SSL from cryptography import x509 from cryptography.x509.base import ( from cryptography.x509.extensions import Extension, ExtensionType from asn1crypto.keys import PublicKeyInfo from ._elliptic_curve import ( from ._int import inverse_mod from ._perf._big_num_ctypes import libcrypto libcrypto_path = find_library('crypto') fname = os.path.join(directory, name) result_path = result_path + p_path This usually indicates corruption in your gcloud installation or problems with your Python interpreter. Please verify that the following is the path to a working Python 2.7 executable: C:\AndroidSdk\CloudSdk\google-cloud-sdk\platform\bundledpython\python.exe If it is not, please set the CLOUDSDK_PYTHON environment variable to point to a working Python 2.7 executable. If you are still experiencing problems, please reinstall the Cloud SDK using the instructions here: https://cloud.google.com/sdk/ Traceback (most recent call last): File "C:\AndroidSdk\CloudSdk\google-cloud-sdk\\bin\bootstrapping\install.py", line 12, in <module> import bootstrapping File "C:\AndroidSdk\CloudSdk\google-cloud-sdk\bin\bootstrapping\bootstrapping.py", line 44, in <module> from …
has comment: http://stackoverflow.com/comment/90911365
has answer: http://stackoverflow.com/a/60894681
type: Question
tagged with: google-cloud-sdk
has answer: http://stackoverflow.com/a/57395189
tagged with: google-cloud-platform
downvote count: 0
linked to: http://stackoverflow.com/q/18649512
has answer: http://stackoverflow.com/a/59357262
favorite count: 0
has comment: http://stackoverflow.com/comment/90876917
tagged with: python-2.7
upvote count: 3
tagged with: python
answer count: 4
has answer: http://stackoverflow.com/a/51981124
accepted answer: http://stackoverflow.com/a/51981124

http://stackoverflow.com/comment/91073172
has text: Looks like your last attempt is getting better.
comment on: http://stackoverflow.com/a/52057110
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/a/52128182
upvote count: 1
has comment: http://stackoverflow.com/comment/91206941
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52111009
answers question: http://stackoverflow.com/q/52111009
type: AcceptedAnswer
score: 1
has body: In your code you can use only 'csv' as the format from pyspark import SparkContext, SparkConf ehsanLocationFiltered = '/FileStore/tables/stackoverflow.csv' df = sqlContext.read.format('csv')\ .options(header='true', inferschema='true')\ .load(ehsanLocationFiltered).rdd result=data.map(lambda row: row.Time &gt; '07:00' and row.Time &lt; '17:00') result.count()
type: Answer

http://stackoverflow.com/comment/90897884
has text: `df_test.append([{'a': 1, 'b': 1, 'c': 2}])`
comment on: http://stackoverflow.com/q/51973692
type: QuestionComment
type: Comment
score: 2

http://stackoverflow.com/q/52029320
favorite count: 0
tagged with: python
has body: My program is using a button from class First to trigger the function in class Second. However, when the button was press, it requires me to include a self argument, so how can I call the other function by using static method suggested form here (Python 3 Tkinter - How to call a function from another class) or using other alternative way to solve this. If you can suggest me on how to use that StringVar in class Second,it will be more easy for me, Regards. The only part of the code that I think should modify: self.traceButton=Button(self.main_inner_frame,text="Trace",command=Second.printSecondLine()) The Second class code: class Second(First): # @staticmethod def __init__(self,master): super().__init__(master) def printSecondLine(self): content = self.traceEntry.get() print(content) If you need a Full Code: from tkinter import * class First(Frame): def __init__(self,master): super().__init__() master.minsize(width=755, height=520) master.maxsize(width=755, height=520) Grid.config(self) # Run all function in [First Class] self.widget_size() #self.getTEXT() def widget_size(self): # Define a small frame for it self.main_inner_frame = LabelFrame(self,text="Tracing Method",height= 120,width =355) self.main_inner_frame.grid(row= 0, column=0) self.main_inner_frame.grid_propagate(0) # Create a button for it [When trace click it will show the text in the entry on terminal] self.traceButton = Button(self.main_inner_frame, text="Trace",command=Second.printSecondLine()) self.traceButton.grid(row = 0, column = 1, sticky = W) # Create a entry box for the user # use a string variable tvar tvar = StringVar() self.traceEntry = Entry(self.main_inner_frame,textvariable=tvar,width=30) self.traceEntry.grid(row = 0, column = 2, sticky = W) # def getTEXT(self): # content = self.traceEntry.get() # print(content) class Second(First): # @staticmethod def __init__(self,master): super().__init__(master) def printSecondLine(self): content = self.traceEntry.get() print(content) return content if …
has comment: http://stackoverflow.com/comment/91009612
type: AnsweredQuestion
tagged with: tkinter
has comment: http://stackoverflow.com/comment/91010088
type: Question
linked to: http://stackoverflow.com/q/44478645
has comment: http://stackoverflow.com/comment/91009937
has answer: http://stackoverflow.com/a/52029397
score: 1
has comment: http://stackoverflow.com/comment/91010029
tagged with: class
upvote count: 2
has comment: http://stackoverflow.com/comment/91010357
answer count: 2
possible better answer: http://stackoverflow.com/a/52029397
tagged with: function
downvote count: 1
has title: Tkinter - Using a Button command in a class to call a function from another class
has answer: http://stackoverflow.com/a/52030002
accepted answer: http://stackoverflow.com/a/52030002

http://stackoverflow.com/q/52006707
tagged with: datetime
tagged with: python
score: 0
has comment: http://stackoverflow.com/comment/90963945
answer count: 1
has answer: http://stackoverflow.com/a/52013012
has comment: http://stackoverflow.com/comment/90967485
has body: I've got datetime server that sends data as: today = datetime.datetime.today() data = bytearray(today.ctime(), encoding="utf8") data.extend('z' * (length-len(data))) In client aplication I want to print only received date and time, without "z" letters. My only idea is to search for first "z" letter and print to the moment when program finds it. Is there more "elegant" way to do it?
type: AnsweredQuestion
has title: How cut datetime trom received data in python
type: Question
accepted answer: http://stackoverflow.com/a/52013012
tagged with: sockets

http://stackoverflow.com/a/52082427
has comment: http://stackoverflow.com/comment/125347426
has comment: http://stackoverflow.com/comment/103981096
type: Answer
score: 3
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52081316
has body: Assuming you’re using the usual CPython interpreter, all is a builtin function object, which just has a pointer to a compiled function statically linked into the interpreter (or libpython). Showing you the x86_64 machine code at that address probably wouldn’t be very useful to the vast majority of people. Try running your code in PyPy instead of CPython. Many things that are builtins in CPython are plain old Python code in PyPy.1 Of course that isn’t always an option (e.g., PyPy doesn’t support 3.7 features yet, there are a few third-party extension modules that are still way too slow to use, it’s harder to build yourself if you’re on some uncommon platform…), so let’s go back to CPython. The actual C source for that function isn’t too hard to find online. It’s in bltinmodule.c. But, unlike the source code to the Python modules in your standard library, you probably don’t have these files around. Even if you do have them, the only way to connect the binary to the source is through debugging output emitted when you compiled CPython from that source, which you probably didn’t do. But if you’re thinking that sounds like a great idea—it is. Build CPython yourself (you may want a Py_DEBUG build), and then you can just run it in your C source debugger/IDE and it can handle all the clumsy bits. But if that sounds more scary than helpful, even though you can read basic C code and would like to find it… How did I know where to find that code on GitHub? Well, I know where the repo is; I know the basic organization of the source into Python, Objects, Modules, etc.; I know how module names usually map to C source file names; I know that builtins is special in a few ways… That’s all pretty simple stuff. Couldn’t you just program all that knowledge into a script, which you could then build a PyCharm plugin out of? You can do the first 50% or so in a quick evening hack, and such things litter the shores of GitHub. But actually doing it right requires handling a ton of special case…
answers question: http://stackoverflow.com/q/52081316
has comment: http://stackoverflow.com/comment/136577041
upvote count: 3
type: AcceptedAnswer

http://stackoverflow.com/q/52042400
type: Question
has body: I am training with exponential weight decay similar to the example from Tensorflow docs (https://www.tensorflow.org/api_docs/python/tf/train/exponential_decay) : global_step = tf.Variable(0, trainable=False) starter_learning_rate = 0.1 learning_rate = tf.train.exponential_decay(starter_learning_rate, global_step, 100000, 0.96, staircase=True) # Passing global_step to minimize() will increment it at each step. learning_step = ( tf.train.GradientDescentOptimizer(learning_rate) .minimize(...my loss..., global_step=global_step) ) How I can get a current learning rate during training (e.g to print it out)?
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/52042527
favorite count: 0
upvote count: 2
accepted answer: http://stackoverflow.com/a/52042527
tagged with: python
score: 2
type: AnsweredQuestion
has title: Getting current LR for tf.train.exponential_decay
tagged with: tensorflow

http://stackoverflow.com/comment/91117583
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52083260
has text: @Ares The users do not have to run the scripts on their own machines. Would I host the Flask API on some kind of internal server? I can't host over the web as sensitive data might be called/transferred. Additionally, is there a different stack website where this kind of discussion is more appropriate?
score: 0

http://stackoverflow.com/comment/91050199
score: 0
comment on: http://stackoverflow.com/q/52037050
type: Comment
type: QuestionComment
has text: Thank your response. Did i need to deploy custom action to production state or i can use it in alpha state ?

http://stackoverflow.com/a/75808761
score: 1
has body: The way to go from a SavedModel to a servable after running tensorflow graph transforms is to use the SavedModel Builder API. First, you need to create a SavedModel Builder object and then rebuild the graph you have just transformed, using the SavedModel Builder API. Next, you need to add the assets, signatures, and other meta-data back into the model. Finally, you need to call the SavedModel Builder API's save() method, which will save the model as a servable. This servable can then be used with tensorflow serving.
upvote count: 1
answers question: http://stackoverflow.com/q/51971050
type: Answer
downvote count: 0

http://stackoverflow.com/comment/90903975
type: Comment
comment on: http://stackoverflow.com/q/51976878
score: 0
has text: Sorry, typo, sleep(2)
type: QuestionComment

http://stackoverflow.com/comment/90887731
comment on: http://stackoverflow.com/q/51968584
type: Comment
type: QuestionComment
has text: No offense intended but that is terrible. I'd suggest a different import method or change how the data is stored. If you are absolutely stuck with that, I'm sorry. This comment may not be very helpful but I'm hoping that hearing this opinion might validate your own suspicions that this is a bad way to have your data be.
score: 0

http://stackoverflow.com/q/52070456
tagged with: ssh-tunnel
tagged with: python-3.x
type: Question
has body: Using Python, how might I validate that SSH connection is successful after the following: server = SSHTunnelForwarder( (host_or_ip, 22), ssh_username = "ssh_username", ssh_private_key = path_to_key, remote_bind_address = (another_host_or_ip, 5432) ) server.start()
answer count: 2
tagged with: ssh
tagged with: python
upvote count: 2
has answer: http://stackoverflow.com/a/52070675
has title: Python sshtunnel - How to Validate SSH Connection?
type: UnansweredQuestion
score: 2
has answer: http://stackoverflow.com/a/61777470
downvote count: 0
favorite count: 0

http://stackoverflow.com/comment/91008449
score: 4
type: Comment
type: QuestionComment
has text: Why not have 1 dictionary with 26 keys rather than 26 separate variables?
comment on: http://stackoverflow.com/q/52029044

http://stackoverflow.com/comment/91036616
comment on: http://stackoverflow.com/a/52042744
type: Comment
has text: I'll edit your post real quick to show what I mean. By all means, re-edit how you see fit.... Done.
score: 0
type: AnswerComment

http://stackoverflow.com/comment/90949667
has text: Yeah, I agree its easy process data from the database than from CSV file. But they provided me the CSV and to process it.
comment on: http://stackoverflow.com/q/52000223
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/91089980
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52021006
has text: Charlie, can you clarify what you mean? As per the current documentation, "Only cells (including values, styles, hyperlinks and comments) and certain worksheet attribues (including dimensions, format and properties) are copied. All other workbook / worksheet attributes are not copied - e.g. Images, Charts." My tests confirm this, unless I am doing something wrong
score: 0

http://stackoverflow.com/q/52042430
has comment: http://stackoverflow.com/comment/91035727
accepted answer: http://stackoverflow.com/a/52042559
tagged with: python
has comment: http://stackoverflow.com/comment/91036990
answer count: 4
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52042774
has comment: http://stackoverflow.com/comment/91035935
has comment: http://stackoverflow.com/comment/91035822
type: Question
has answer: http://stackoverflow.com/a/52042832
upvote count: 5
has answer: http://stackoverflow.com/a/52042559
possible better answer: http://stackoverflow.com/a/52042515
has body: I want to return True of two lists of dictionaries are memberwise equal (member being the content of each dictionary, disregarding order of lists), else return False. What is good way to do that in python? Eg, if a = [dict1, dict2] and b = [dict2, dict1], then a is equal to b. (dict1's and dict2's keys and values must match.) Here's my way: def _compare(self, a,b): if len(a) != len(b): return False for d in a: if d in b: continue else: return False return True
score: 5
has answer: http://stackoverflow.com/a/52042515
downvote count: 0
has comment: http://stackoverflow.com/comment/91038015
has title: Comparing 2 lists of dictionaries
favorite count: 0

http://stackoverflow.com/a/52048660
has body: I personally think this is one of the rare cases when applying a regular expression to the complete document without using an HTML parser is the easiest and a good way to go. And, since you are actually just looking for URLs and not matching any HTML tags in the regular expression, points made in this thread are not valid for this case: In [1]: data = """ ...: &lt;meta name="twitter:image" content="https://smtgvs.weathernews.jp/s/topics/img/201807/201807300285_sns_img_A.jpg?1532940869"&gt; ...: &lt;img style="width:100%" id="box_img1" alt="box1" src="https://smtgvs.weathernews.jp/s/topics/img/dummy.png" class="lazy" data-original="https: ...: //smtgvs.weathernews.jp/s/topics/img/201807/201807300285_box_img1_A.png?1503665797"&gt;` ...: &lt;img style="width:100%" id="box_img2" alt="box2" src="https://smtgvs.weathernews.jp/s/topics/img/201807/201807300285_box_img2_A.jpg?1503378518 ...: "&gt; ...: """ In [2]: import re In [3]: pattern = re.compile(r"https://smtgvs.weathernews.jp/s/topics/img/[0-9]+/.+\?[0-9]+") In [4]: pattern.findall(data) Out[4]: ['https://smtgvs.weathernews.jp/s/topics/img/201807/201807300285_sns_img_A.jpg?1532940869', 'https://smtgvs.weathernews.jp/s/topics/img/201807/201807300285_box_img1_A.png?1503665797', 'https://smtgvs.weathernews.jp/s/topics/img/201807/201807300285_box_img2_A.jpg?1503378518'] If you are though interested in how would you apply a regular expression pattern to multiple attributes in BeautifulSoup, it may be something along these lines (not pretty, I know): In [6]: results = soup.find_all(lambda tag: any(pattern.search(attr) for attr in tag.attrs.values())) In [7]: [next(attr for attr in tag.attrs.values() if pattern.search(attr)) for tag in results] Out[7]: [u'https://smtgvs.weathernews.jp/s/topics/img/201807/201807300285_sns_img_A.jpg?1532940869', u'https://smtgvs.weathernews.jp/s/topics/img/201807/201807300285_box_img1_A.png?1503665797', u'https://smtgvs.weathernews.jp/s/topics/img/201807/201807300285_box_img2_A.jpg?1503378518…
upvote count: 3
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/91048168
has comment: http://stackoverflow.com/comment/91052764
type: Answer
downvote count: 0
has comment: http://stackoverflow.com/comment/91049029
has comment: http://stackoverflow.com/comment/91052379
answers question: http://stackoverflow.com/q/52048617
score: 3
accepted answer of: http://stackoverflow.com/q/52048617
has comment: http://stackoverflow.com/comment/91050089

http://stackoverflow.com/comment/90960974
type: Comment
comment on: http://stackoverflow.com/q/51993507
has text: I basically mean I want to get the geometry objects from the file and know which OCG they are associated with. The goal for this script is to output multiple files each displaying a single layer.
score: 0
type: QuestionComment

http://stackoverflow.com/comment/91107229
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52067462
has text: Ok so that loads the web pages faster, however, it opens the tabs in any chrome window that I have open. Is there a way to specify a new window and then tabs in that window? I'll be sending search terms to the different handles once they open and I'm not sure how to specify the handle if it opens in an existing chrome window.

http://stackoverflow.com/q/51979903
answer count: 1
favorite count: 0
tagged with: python-3.x
has title: Heroku python app throwing error - KeyError: 'pip._vendor.urllib3.util.queue'
type: UnansweredQuestion
tagged with: pip
tagged with: python
tagged with: heroku
score: 1
upvote count: 1
type: Question
downvote count: 0
has answer: http://stackoverflow.com/a/57584247
has body: I am getting below error while deploying my application on Heroku. Previously it was working fine but now giving this error. Running same application on Linux Virtual environment with same python version is working fine. 2018-08-23T06:40:34.055457+00:00 app[web.1]: importlib.import_module(package) 2018-08-23T06:40:34.055459+00:00 app[web.1]: return _bootstrap._gcd_import(name[level:], package, level) 2018-08-23T06:40:34.055458+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/importlib/__init__.py", line 126, in import_module 2018-08-23T06:40:34.055460+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/spacy/__init__.py", line 5, in &lt;module&gt; 2018-08-23T06:40:34.055462+00:00 app[web.1]: from .deprecated import resolve_model_name 2018-08-23T06:40:34.055463+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/spacy/deprecated.py", line 8, in &lt;module&gt; 2018-08-23T06:40:34.055464+00:00 app[web.1]: from .cli import download 2018-08-23T06:40:34.055466+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/spacy/cli/__init__.py", line 1, in &lt;module&gt; 2018-08-23T06:40:34.055467+00:00 app[web.1]: from .download import download 2018-08-23T06:40:34.055468+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/spacy/cli/download.py", line 9, in &lt;module&gt; 2018-08-23T06:40:34.055469+00:00 app[web.1]: from .link import link_package 2018-08-23T06:40:34.055471+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/spacy/cli/link.py", line 4, in &lt;module&gt; 2018-08-23T06:40:34.055473+00:00 app[web.1]: import pip 2018-08-23T06:40:34.055474+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/pip/__init__.py", line 45, in &lt;module&gt; 2018-08-23T06:40:34.055475+00:00 app[web.1]: from pip.vcs import git, mercurial, subversion, bazaar # noqa 2018-08-23T06:40:34.055477+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/pip/vcs/…

http://stackoverflow.com/comment/90960390
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52005381
has text: Is the fact, that the `return` in your `fun` function in not indented intentional? Or did that happend while formatting your question for StackOverflow?
score: 0

http://stackoverflow.com/comment/91010287
score: 1
has text: @Denziloe People take "pure" distributions and rescale/translate them all the time for modeling purposes. If two distributions have identical histograms other than the labels on the axes, I think it's fair to say they're similar.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52029622

http://stackoverflow.com/a/52012422
type: Answer
has body: If the hours are consistent from day to day as it seems like they might be, you can just filter the index, which should be pretty fast: In [5]: prices.loc[prices.index.hour.isin(range(8,18))] Out[5]: price 2018-01-01 08:00:00 0.638051 2018-01-01 09:00:00 0.059258 2018-01-01 10:00:00 0.869144 2018-01-01 11:00:00 0.443970 2018-01-01 12:00:00 0.725146 2018-01-01 13:00:00 0.309600 2018-01-01 14:00:00 0.520718 2018-01-01 15:00:00 0.976284 2018-01-01 16:00:00 0.973313 2018-01-01 17:00:00 0.158488 2018-01-02 08:00:00 0.053680 2018-01-02 09:00:00 0.280477 2018-01-02 10:00:00 0.802826 2018-01-02 11:00:00 0.379837 2018-01-02 12:00:00 0.247583 .... EDIT: To your comment, working directly on the index and then doing a single lookup at the end will still probably be fastest even if it's not always consistent from day to day. Single day frames at the end will be easy with a groupby. For example: df = prices.loci for i in prices.index if (i.hour in range(8, 18) and i.day in range(1,10)) or (i.hour in range(2,4) and i.day in range(11,32)) framelist = [frame for _, frame in df.groupby(df.index.date)] will give you a list of dataframes with 1 day per list element, and will include 8:00-17:00 for the first 10 days each month and 2:00-3:00 for days 11-31.
has comment: http://stackoverflow.com/comment/90975772
has comment: http://stackoverflow.com/comment/90975743
score: 0
answers question: http://stackoverflow.com/q/52012279

http://stackoverflow.com/comment/90914193
comment on: http://stackoverflow.com/q/51981323
score: 0
has text: Have you tried using the request package to download the CSV, and then import to pandas data frame?
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/106107058
has text: @SukanyaPai The value of **`max`** expects in ***`int`*** type and in your case, it is **`str`**.
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52070665
score: 1

http://stackoverflow.com/q/52079567
downvote count: 0
has answer: http://stackoverflow.com/a/52079669
tagged with: pandas
tagged with: datetime
answer count: 1
score: 1
favorite count: 0
type: UnansweredQuestion
tagged with: python
upvote count: 1
has body: I have had a code snippet that has worked historically, which seems to have randomly broke this time around. The error is a type comparison error: df = df[df['loaded'] &gt; last_load] Traceback (most recent call last): File "&lt;ipython-input-13-62572f9caa45&gt;", line 1, in &lt;module&gt; df = df[df['loaded'] &gt; last_mart] File "C:\Users\user\AppData\Local\Continuum\anaconda3\lib\site-packages\pandas\core\ops.py", line 1201, in wrapper pd.DatetimeIndex) File "C:\Users\user\AppData\Local\Continuum\anaconda3\lib\site-packages\pandas\core\ops.py", line 1098, in dispatch_to_index_op result = op(left_idx, right) File "C:\Users\user\AppData\Local\Continuum\anaconda3\lib\site-packages\pandas\core\indexes\datetimes.py", line 133, in wrapper (type(other), str(other))) TypeError: &lt;class 'datetime.date'&gt; type object 2018-08-15 The code snippet is very straight forward: df['loaded'] = pd.to_datetime(df['loaded']) last_load = datetime.datetime.now().date() - datetime.timedelta(weeks = 2) df = df[df['loaded'] &gt;= last_load] When looking at the types, I have confirmed that last_load is datetime.date and that df['loaded'] is datetime64[ns]. Looking at the direct data in the dataframe, there has been no random change in formatting or odd new data points. The error seems to be referencing last_load, as that is the date specified by the definition of last_load. I'm not sure what the issue is. Any help?
has title: Pandas Datetime Comparison Failing
type: Question

http://stackoverflow.com/q/52036396
accepted answer: http://stackoverflow.com/a/52036873
score: 1
favorite count: 0
has title: python; reading file path error
tagged with: path
tagged with: python
type: AnsweredQuestion
has body: i have a directory structure; DIR1: ----outerPyFile.py ----DIR2: --------innerPyFile.py --------DIR3: ------------fileToRead.csv I'm reading fileToRead.csv in innerPyFile: pd.read_csv('DIR3/fileToRead.csv') works fine if i run innerPyFile.py individually Now when import innerPyFile module inside outerPyFile.py as import innerPyFile -- FileNotFoundError: DIR3\\fileToRead.csv. does not exist i tried replacing path with absolute path in innerPyFile as pd.read_csv(os.path.abspath('DIR3/fileToRead.csv')) still, when i run outerPyFile i get, FileNotFoundError C:\\\DIR1\\\DIR3\\\fileToRead.csv does not exist, here the code omitted DIR2 so i changed code as pd.read_csv(os.path.abspath('DIR2/DIR3/fileToRead.csv')) Now the code structure works file when i run outerPyFile.py which is acceptable. but here the problem will arise when i run innerPyFile individually because it will search for DIR2 which is not there in CWD of innerPyFile. anyone can suspect this behavior, please revert me what is going on? FYI, I've also tried pathLib module which didn't solve the issue.
upvote count: 1
has answer: http://stackoverflow.com/a/52036873
type: Question
tagged with: pathlib
tagged with: absolute-path
tagged with: os.path
answer count: 1
downvote count: 0

http://stackoverflow.com/comment/90936128
has text: @hpaulj: Well, I am reading about h5py and there it is quite easy to add attributes to datasets and groups, and it seems that pandas doesnt support this. Ordinary tables are easy to store, but I still haven't figured out what to do with the multidim dframes. I don't know how to add an attribute to a group given by pandas df stored with HDFStore.
type: Comment
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/51987891

http://stackoverflow.com/comment/91020068
type: AnswerComment
has text: This is in the right spirit, but you should always err on the side of using `isinstance` instead of doing an equality comparison on the `type`.
type: Comment
score: 1
comment on: http://stackoverflow.com/a/52035061

http://stackoverflow.com/q/52002244
type: UnansweredQuestion
downvote count: 0
score: 1
tagged with: data-structures
favorite count: 0
tagged with: python-3.x
type: Question
has title: Linked List Choke Python
has answer: http://stackoverflow.com/a/52002480
tagged with: python
tagged with: linked-list
upvote count: 1
answer count: 1
has body: I have an assignment on Linked List, and the name of the game is to add words from a string into an array implemented linked list, which is alphabetically ordered with pointers. However, when I run the following code, the Python Shell gets stuck and no results come back. Please help! Thank you! I think the error may be in here, but im not sure why no results come back :/ if self.NextFree != len(self.array): prev = curr = self.Start while self.array[curr].word &lt; nword: prev = curr curr = self.array[curr].pointer The full code is here: (Sorry if its long im a beginner! :)) class ListNode: def __init__(self,word,pointer,count = 1): self.word = word self.pointer = pointer self.count = count class LinkedList: def __init__(self): self.array = [] self.Start = -1 self.NextFree = self.Start + 1 def Initialise(self): MAX = 30 for i in range(MAX-1): self.array.append(ListNode('',i+1)) self.array.append(ListNode(' ', -1)) #last node has pointer of -1 def Display(self): print(self.Start, self.NextFree, len(self.array),sep = ' ') print("Index ", "Content ", "Count ", "Pointer") for i in range(len(self.array)): print('{0:&lt;7}{1:&lt;11}{2:&lt;8}{3:}'.format(i, self.array[i].word, self.array[i].count, self.array[i].pointer)) def IsEmpty(self): return self.Start == -1 def IsFull(self): return self.NextFree == len(self.array) def Update(self,nword): #nword = newword if self.IsEmpty(): self.Start = 0 self.array[0].word = nword self.NextFree += 1 else: if self.NextFree != len(self.array): prev = curr = self.Start while self.array[curr].word &lt; nword: prev = curr curr = self.array[curr].pointer if self.array[curr].word == nword: self.array[curr].count += 1 else: self.array[prev].pointer = self.NextFree self.array[self.NextFree].word = nword self.array[self.NextFree].pointer = curr self.NextFree += 1 else: print ("f") def DisplayT(self): for i in range(len(self.array)): print(self.array[i].word) l = LinkedList() l.Initialise() ##with open("Story.txt") as file: ## for words in file.…

http://stackoverflow.com/comment/90971817
has text: @Jean-FrançoisFabre So on windows you can put more than one backslash in between folder names?
comment on: http://stackoverflow.com/a/52010426
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/91088535
score: 0
comment on: http://stackoverflow.com/q/52067432
type: QuestionComment
type: Comment
has text: ss_prime is first version and cross_entropy is the second . Both are calculating same value

http://stackoverflow.com/q/52094901
type: Question
downvote count: 0
accepted answer: http://stackoverflow.com/a/52097429
tagged with: pandas
has title: Rolling correlation pandas
answer count: 1
score: 1
favorite count: 0
tagged with: correlation
has comment: http://stackoverflow.com/comment/106413035
upvote count: 1
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52097429
has body: I have a dataframe with time series. I'd like to compute the rolling correlation (periods=20) between columns. store_corr=[] #empty list to store the rolling correlation of each pairs names=[] #empty list to store the column name df=df.pct_change(periods=1).dropna(axis=0) #Prepate dataframe of time series for i in range(0,len(df.columns)): for j in range(i,len(df.columns)): corr = df[df.columns[i]].rolling(20).corr(df[df.columns[j]]) names.append('col '+str(i)+' -col '+str(j)) store_corr.append(corr) df_corr=pd.DataFrame(np.transpose(np.array(store_corr)),columns=names) This solution is working and gives me the rolling correlation.This solution is with the help of Austin Mackillop (comments). Is there another faster way? (I.e. I want to avoid this double for loop.)

http://stackoverflow.com/q/52040353
answer count: 2
downvote count: 0
favorite count: 0
tagged with: python
tagged with: language-agnostic
has body: I am currently processing a very large database of locations and trying to match them with their real world coordinates. To achieve this, I have downloaded the geoname dataset which contains a lot of entries. It gives possible names and lat/long coordinates. To try and speed up the process, I have managed to reduce the huge csv file (of 1.6 GB) to 0.450 GB by removing entries that do not make sense for my dataset. It still contains however 4 million entries. Now I have many entries such as: Slettmarkmountains seen from my camp site in Jotunheimen, Norway, last week Adventuring in Fairy Glen, Isle of Skye, Scotland, UK Morning in Emigrant Wilderness, California Knowing that string matching with such long strings, I used Standford's NER via NLTK to get a better string to qualify my location. Now I have strings like: Slettmarkmountains Jotunheimen Norway Fairy Glen Skye Scotland UK Emigrant Wilderness California Yosemite National Park Half Dome Yosemite National Park The geoname dataset contains things like: Jotunheimen Norway Lat Long Slettmarkmountains Jotunheimen Norway Lat Long Bryce Canyon Lat Long Half Dome Lat Long ... And I am applying this algorithm to get a good possible match between my entries and the geoname csv containing 4M entries. I first read the geoname_cleaned.csv file and put all of the data into a list. For each entry I have I then call for each one of my entries string_similarity() between the current entry and all the entries of the geoname_list def get_bigrams(string): """ Take a string and return a list of bigrams. """ s = string.lower() return [s[i:i+2] for i in list(range(len(s) - 1))] def string_similarity(str1, str2): """ Perform bigram comparison between two strings and return a percentage match in decimal form. """ pairs1 = get_bigrams(str1) pairs2 = get_bigrams(str2) union = len(pairs1) + len(pairs2) hit_count = 0 for x in pairs1: for y in pairs2: if x == y: hit_count += 1 break return (2.0 * hit_count) / union I have tested the algorit…
has title: Speeding up a "closest" string match algorithm
upvote count: 6
type: AnsweredQuestion
score: 6
has answer: http://stackoverflow.com/a/52041936
type: Question
has answer: http://stackoverflow.com/a/52043952
tagged with: string-matching
tagged with: performance
tagged with: algorithm
accepted answer: http://stackoverflow.com/a/52041936
possible better answer: http://stackoverflow.com/a/52043952

http://stackoverflow.com/comment/91058558
has text: @FHTMitchell, thanks a lot, it works in the terminal ... would have really liked to use the IDLE but I guess life is cruel.
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/52054062

http://stackoverflow.com/comment/90968610
has text: See the validation section of my link in question. This is returning the last position of the max.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52007394
type: Comment

http://stackoverflow.com/comment/91012959
has text: Have you *saved* `fileB.py`?
comment on: http://stackoverflow.com/q/52031203
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51979663
type: Question
tagged with: mongodb
has answer: http://stackoverflow.com/a/51979960
has body: Here's my query %%time from pymongo import MongoClient import datetime as dt mongo_client = MongoClient(...credential...) db_score = mongo_client['at-device-info'] cvsms = db_score['flat_sms'] test = cvsms.find({'customer_id': {'$in': list1}},{ 'customer_id': 1,'timestamp': 1}) df1 = pd.DataFrame(list(test)) What I did is copy last two lines and change list1 to list2, and df1 to df2. so it will become test = cvsms.find({'customer_id': {'$in': list2}},{ 'customer_id': 1,'timestamp': 1}) df2 = pd.DataFrame(list(test)) Then keep doing the same for list3 and df3. How to do this automatically for 48 list, the one query requires 4 minutes to run on my jupyter notebook
tagged with: dataframe
has title: How to do multiple mongoDB query by python list automatically
score: 0
tagged with: pandas
answer count: 1
accepted answer: http://stackoverflow.com/a/51979960
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/a/52062995
upvote count: 1
downvote count: 0
has body: You have an infinite loop for receiving data, but you close the serversocket after receiving the first batch. That's why the second call to accept fails
type: Answer
score: 1
answers question: http://stackoverflow.com/q/52062947

http://stackoverflow.com/q/52102105
has comment: http://stackoverflow.com/comment/91155008
tagged with: scatter-plot
answer count: 1
favorite count: 0
linked to: http://stackoverflow.com/q/12236566
has comment: http://stackoverflow.com/comment/91159102
upvote count: 2
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/91155118
duplicate of: http://stackoverflow.com/q/12236566
has title: Scatter plot with two colors
has comment: http://stackoverflow.com/comment/91156117
score: 1
has body: I need to color half of an array one color. Suppose I have 2 arrays that I concatenate arr1 = [[1,2, 3,4]] arr2 = [[1,2, 3,4]] arr 3 = np.concatenate((arr1, arr2), axis=0) plt.scatter(arr3[:,0], arr3[:,1], c= ???) This is an example, my real data set has 16,000 data points so a separate label array might not be possible. From index 0 - 8000~ I want to be red. 8000 - 16000 I want to be blue. Thanks
downvote count: 1
has comment: http://stackoverflow.com/comment/91155175
type: Question
has answer: http://stackoverflow.com/a/52102192
tagged with: matplotlib

http://stackoverflow.com/a/52052252
type: AcceptedAnswer
has body: You were almost there. The main problem you were facing is due to the order of the for loop. The order of for loop inside the list comprehension is based on the order in which they appear in traditional loop approach. Outer most loop comes first, and then the inner loops subsequently. a = {'b': [1,2,3], 'c':[4,5,6]} x = [] for k, v in a.items(): for i in v: x.append([k, i]) print(x) print([[k,i] for i in v for k, v in a.items()]) print([[k,i] for k, v in a.items() for i in v]) OUTPUT [['b', 1], ['b', 2], ['b', 3], ['c', 4], ['c', 5], ['c', 6]] [['b', 4], ['c', 4], ['b', 5], ['c', 5], ['b', 6], ['c', 6]] [['b', 1], ['b', 2], ['b', 3], ['c', 4], ['c', 5], ['c', 6]]
type: Answer
score: 3
accepted answer of: http://stackoverflow.com/q/52052003
downvote count: 0
answers question: http://stackoverflow.com/q/52052003
upvote count: 3

http://stackoverflow.com/q/52027787
favorite count: 0
tagged with: beautifulsoup
answer count: 1
has title: How to use beautiful soup to create user events?
tagged with: python-3.x
tagged with: python
has answer: http://stackoverflow.com/a/52027898
downvote count: 1
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91005800
score: -1
has body: can beautiful soup be used to create user events such as adding search string in the search box, clicking a button, selecting an option from the list, clicking an item etc?
type: Question
upvote count: 0
accepted answer: http://stackoverflow.com/a/52027898

http://stackoverflow.com/q/52045877
has comment: http://stackoverflow.com/comment/91043702
answer count: 1
tagged with: scikit-learn
has body: I'm using Anaconda. When I do conda list it shows me that currently scikit-learn 0.19.1 is installed. I would like to upgrade to 0.19.2, so I'm doing conda config --append channels conda-forge conda install scikit-learn=0.19.2 But then I'm getting the following error: PackagesNotFoundError: The following packages are not available from current cha nnels: - scikit-learn=0.19.2 Current channels: - https://repo.anaconda.com/pkgs/main/win-64 - https://repo.anaconda.com/pkgs/main/noarch - https://repo.anaconda.com/pkgs/free/win-64 - https://repo.anaconda.com/pkgs/free/noarch - https://repo.anaconda.com/pkgs/r/win-64 - https://repo.anaconda.com/pkgs/r/noarch - https://repo.anaconda.com/pkgs/pro/win-64 - https://repo.anaconda.com/pkgs/pro/noarch - https://repo.anaconda.com/pkgs/msys2/win-64 - https://repo.anaconda.com/pkgs/msys2/noarch - https://conda.anaconda.org/conda-forge/win-64 - https://conda.anaconda.org/conda-forge/noarch How can I install scikit-learn 0.19.2?
has comment: http://stackoverflow.com/comment/91044463
tagged with: python
has title: Update of scikit-learn fails with Anaconda
has answer: http://stackoverflow.com/a/52045934
type: AnsweredQuestion
tagged with: anaconda
has comment: http://stackoverflow.com/comment/91044318
type: Question
accepted answer: http://stackoverflow.com/a/52045934
score: 0

http://stackoverflow.com/a/52074561
downvote count: 0
answers question: http://stackoverflow.com/q/52074329
score: 1
has body: if you will receive a string in only this format then you can do the following: import numpy as np string_words=string.split(',') uniq_words=np.unique(string_words) string="" for word in uniq_words: string+=word+", " string=string[:-1] what this code does is that it splits words into a list, finds unique items, and then merges them into a string like before
upvote count: 1
type: Answer

http://stackoverflow.com/q/51995977
has comment: http://stackoverflow.com/comment/90941420
linked to: http://stackoverflow.com/q/63826471
tagged with: deep-learning
upvote count: 94
possible better answer: http://stackoverflow.com/a/54777347
tagged with: keras
has answer: http://stackoverflow.com/a/54777347
has body: I have a dataset containing grayscale images and I want to train a state-of-the-art CNN on them. I'd very much like to fine-tune a pre-trained model (like the ones here). The problem is that almost all models I can find the weights for have been trained on the ImageNet dataset, which contains RGB images. I can't use one of those models because their input layer expects a batch of shape (batch_size, height, width, 3) or (64, 224, 224, 3) in my case, but my images batches are (64, 224, 224). Is there any way that I can use one of those models? I've thought of dropping the input layer after I've loaded the weights and adding my own (like we do for the top layers). Is this approach correct?
favorite count: 0
has comment: http://stackoverflow.com/comment/90942416
has answer: http://stackoverflow.com/a/62976857
has comment: http://stackoverflow.com/comment/90941359
has title: How can I use a pre-trained neural network with grayscale images?
tagged with: python
has answer: http://stackoverflow.com/a/51996037
has comment: http://stackoverflow.com/comment/113699899
answer count: 15
has answer: http://stackoverflow.com/a/79322276
has answer: http://stackoverflow.com/a/52792646
type: AnsweredQuestion
score: 93
has answer: http://stackoverflow.com/a/72464383
tagged with: machine-learning
has answer: http://stackoverflow.com/a/60820788
has answer: http://stackoverflow.com/a/60783965
downvote count: 1
has answer: http://stackoverflow.com/a/60690678
tagged with: tensorflow
has answer: http://stackoverflow.com/a/73757056
type: Question
has comment: http://stackoverflow.com/comment/103012091
has answer: http://stackoverflow.com/a/72990952
has answer: http://stackoverflow.com/a/59959369
has comment: http://stackoverflow.com/comment/90941434
accepted answer: http://stackoverflow.com/a/51996037
has answer: http://stackoverflow.com/a/78191804
has answer: http://stackoverflow.com/a/62739217
has comment: http://stackoverflow.com/comment/90941358
has answer: http://stackoverflow.com/a/53294835

http://stackoverflow.com/q/52050934
tagged with: python
has comment: http://stackoverflow.com/comment/91052295
has comment: http://stackoverflow.com/comment/91052238
answer count: 0
score: 0
has title: Python: I need to parse a binary file in python with mixture of encoded data?
type: Question
has body: I have a file which contains encoded data in Latin - 1 coded and binary coded depending upon the position of the byte. I want to create a parser that can read that binary data, analyze it and filter the unwanted data. Issue: I am not able to view the binary file's actual format so that I can analyze the pattern and remove the unnecessary data. I am not able to handle this issue. I have tried using bytearray but it fails because it requires encoding.And reading byte by byte also results is false data. with open("FOA", "rb") as f: with open("FA", "w") as d: byte = f.read(1) while byte != "": # Do stuff with byte. print(byte) d.write(str(byte)) byte = f.read(1) I have not used bcoz i wanted to see the result.But i think its not giving correct output. Thanks in advance.
tagged with: python-3.x
tagged with: binary
type: UnansweredQuestion

http://stackoverflow.com/a/52060991
has comment: http://stackoverflow.com/comment/91072349
answers question: http://stackoverflow.com/q/52060931
has comment: http://stackoverflow.com/comment/91072248
score: 0
has comment: http://stackoverflow.com/comment/91074098
has body: A little more information about where the audio file would be helpful. Such as the URL or the location of the file. You might be able to use beautiful soup to scrape for the length if it's mentioned on a webpage, otherwise, you might be able to use some sort of an API call. https://github.com/quodlibet/mutagen would helpful to look at
type: Answer
has comment: http://stackoverflow.com/comment/91072292

http://stackoverflow.com/q/52028909
answer count: 2
has comment: http://stackoverflow.com/comment/91009327
type: UnansweredQuestion
type: Question
has body: I have two python files. I need to call the 2nd one from 1st. I'm aware of os.system() commands. But it's been mentioned as the worst way to execute a python script. The script I need to call doesn't contain any functions or classes. but just the flow. what is the better way to execute the script from another script.
has answer: http://stackoverflow.com/a/52028928
linked to: http://stackoverflow.com/q/2349991
tagged with: python
has title: How to execute a python file from another
duplicate of: http://stackoverflow.com/q/2349991
has answer: http://stackoverflow.com/a/52028932
score: 0

http://stackoverflow.com/a/52036743
score: 2
accepted answer of: http://stackoverflow.com/q/52036585
answers question: http://stackoverflow.com/q/52036585
has body: I believe need create boolean mask for specify which values has to be multiple: #or add parameter thousands=',' to read_csv like suggest @Inder b['b2'] = b['b2'].str.replace(",", "", regex=True).astype(np.int64) mask = b['b2'] &lt; 10000 b['b2'] = np.where(mask, b['b2'] * 10, b['b2']) print (b) a2 b2 0 x 13560 1 y 193309 2 z 38090 3 k 37212
type: AcceptedAnswer
downvote count: 0
upvote count: 2
type: Answer

http://stackoverflow.com/comment/90992116
has text: Did you install that module? If so, how did you do it?
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52020409

http://stackoverflow.com/comment/90914189
comment on: http://stackoverflow.com/a/51980746
score: 0
type: AnswerComment
has text: Add it to the question or create a new one pertaining to the exact error and link it in the comment.
type: Comment

http://stackoverflow.com/q/52047078
has body: I think after some update my Django app has started to segfault time after time. Below is my attempt to debug using gdb, however I cannot see the root cause: # gdb -ex=r --args ../pyenv/bin/python3 -X faulthandler manage.py runserver 127.0.0.1:8000 GNU gdb (GDB) 8.1.1 Copyright (C) 2018 Free Software Foundation, Inc. License GPLv3+: GNU GPL version 3 or later &lt;http://gnu.org/licenses/gpl.html&gt; This is free software: you are free to change and redistribute it. There is NO WARRANTY, to the extent permitted by law. Type "show copying" and "show warranty" for details. This GDB was configured as "x86_64-pc-linux-gnu". Type "show configuration" for configuration details. For bug reporting instructions, please see: &lt;http://www.gnu.org/software/gdb/bugs/&gt;. Find the GDB manual and other documentation resources online at: &lt;http://www.gnu.org/software/gdb/documentation/&gt;. For help, type "help". Type "apropos word" to search for commands related to "word"... Reading symbols from ../pyenv/bin/python3...(no debugging symbols found)...done. Starting program: /home/narunas/website/www/pyenv/bin/python3 -X faulthandler manage.py runserver 127.0.0.1:8000 [Thread debugging using libthread_db enabled] Using host libthread_db library "/usr/lib/libthread_db.so.1". Performing system checks... System check identified no issues (0 silenced). August 27, 2018 - 15:59:58 Django version 2.0, using settings 'website.settings.dev' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. Program received signal SIGSEGV, Segmentation fault. 0x00007ffff7de107b in kill () from /usr/lib/libc.so.6 (gdb) bt #0 0x00007ffff7de107b in kill () from /usr/lib/libc.so.6 #1 0x00007ffff7a450b7 in ?? () from /usr/lib/libpython3.7m.so.1.0 #2 0x00007ffff7984ff3 in _PyMethodDef_RawFastCallKeywords () from /usr/lib/libpython3.7m.so.1.0 #3 0x00007ffff7985201 in _PyCFunction_FastCallKeywords () from /usr/lib/libpython3.7m.so.1.0 #4 0x00007ffff79faf5d in _PyEval_EvalFrameDe…
has comment: http://stackoverflow.com/comment/91046579
tagged with: gdb
tagged with: segmentation-fault
has comment: http://stackoverflow.com/comment/96873350
has comment: http://stackoverflow.com/comment/91105834
has comment: http://stackoverflow.com/comment/91116279
tagged with: python-3.7
has comment: http://stackoverflow.com/comment/91111267
downvote count: 0
favorite count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91053331
has comment: http://stackoverflow.com/comment/91136182
tagged with: django
tagged with: python
has title: How to debug Django segmentation faults?
has comment: http://stackoverflow.com/comment/91073365
has comment: http://stackoverflow.com/comment/91121333
answer count: 0
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/91053644
type: Question

http://stackoverflow.com/comment/91077143
type: Comment
has text: You may have cut off a little bit too much from those entries. I can't see what triggered the `timezone` and `tz` errors, and can't see what the recursion error is doing. Can we see a bit more of those tracebacks? If you have the *starting lines* that would be helpful too.
comment on: http://stackoverflow.com/q/52063337
score: 0
type: QuestionComment

http://stackoverflow.com/comment/90886710
comment on: http://stackoverflow.com/q/51962723
type: QuestionComment
score: 2
has text: Possible duplicate of [Moving numpy arrays from VBA to Python and back](https://stackoverflow.com/questions/45105388/moving-numpy-arrays-from-vba-to-python-and-back)
type: Comment

http://stackoverflow.com/comment/91011813
has text: Thank you very much Neil, that was really fast ! I did not understand threading pool.map returned the objects. I'm gonna try this way. NB: as MyThreadFunction(OneOfMyObject) takes only 1 input object, It would return only 1 output object as well ?
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/52030641

http://stackoverflow.com/q/52051310
tagged with: jupyter-notebook
has title: SyntaxError: unexpected EOF while parsing _ input.split
has comment: http://stackoverflow.com/comment/91052878
duplicate of: http://stackoverflow.com/q/21122540
has answer: http://stackoverflow.com/a/52051379
upvote count: 1
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/91052811
score: 0
answer count: 1
favorite count: 0
linked to: http://stackoverflow.com/q/2589309
type: UnansweredQuestion
tagged with: python
has body: Today, I wrote this code. a, b = map(int, input("").split("")) print(a) However, When I enter the number a, b, I keep getting this error File "&lt;string&gt;", line 1 2 3 ^ SyntaxError: unexpected EOF while parsing I don't know why I keep getting the error. Please help

http://stackoverflow.com/a/52054366
upvote count: 3
has body: Your SEARCH_URL is not a string, it's a list of strings. So, you have to convert them individually. Something like search_urls = [url.format(search_term) for url in SEARCH_URLS]
downvote count: 0
has comment: http://stackoverflow.com/comment/91059874
has comment: http://stackoverflow.com/comment/91059521
type: Answer
answers question: http://stackoverflow.com/q/52054322
score: 3
has comment: http://stackoverflow.com/comment/91059670
has comment: http://stackoverflow.com/comment/91059987
has comment: http://stackoverflow.com/comment/91059290
has comment: http://stackoverflow.com/comment/91059206
has comment: http://stackoverflow.com/comment/91059066
has comment: http://stackoverflow.com/comment/91059160

http://stackoverflow.com/comment/91216468
type: AnswerComment
has text: Thanks @gregory for the info! I will do my best to make the necessary changes.
type: Comment
comment on: http://stackoverflow.com/a/52049491
score: 0

http://stackoverflow.com/a/52012883
score: 0
answers question: http://stackoverflow.com/q/52012520
type: Answer
has body: I believe in this case python multiprocessing module will capture the closure of the function by copying all the variables in that function. There are several ways around that but you need to pass in each row (or the index of the row) to each thread to avoid copying the whole array. In conjunction, you will need to establish a mechanism for storing/modifying the whole array after sorting each thread is complete. You can either use a file or you can refer to this question for a shared object in multiprocessing.

http://stackoverflow.com/a/52040426
score: 1
has comment: http://stackoverflow.com/comment/91031616
upvote count: 1
answers question: http://stackoverflow.com/q/52040029
downvote count: 0
has comment: http://stackoverflow.com/comment/91032932
has body: How about TensorBoardCallback? It will create interactive graphs that you can explore based on your model if you use Tensorflow as your backend. You just need add it as a callback to your fit function and make sure write_graph=True is set (which it is by default). If you want a shortcut you can directly invoke its methods instead of passing as a callback: tensorboard = TensorboardCallback() tensorboard.set_model(model) # your model here, will write graph etc tensorboard.on_train_end() # will close the writer Then just run tensorboard --logdir=./logs to start the server.
type: Answer

http://stackoverflow.com/comment/91167770
type: Comment
score: 0
has text: @Julien added, thanks for the help
comment on: http://stackoverflow.com/q/52108386
type: QuestionComment

http://stackoverflow.com/q/51960151
answer count: 2
favorite count: 0
type: UnansweredQuestion
tagged with: python
tagged with: regex
has answer: http://stackoverflow.com/a/51960210
downvote count: 2
has title: Regex breaking with preceding characters
upvote count: 1
type: Question
score: -1
has answer: http://stackoverflow.com/a/51960289
has body: I am trying to parse a phone number from a group of strings by compiling this regex: exp = re.compile(r'(\+\d|)(([^0-9\s]|)\d\d\d([^0-9\s]|)([^0-9\s]|)\d+([^0-9\s]|)\d+)') This successfully matches with a line like "+1(123)-456-7890". However, if I add anything in front of it, like "P: +1(123)-456-7890" it does not match. I tested on Regex websites but can't figure this out at all.

http://stackoverflow.com/comment/91012485
type: Comment
comment on: http://stackoverflow.com/a/52030910
score: 0
type: AnswerComment
has text: From the image, the boundary is at the maximum "Y" value - if this should always be true, then automatically finding the boundary is trivially simple. It appears to me as if the data to the left of this value is not a straight line.

http://stackoverflow.com/comment/90933534
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51986258
has text: Possible duplicate of [Python Script not Running and Not Giving an Error](https://stackoverflow.com/questions/51937046/python-script-not-running-and-not-giving-an-error)

http://stackoverflow.com/a/52050884
downvote count: 0
upvote count: 2
answers question: http://stackoverflow.com/q/52050634
has body: Take a look at following picture from Tensorflow official website that explains about Graph and Session concepts: According to documentation: Calling tf.constant() creates a single Operation that produces a value, adds it to the default graph. Calling tf.matmul(x, y) creates a single Operation that multiplies the values of tf.Tensor objects x and y, adds it to the default graph, and returns a tf.Tensor that represents the result of the multiplication Calling tf.train.Optimizer.minimize will add operations and tensors to the default graph that calculates gradients, and return a Operation that, when run, will apply those gradients to a set of variables. when running the “session.run()” the variables weights and the biases will be updated. Actually their value calculated not updated. For example, take a look at following example: a = tf.Variable(2) with tf.Session() as sess: sess.run(a.initializer) print(sess.run(a)) In this example no update will happen. Look at the above picture again, as you can see in the picture when we go forward we understand what parameters needs to updated so in the backward, the parameters updated according to loss by SGD optimizer.
type: Answer
score: 2

http://stackoverflow.com/comment/91133902
has text: @norok2 Good question. Added section at the end including timings.
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/52087221
type: Comment

http://stackoverflow.com/comment/90899912
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51974455
has text: The basic problem is that your lamba expression is *not* an expression: you have tried to include a `print` statement, then an `elif` without any attached `if` or `else`.

http://stackoverflow.com/comment/91173866
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/52111660
has text: Um... think there's also a good Q/A on `pd.set_option` regarding this as well...

http://stackoverflow.com/q/52028235
tagged with: object
has comment: http://stackoverflow.com/comment/91007076
has answer: http://stackoverflow.com/a/52028377
tagged with: class
answer count: 2
favorite count: 0
has comment: http://stackoverflow.com/comment/91007023
score: 0
has body: I'm practice classes and inheritance in a program idea that I came up with myself. Basically Im making an arcade game menu simulator that can play two modes, single player and multiplayer. Every time I enter a choice, either 1 or 2, the menu displays a couple times and then it proceeds to accept the input, I only want the menu to be displayed once. Heres my code: # Suppose you are at an arcade and you and your friend want to play a multiplayer game that requires UI. # Make the game ask for the users name and age to see if they can play, make the program so that it can add a friend. # If any of the players are under the age of 18, they are not allowed to play, otherwise proceed. # **EXTRA CREDIT** --&gt; Add a functionality which adds the players to a list until the list reaches 4 players, then stop adding to the list. # arcade_game.py import sys # give the user a greeting import self as self lst = [] class menu: def __init__(self, ready): self.ready = ready #display menu @classmethod def display_menu(self): print("Pick from one of the choices below, type in the corressponding number") print("1. single player \n" "2. Multiplayer") choice = int(input("Enter your choice here: ")) return choice # ready or not function to see if the user is ready to play def ready_or_not(self): # see if user types 1 or 2 with try &amp; except try: # ask user if they are ready self.ready = int(input("Are you ready to play? Type 1 for yes, 2 for no")) self.display_menu() except ValueError: print("You did not type 1 or 2, please try again!") # add players class class player(menu): # add a default player to __init__(), **(since there has to be at least one player)** def __init__(self, ready, player1): super().__init__(ready) self.player1 = player1 # single player method def set_name(self): self.player1 = input("Enter your name for single player mode") print("Lets play! ", self.player1) # multiplayer method def set_names(self): try: self.player1 = input("Enter your name to begin") lst.append(…
has answer: http://stackoverflow.com/a/52028436
accepted answer: http://stackoverflow.com/a/52028377
tagged with: python
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/52028436
upvote count: 1
downvote count: 1
has title: My display menu repeats multiple times when an input is entered
type: Question
has comment: http://stackoverflow.com/comment/91006864

http://stackoverflow.com/comment/91044576
has text: @Shawn thx u, it is also good idea=)
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52043323

http://stackoverflow.com/comment/91205298
type: Comment
has text: I updated my answer to rather use aspect ratio. You should also remember SO will rarely give plug-and-play answers. You will always need to fit it into your code yourself, and fix weird edge cases like `#7`.
type: AnswerComment
comment on: http://stackoverflow.com/a/52112758
score: 0

http://stackoverflow.com/comment/91235161
type: QuestionComment
has text: @snakecharmerb yes, the output is the same. I've accepted an answer that explains that the issue had nothing to do with anything not being encoding it UTF-8, but with how data was passed to the post request: it needs to be passed via a `files` parameter because the form is a multipart form. `requests` defaults to urlencoding (when using the `data` parameter), so that's why the data was mangled horribly,
comment on: http://stackoverflow.com/q/52109055
score: 0
type: Comment

http://stackoverflow.com/q/51987502
tagged with: django
tagged with: python
accepted answer: http://stackoverflow.com/a/51987542
type: AnsweredQuestion
downvote count: 1
type: Question
score: -1
has title: is not a valid regular expression in urls.py
has answer: http://stackoverflow.com/a/51987542
has comment: http://stackoverflow.com/comment/90924482
has body: I faced the problem, I need to add functions to the file urls.py urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^(?P[0-9]+)/$', views.detail, name='detail'), url(r'^(?P[0-9]+)/answer/$', views.answer, name='answer') ] Running the server I get "^(?P[0-9]+)/$" is not a valid regular expression: unknown extension ?P[ Tell me what's wrong...
upvote count: 0
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/90924526
tagged with: windows

http://stackoverflow.com/q/51996912
score: 5
has title: How to enforce only one running instance of a process in python Django framework?
downvote count: 0
answer count: 1
favorite count: 0
has body: I have a python Django manage command that should be called upon receiving an input file but this command is not safe for parallel calls. So an input file should be processed only and only when there is no other file being processed. One solution that I have is to use a lock file. Basically, create a lock file at the start of the process and delete it at the end. I'm worried that if the process crashes the lock file won't be deleted and consequently none of the other files would be processed until we manually remove that lock file. The solution doesn't need to be specific for Django or even python, but what is the best practice to enforce that only one instance of this process is being run?
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/90964275
has answer: http://stackoverflow.com/a/51999124
tagged with: python
tagged with: lockfile
has comment: http://stackoverflow.com/comment/90943520
type: AnsweredQuestion
tagged with: django
type: Question
accepted answer: http://stackoverflow.com/a/51999124
upvote count: 5
tagged with: concurrency

http://stackoverflow.com/comment/91127962
type: QuestionComment
has text: Does testImport really need to be an `ipynb` file? Could it not just be a normal `py` file? Importing a notebook into another notebook looks a bit [complicated](https://stackoverflow.com/questions/20186344/ipynb-import-another-ipynb-file).
type: Comment
comment on: http://stackoverflow.com/q/52088763
score: 0

http://stackoverflow.com/q/52070036
downvote count: 2
upvote count: 1
answer count: 1
has body: I've a 15 images which are stored locally. How do I transform these images to a array using tensorflow for a CNN type of Classification?
favorite count: 0
type: UnansweredQuestion
tagged with: python
tagged with: tensorflow
has answer: http://stackoverflow.com/a/52078190
type: Question
has title: Processing an Image using Tensorflow
score: -1
has comment: http://stackoverflow.com/comment/91095433

http://stackoverflow.com/a/52044429
has comment: http://stackoverflow.com/comment/111252422
has comment: http://stackoverflow.com/comment/91041265
has comment: http://stackoverflow.com/comment/91039738
answers question: http://stackoverflow.com/q/52044348
has body: Example: As a minimal example, take this: &gt;&gt;&gt; df GWA_BTC GWA_ETH GWA_LTC GWA_XLM GWA_XRP Date 2013-01-19 11,826.36 1,068.45 195.00 0.51 1.82 2013-01-20 13,062.68 1,158.71 207.58 0.52 1.75 2013-01-28 12,326.23 1,108.90 197.36 0.48 1.55 2013-01-29 11,397.52 1,038.21 184.92 0.47 1.43 And we can find the missing dates between 2013-01-19 and 2013-01-29 Method 1: See @Vaishali's answer Use .difference to find the difference between your datetime index and the set of all dates within your range: pd.date_range('2013-01-19', '2013-01-29').difference(df.index) Which returns: DatetimeIndex(['2013-01-21', '2013-01-22', '2013-01-23', '2013-01-24', '2013-01-25', '2013-01-26', '2013-01-27'], dtype='datetime64[ns]', freq=None) Method 2: You can re-index your dataframe using all dates within your desired daterange, and find where reindex has inserted NaNs. And to find missing dates between 2013-01-19 and 2013-01-29: &gt;&gt;&gt; df.reindex(pd.date_range('2013-01-19', '2013-01-29')).isnull().all(1) 2013-01-19 False 2013-01-20 False 2013-01-21 True 2013-01-22 True 2013-01-23 True 2013-01-24 True 2013-01-25 True 2013-01-26 True 2013-01-27 True 2013-01-28 False 2013-01-29 False Freq: D, dtype: bool Those values with True are the missing dates in your original dataframe
has comment: http://stackoverflow.com/comment/91041296
type: Answer
upvote count: 4
downvote count: 0
score: 4
has comment: http://stackoverflow.com/comment/91039776

http://stackoverflow.com/q/52081675
has body: I am able to connect to hive from Python using PyHive library. While fetching data from hive using PyHive I am facing issue Connection reset by peer. After connection established I am fetching data from hive using PyHive from Python. Connection is getting successful but while fetching data from hive it runs for fore than 5 mins and then throws connection reset by peer. from pyhive import hive conn = hive.Connection(host="host1", port="",auth="", database="",kerberos_service_name="") #successfully connection established cur = conn.cursor() cur.execute(query1) #(sometimes it works and some times it throws "Connection reset by peer" if query runs more than 5min)
tagged with: hive
type: Question
has title: Python Hive-PyHive Connection reset issue
tagged with: pyhive
answer count: 1
has comment: http://stackoverflow.com/comment/91114888
score: 0
tagged with: python
has comment: http://stackoverflow.com/comment/91114221
has answer: http://stackoverflow.com/a/54193390
type: UnansweredQuestion

http://stackoverflow.com/a/52050992
downvote count: 0
score: 1
has body: Initially weights and biases are initialised using random values. When you run session.run([...]), it'll evaluate optimizer,loss and train_prediction and all the variables these three may depend on. For example, optimizer depends on loss, loss on train_labels and logits, logits on weights and biases and so on... When it reaches the end(calculates all variables), it'll update the weights and biases as per gradient descent algorithm(To understand, how tensorflow does it, you'll need to understand Gradient Descent algorithm first. Check out this link). It's called "completing 1 epoch". In your case, you have used only 1 epoch so there will be only one pass. Accuracy won't be that good either. To further optimize it, use it like below: Let epochs=100 with tf.Session(graph=graph) as session:: tf.global_variables_initializer().run() for i in range(epochs): _, l, predictions = session.run([optimizer, loss, train_prediction]) This way, session.run(...) will run 100 times, updating the weights and biases in every iteration according to loss. Tensorflow will update all those varibles, which are initialised using tf.Variable().
answers question: http://stackoverflow.com/q/52050634
upvote count: 1
type: Answer

http://stackoverflow.com/a/62442148
score: 2
downvote count: 0
type: Answer
has body: I realized resizeAndAddLogo.py resizes the file to which the logo is pasted on, not the logo size proportioned to the file. We don't want that. So I changed the script to change logo size with the ratio of 1/5 to the image file. ... # Resize the logo. print(f'Resizing logo to fit {filename}...') sLogo = logoIm.resize((int(width / 5), int(height / 5))) sLogoWidth, sLogoHeight = sLogo.size # Add the logo. print(f'Adding logo to {filename}...') im.paste(sLogo, (width - sLogoWidth, height - sLogoHeight), sLogo) ... At this point, I don't need SQUARE_FIT_SIZE = 300, so I deleted it and made the code shorter. Here's my full script. import os from PIL import Image LOGO_FILENAME = 'catlogo.png' logoIm = Image.open(LOGO_FILENAME) os.makedirs('withLogo', exist_ok=True) # Loop over all files in the working directory. for filename in os.listdir(): if not (filename.endswith('.png') or filename.endswith('.jpg')) or filename == LOGO_FILENAME: continue im = Image.open(filename) width, height = im.size # Resize the logo. print(f'Resizing logo to fit {filename}...') sLogo = logoIm.resize((int(width / 5), int(height / 5))) sLogoWidth, sLogoHeight = sLogo.size # Add the logo. print(f'Adding logo to {filename}...') im.paste(sLogo, (width - sLogoWidth, height - sLogoHeight), sLogo) # Save changes. im.save(os.path.join('withLogo', filename)) Note that resized logo should be assigned to be used in loop. And this one of the resulted images.
upvote count: 2
answers question: http://stackoverflow.com/q/51995182

http://stackoverflow.com/a/52023853
answers question: http://stackoverflow.com/q/52023783
score: 0
type: Answer
has body: A string in Python that is equal to "" evaluates to False, while any string that is not blank will evaluate to True. #Evaluates to False print(bool("")) #Evaluates to True print(bool("A String")) In the loop you have specified, if there was a line that was successfully read, the string line will not be blank, and thus will evaluate to True. Once there is a line that didn't read in a string, the string line will be set to False and the loop should exit.

windows-server-2008-r2
tag name: windows-server-2008-r2
type: Tag
tags question: http://stackoverflow.com/q/52080462

http://stackoverflow.com/q/52090551
upvote count: 1
has title: parsing a jsonArray in python
tagged with: http://stackoverflow.com/tag/json
has body: I have this jsonArray in a file in python. I want to parse this and retrieve information such as orders, number, vendornumber and so on. How do I do that? How to parse a jsonArray in python? ( [count] =&gt; 1 [total] =&gt; 1 [orders] =&gt; Array ( [0] =&gt; Array ( [number] =&gt; 613 [vendorNumber] =&gt; 613 [created] =&gt; 2015-09-29 02:01:51 [paymentStatus] =&gt; ACCEPTED [fulfillmentStatus] =&gt; NEW [billingPerson] =&gt; Array ( [name] =&gt; Farhaan [companyName] =&gt; [street] =&gt; belapur Navi [city] =&gt; Mumbai [countryCode] =&gt; IN [postalCode] =&gt; [stateOrProvinceCode] =&gt; 15 [stateName] =&gt; 15 [countryName] =&gt; India [phone] =&gt; ) [paymentParameters] =&gt; Array ( ) [customerName] =&gt; xyz [customerEmail] =&gt; xyz@gmail.com [customerIP] =&gt; 182.70.60.203 [customerCountryCodeByIP] =&gt; IN [subtotalCost] =&gt; 0 [couponDiscountCost] =&gt; 0 [volumeDiscountCost] =&gt; 0 [discountCost] =&gt; 0 [shippingCost] =&gt; 0 [taxCost] =&gt; 0 [totalCost] =&gt; 0 [items] =&gt; Array ( [0] =&gt; Array ( [sku] =&gt; Dummy-HCm-8 [name] =&gt; Dummy HCm 8 [quantity] =&gt; 1 [price] =&gt; 0 [weight] =&gt; 0 [productId] =&gt; 0 [options] =&gt; Array ( [0] =&gt; Array ( [name] =&gt; Access option [type] =&gt; SELECT [value] =&gt; Self Paced Only ) ) [categoryId] =&gt; 0 [taxes] =&gt; Array ( ) ) ) [lastChangeDate] =&gt; 2018-08-25 23:24:00 [updated] =&gt; 2018-08-25 23:24:00 [sample] =&gt; ) ) ) I have written a small piece of code for the same but unfortunately that is not working. The code is as follows: import json input_file = open('data/data2') json_array = json.loads(input_file.read()) store_list = [] for item in json_array: store_details = {"number":None, "name":None} store_details['number'] = item['number'] store_details['name'] = item['name'] store_list.append(store_details) print(store_list)
type: Question
tagged with: arrays
downvote count: 0
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/91131020
has comment: http://stackoverflow.com/comment/91130878
tagged with: python
has comment: http://stackoverflow.com/comment/107768611
has comment: http://stackoverflow.com/comment/107768570
has comment: http://stackoverflow.com/comment/91131424
answer count: 0
type: UnansweredQuestion
score: 1

http://stackoverflow.com/comment/91153132
has text: Added console log
type: QuestionComment
comment on: http://stackoverflow.com/q/52099920
type: Comment
score: 0

http://stackoverflow.com/a/52098091
type: Answer
accepted answer of: http://stackoverflow.com/q/52063463
score: 2
upvote count: 2
has body: I think it is related to this error https://github.com/conda-forge/gdal-feedstock/issues/219 You should use virtual environments, (at least in order to quickly test different configurations) You can try one of the following fixes: 1) From the issue it seems like a problem with vs2015_runtime which has to be 14 for it to work. So check your version of vc2015 runtime, if it is too high you can downgrade it by. conda create --name gdal_vs15_14 python=3.6.5 (Here you can probably see what version of vs2015_runtime it installs into the environment) conda activate gdal_vs15_14 conda install -c conda-forge vs2015_runtime=14 conda install -c conda-forge gdal 2) Another simple fix for now, is by using python 2.7 (which is of course not optimal, but at least worked for me for now as a quick fix) conda create --name gdal_py27 python=2.7 conda activate gdal_py27 conda install -c conda-forge gdal
has comment: http://stackoverflow.com/comment/96191866
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/52063463

http://stackoverflow.com/q/52033281
accepted answer: http://stackoverflow.com/a/52033345
tagged with: python-requests
type: Question
has answer: http://stackoverflow.com/a/52033353
score: -1
possible better answer: http://stackoverflow.com/a/52033336
has answer: http://stackoverflow.com/a/52033336
has body: I have a list of web-pages that I'm looping through. My goal is to get text from each of these web-pages IF there is something. I'm looking for certain -tag elements that have same className. First part (looping) is working perfectly but for some reason i'm getting only value [None] while printing this -tags text. here is what i'm doing: jotain = [] col = 3 for row, urls in enumerate(links): page = requests.get(urls) soup = BeautifulSoup(page.content, 'html.parser') sposti = soup.find('a', {'class' : '_contactLink_1i8pl_1'}) jotain.append(sposti) print(jotain.text) sheet.write(row, col, sposti) It returns me: "AttributeError: 'list' object has no attribute 'text'" And this is how the html looks like: info@talligym.fi Thanks for help in advance!
downvote count: 2
upvote count: 1
favorite count: 0
tagged with: beautifulsoup
answer count: 3
tagged with: python
type: AnsweredQuestion
has title: Python get text from tag
has answer: http://stackoverflow.com/a/52033345

http://stackoverflow.com/comment/91035624
type: Comment
has text: Sorry, I do not. I'm one of the paid closed source providers, myself.
comment on: http://stackoverflow.com/a/52012277
score: 0
type: AnswerComment

http://stackoverflow.com/comment/91159602
has text: Another variation on `stack`: np.stack([aa,bb],1).transpose(2,0,1)`. This gets the (3,2) order right, and then transposes the 566 to the start.
type: Comment
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/52102423

http://stackoverflow.com/q/52104143
downvote count: 1
has answer: http://stackoverflow.com/a/52104203
score: 2
has comment: http://stackoverflow.com/comment/91159503
upvote count: 3
has comment: http://stackoverflow.com/comment/91164775
has title: How do I print values of list?
has answer: http://stackoverflow.com/a/52104331
type: Question
has body: I have a python question: Suppose you are given a vector, x, containing real values that are mostly zero. For instance: x = [0.0, 0.87, 0.0, 0.0, 0.0, 0.32, 0.46, 0.0, 0.0, 0.10, 0.0, 0.0] Complete the function, compress_vector(x), so that returns a dictionary d with two keys, d['inds'] and d['vals'], which are lists that indicate the position and value of all the non-zero entries of x. For the previous example, d['inds'] = [1, 5, 6, 9] d['vals'] = [0.87, 0.32, 0.46, 0.10] Note 1. Your implementation must not modify the input vector x. Note 2. If x contains only zero entries, d['inds'] and d['vals'] should be empty lists. I was able to print the indices, but I'm not sure how to print the values. def compress_vector(x): assert type(x) is list d = {'inds': [], 'vals': []} d = ([i for i, e in enumerate(x) if e != 0], ) return d
has answer: http://stackoverflow.com/a/52104231
has answer: http://stackoverflow.com/a/52104556
has answer: http://stackoverflow.com/a/52104924
answer count: 6
has comment: http://stackoverflow.com/comment/91164704
favorite count: 0
has comment: http://stackoverflow.com/comment/91159421
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/52104205
tagged with: python

random-data
tags question: http://stackoverflow.com/q/52012247
tag name: random-data
type: Tag

http://stackoverflow.com/comment/90988163
has text: No, that's what I want to avoid. I want it to run all tests in a project. Assume this is a huge project with 100s of modules, I don't want to pass them explicitly.
type: Comment
comment on: http://stackoverflow.com/a/52013660
type: AnswerComment
score: 1

http://stackoverflow.com/comment/106504542
has text: Related: https://stackoverflow.com/questions/7711246/why-weakref-doesnt-support-built-in-types-in-python/7712764
score: 0
type: Comment
comment on: http://stackoverflow.com/q/52011430
type: QuestionComment

http://stackoverflow.com/comment/90903765
has text: Hi Debanjan, I am able to open the following elemnent in n new tab using this code: self.home_banner = ui.WebDriverWait(self.browser,15).until(lambda browser: self.browser.find_element_by_link_text('TELL ME MORE')) self_banner=self.browser.execute_script("window.open('self.home_banner')") But I am not able to open in new tab using "self.homescreen_banner.send_keys(Keys.CONTROL + Keys.RETURN)". So can you please let me know why I am not able to open using Keys.CONTROL. ?
comment on: http://stackoverflow.com/a/51961211
type: AnswerComment
type: Comment
score: 0

http://stackoverflow.com/comment/90916970
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51980677
has text: Fantastic. It works smoothly. Thanks a lot for the help.
type: AnswerComment

http://stackoverflow.com/q/51962723
has comment: http://stackoverflow.com/comment/90886710
tagged with: vba
downvote count: 0
has comment: http://stackoverflow.com/comment/90876497
has comment: http://stackoverflow.com/comment/90879437
favorite count: 0
has comment: http://stackoverflow.com/comment/127835064
has comment: http://stackoverflow.com/comment/90877797
has comment: http://stackoverflow.com/comment/90878156
linked to: http://stackoverflow.com/q/51942083
tagged with: pywin32
tagged with: python
has comment: http://stackoverflow.com/comment/90879383
linked to: http://stackoverflow.com/q/45105388
has comment: http://stackoverflow.com/comment/90876083
answer count: 0
type: UnansweredQuestion
score: 1
upvote count: 1
tagged with: excel
has comment: http://stackoverflow.com/comment/90876172
has comment: http://stackoverflow.com/comment/90886624
type: Question
has comment: http://stackoverflow.com/comment/90875929
has title: How to debug Python Script called from an Excel VBA script?
has comment: http://stackoverflow.com/comment/90876032
has body: I call a python script from VBA to do a fit that excel cannot do and scipy has a convenient function for it. So I use this code to call the function and get and set data in VBA: Public Function GetData() GetData = Cache Cache = Empty End Function Public Sub SetData(data) Dim ok As Boolean Cache = data End Sub Sub LSQCBSplineIO(targetrng As Range) Dim oShell As Object Dim OutputArr() As Double Dim InputArr() As Double Dim ok As Boolean Call getinputarray(targetrng, InputArr) ' This works, tested it Set oShell = VBA.CreateObject("WScript.Shell") ' Make the data available via GetData()' Cache = InputArr Debug.Assert 0 = oShell.Run("&lt;FullpathtoScript&gt;.py", 0, True) ' Handle the returned data ' targetrng = Cache End Sub This does work according to the answer to this question. The python code I call is the following: import win32com.client import numpy as np import os import matplotlib.pyplot as plt import win32com.client from scipy.interpolate import LSQUnivariateSpline, UnivariateSpline print "Hello, User!" # get the running instance of Excel app = win32com.client.GetObject(Class="Excel.Application") # get some data from Excel data = app.Run("GetData") ssc=np.array(data) # do fitting ... &lt;insert fitting code here&gt; # return some data to excel app.run("SetData") The program is basically this: VBA calls Python Python calls VBA and gets data Python does stuff Python calls VBA and sets data Python is done and VBA takes over again If now Python has an error VBA will get stuck. VBA doesn't get an errormessage and hangs in there forever, causing excel to crash. So a bug in python means that I need to forcequit excel afterwards. The python script above is made to be called from VBA because only then the required data is at the right place for it to be gathered. The problem is now: That this cannot be debugged in python and not in VBA. In python the program doesn't work because it is not meant to work like that and in VBA I get no errormessage and the program gets stu…
has comment: http://stackoverflow.com/comment/90877254

http://stackoverflow.com/q/51988166
score: -1
has title: Convert list to vector in python
type: Question
has body: I'd like to convert a long list into a matrix or vector in order to convert it to degrees. I don't want to use a "for" loop because the list is too long and I want my program to be as fast as possible. How could I do this? EDIT: This is what I've tried so far, latR=np.asarray(lat) latR=np.degrees(latR) but this is what I get: ufunc 'degrees' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe'' Thanks!
has answer: http://stackoverflow.com/a/51988226
tagged with: numpy
answer count: 2
has comment: http://stackoverflow.com/comment/90932244
tagged with: vector
upvote count: 0
has comment: http://stackoverflow.com/comment/90925933
has answer: http://stackoverflow.com/a/51993586
has comment: http://stackoverflow.com/comment/90929973
tagged with: matrix
favorite count: 0
has comment: http://stackoverflow.com/comment/90926103
type: UnansweredQuestion
tagged with: python
downvote count: 1
tagged with: list

http://stackoverflow.com/a/52037811
answers question: http://stackoverflow.com/q/52037765
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52037765
score: 1
type: Answer
upvote count: 1
has body: Use ast.literal_eval to convert the string to a tuple. &gt;&gt;&gt; s = "('Who is Shaka Khan?',{'entities': [(7, 17, 'PERSON')]})," &gt;&gt;&gt; import ast &gt;&gt;&gt; t = ast.literal_eval(s) &gt;&gt;&gt; t[0] ('Who is Shaka Khan?', {'entities': [(7, 17, 'PERSON')]}) &gt;&gt;&gt; t[0][0] 'Who is Shaka Khan?' &gt;&gt;&gt; t[0][1] {'entities': [(7, 17, 'PERSON')]} Optionally, you can convert it to a dict for easy access &gt;&gt;&gt; d = dict(ast.literal_eval(s)) &gt;&gt;&gt; d['Who is Shaka Khan?'] {'entities': [(7, 17, 'PERSON')]}

http://stackoverflow.com/a/52059960
downvote count: 0
score: 1
has body: At the moment you are receiving HTML not XML with your request. You need to set the format of the response you want: https://www.goodreads.com/book/isbn/ISBN?format=FORMAT And you need to use params not payload: Constructing requests with URL Query String in Python P.S. For the request you are doing you can use JSON. https://www.goodreads.com/api/index#book.show_by_isbn
type: Answer
answers question: http://stackoverflow.com/q/52059566
upvote count: 1

http://stackoverflow.com/comment/91048168
has text: Maybe with a caveat that it will match content in comments etc also
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52048660

http://stackoverflow.com/comment/91158100
comment on: http://stackoverflow.com/a/52103505
type: Comment
has text: Wow, It is hard for a newbie like me to comprehend your answer but it is working like a charm. really genius and the answer within a minute. Thank you very much, really appreciate your help.
score: 0
type: AnswerComment

http://stackoverflow.com/comment/90934267
type: AnswerComment
comment on: http://stackoverflow.com/a/51992041
type: Comment
score: 0
has text: I keep getting an error message ['where'] is not in index.

http://stackoverflow.com/a/76407837
type: Answer
answers question: http://stackoverflow.com/q/52051996
score: 0
has body: I have just used # Scroll up pyautogui.hotkey('ctrl', 'up') # Scroll down pyautogui.hotkey('ctrl', 'down')

http://stackoverflow.com/a/51972487
has body: I don't know of anything OCR-specific, but you might be able to make this work with Biopython, because the basic problem of comparing one string to another using a matrix that scores each character's similarity to every other character is very common in bioinformatics. We call it a sequence alignment problem. Have a look at the pairwise2 module that Biopython provides; you would be able to compare each input word against each dictionary word with pairwise2.align.globaldx, using a dict that has all the pairwise character similarities. There are also functions in there for scoring deleted/inserted characters. Computing the pairwise character similarities would be something you'd have to do yourself, maybe by rendering each character in your chosen font and comparing the images, or maybe manually by just rating which characters look similar to you. You could also have a look at this other SO answer where characters are broken into classes based on the presence/absence of strokes. If you want something better than O(input * dictionary), you'd have to switch from brute force comparison to some kind of seed-match-based algorithm. If you assume that you'll always have a 2-character perfect match for example, you can index your dictionary by which words contain each length-2 string, and only compare the input words against the dictionary words that share a length-2 string with them.
type: Answer
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/51971206
downvote count: 0
has comment: http://stackoverflow.com/comment/90898006

http://stackoverflow.com/a/65515080
downvote count: 0
answers question: http://stackoverflow.com/q/52068102
type: Answer
score: 2
upvote count: 2
accepted answer of: http://stackoverflow.com/q/52068102
has body: For using service account credentials, the ServiceAccountCredentials library should be imported from oauth2client.service_account and used as below: # The needed import for service account credentials: from oauth2client.service_account import ServiceAccountCredentials from apiclient.discovery import build scope = ['https://www.googleapis.com/auth/drive'] # Parsing JSON credentials for a service account: credentials = ServiceAccountCredentials.from_json_keyfile_name('creds.json', scope) service = build('drive', 'v3', credentials=credentials) Then, use service as regular, e.g. service.files() etc.
type: AcceptedAnswer

http://stackoverflow.com/q/52078235
possible better answer: http://stackoverflow.com/a/52078485
tagged with: python
has answer: http://stackoverflow.com/a/52078448
type: AnsweredQuestion
score: 3
has body: What is the best way of storing items with several entries (fixed length) in a pandas DataFrame column? I’m thinking of something like a 3D position vector. For example, if my DataFrame is storing data about a bunch of physical objects, it could look like this: df = pandas.DataFrame({ 'type': [1, 2, 1, 1, 3], 'mass': [1.1, 2.2, 3.3, 4.4, 5.5], 'pos': [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12], [13, 14, 15]], 'vel': [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12], [13, 14, 15]] }) # mass pos type vel # 0 1.1 [1, 2, 3] 1 [1, 2, 3] # 1 2.2 [4, 5, 6] 2 [4, 5, 6] # 2 3.3 [7, 8, 9] 1 [7, 8, 9] # 3 4.4 [10, 11, 12] 1 [10, 11, 12] # 4 5.5 [13, 14, 15] 3 [13, 14, 15] Here, the columns 'pos' and 'vel' are the positions and velocities of the objects in 3D space. I have thought of several options, none of which seem ideal or even work: Storing Python lists as values in the column. This is basically what I showed in the example above. Unfortunately, this is very inefficient. Splitting the column into several different ones: df = pandas.DataFrame({ 'type': [1, 2, 1, 1, 3], 'mass': [1.1, 2.2, 3.3, 4.4, 5.5], 'x': [1, 4, 7, 10, 13], 'y': [2, 5, 8, 11, 14], 'z': [3, 6, 8, 12, 15], 'vx': [1, 4, 7, 10, 13], 'vy': [2, 5, 8, 11, 14], 'vz': [3, 6, 8, 12, 15] }) # mass type vx vy vz x y z # 0 1.1 1 1 2 3 1 2 3 # 1 2.2 2 4 5 6 4 5 6 # 2 3.3 1 7 8 8 7 8 8 # 3 4.4 1 10 11 12 10 11 12 # 4 5.5 3 13 14 15 13 14 15 This seems like it would become cumbersome for larger attributes. But at least it’s efficient? I’ve also tried assigning a multi-dimensional numpy array to the column, but unfortunately, pandas refuses: pos = numpy.array([[11, 12, 13], [22, 23, 24], [33, 34, 35], [44, 45, 46], [55, 56, 57]]) df.loc[:, 'pos'] = pos # --------------------------------------------------------------------------- # ValueError Traceback (most recent call last) # &lt;ipython-input-228-2ee95dd5aa19&gt; in &lt;module&gt;() # ----&gt; 1 df.loc[:, 'pos'] = pos # # /opt/anaconda-3/anaconda3/lib/python3.6/site-p…
upvote count: 3
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/91106505
accepted answer: http://stackoverflow.com/a/52078448
has title: Storing multi-dimensional attributes (columns) in pandas DataFrame
answer count: 2
tagged with: pandas
has comment: http://stackoverflow.com/comment/91106751
has answer: http://stackoverflow.com/a/52078485
downvote count: 0
favorite count: 0

http://stackoverflow.com/q/52084485
accepted answer: http://stackoverflow.com/a/52084846
possible better answer: http://stackoverflow.com/a/52084685
linked to: http://stackoverflow.com/q/46655712
score: 5
answer count: 3
tagged with: pandas
has answer: http://stackoverflow.com/a/52084685
downvote count: 0
favorite count: 0
tagged with: python-3.x
has body: What I'm trying to do is: options = ['abc', 'def'] df[any(df['a'].str.startswith(start) for start in options)] I want to apply a filter so I only have entries that have values in the column 'a' starting with one of the given options. the next code works, but I need it to work with several options of prefixes... start = 'abc' df[df['a'].str.startswith(start)] The error message is ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all(). Read Truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all() but haven't got understanding of how to do so.
tagged with: python
has answer: http://stackoverflow.com/a/52279626
linked to: http://stackoverflow.com/q/36921951
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52084846
has title: Filter dataframe by a list of possible prefixes for specific column
type: Question
upvote count: 5
has comment: http://stackoverflow.com/comment/91119471

http://stackoverflow.com/q/52107955
has title: Plotly (offline) for Python click events
answer count: 1
has body: I need to get click events in Plotly (offline) in Jupyter. The way I am thinking to handle this is use javascript and the following command to return the values to python: var kernel = IPython.notebook.kernel; kernel.execute(command); ...where command would be something like variable = xxxxx (just like here) I am stucked in the beggining of my attempt, trying to plot a chart in HTML in python (observe that I can succesfully load jQuery this way): from IPython.display import HTML HTML(''' Gráfico ''') The error message is: ReferenceError: Plotly is not defined at eval (eval at globalEval (jquery.min.js:2), :21:17) at eval () at Function.globalEval (jquery.min.js:2) at ua (jquery.min.js:3) at n.fn.init.append (jquery.min.js:3) at OutputArea._safe_append (outputarea.js:456) at OutputArea.append_execute_result (outputarea.js:493) at OutputArea.append_output (outputarea.js:326) at OutputArea.handle_output (outputarea.js:257) at output (codecell.js:382)
linked to: http://stackoverflow.com/q/50474244
type: UnansweredQuestion
tagged with: python
tagged with: jupyter-notebook
has answer: http://stackoverflow.com/a/52119409
type: Question
linked to: http://stackoverflow.com/q/43759543
score: 0

http://stackoverflow.com/comment/91079816
comment on: http://stackoverflow.com/q/52054605
score: 0
type: Comment
type: QuestionComment
has text: No, there is 4 view upvotes buttons, when you print the text of the first element of upvoter_list you get 'view upvotes', but for the remaining you get empty result

http://stackoverflow.com/q/52051760
has title: Adding Julia to PATH caused others to be knocked off the PATH || Mac OSX
has comment: http://stackoverflow.com/comment/91054124
score: 2
has comment: http://stackoverflow.com/comment/91054076
has answer: http://stackoverflow.com/a/52059589
has answer: http://stackoverflow.com/a/52056200
favorite count: 0
has comment: http://stackoverflow.com/comment/91054448
type: Question
tagged with: python
has comment: http://stackoverflow.com/comment/91054546
tagged with: macos
has answer: http://stackoverflow.com/a/52062007
has comment: http://stackoverflow.com/comment/91054661
has comment: http://stackoverflow.com/comment/91054194
upvote count: 3
tagged with: homebrew
has comment: http://stackoverflow.com/comment/91054734
answer count: 3
has comment: http://stackoverflow.com/comment/91054221
has body: I had a perfectly working copy of Anaconda (with Spyder at python 3.7). I installed Julia and added Julia to PATH, to be able to run it from terminal using the following command (from this source - https://en.wikibooks.org/wiki/Introducing_Julia/Getting_started): ln -fs "/Applications/Julia-1.0.app/Contents/Resources/julia/bin/julia" /usr/local/bin/julia This has had following effects: A) I can no longer use conda update conda However, Anaconda / Spyder are working fine - on their own. B) The default Python version on Mac has been set back to 2.7 - the one that comes with Mac C) typing python3 in the terminal results in, -bash: python3: command not found but Python 3 is installed. D) Running the following command at terminal, results in ls /usr/local/bin/python ls: /usr/local/bin/python: No such file or directory Further, running following command, sudo find / -iname python results in a very long list with "python" in the name (including folders). E) it has caused homebrew installation to break. Typing brew upgrade results in, -bash: brew: command not found Also, typing cd /usr/local/Library/Homebrew results in, -bash: cd: /usr/local/Library/Homebrew: No such file or directory F) Typing the sudo command e.g the below one: sudo nano ~/.bash_profile results in the following message: -bash: sudo: command not found I have searched for solutions but to no avail. It seems that, essentially, the terminal based stuff using PATH has been wrecked. How can I repair all of the above? Thanks in advance. ================= Edit / update - 1) Just rebooted the computer and on relaunching the terminal, I get the following message: -bash: export: `/users/&lt;user_name&gt;/anaconda/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/opt/X11/bin:/usr/local/git/bin:/Library/TeX/texbin': not a valid identifier 2) Now, even python command in the terminal is not being recognised. Typing python in the terminal, results in -bash: python: command not found
downvote count: 1
tagged with: julia
has comment: http://stackoverflow.com/comment/91056139
has comment: http://stackoverflow.com/comment/91054790
tagged with: anaconda
has comment: http://stackoverflow.com/comment/91053956
has comment: http://stackoverflow.com/comment/91054143
has comment: http://stackoverflow.com/comment/91055699
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91055070

http://stackoverflow.com/comment/90883060
comment on: http://stackoverflow.com/q/51963362
score: 0
type: QuestionComment
has text: This looks like an encoding issue. When I look at the file, it does not seem to actually contain a `\xd9' and unpickles without issues in Python 2 and 3. What is your environment, how did you put the file locally, what is its encoding?
type: Comment

http://stackoverflow.com/q/52027203
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91004572
accepted answer: http://stackoverflow.com/a/52027327
has body: I'm trying to convert integers from my list to binary and vice versa. but for some reason i'm only getting the last integer back and not the entire list. redChannelData = [46, 49, 50, 51, 53, 53, 54, 56, 59, 59, 60, 61, 62, 62, 64, 64, 65, 65] for value in redChannelData: encoded = [bin(value)[2:]] print(encoded) for binary in encoded: decoded = [int(binary ,2)] print(decoded) Output: ['101110'] ['110001'] ['110010'] ['110011'] ['110101'] ['110101'] ['110110'] ['111000'] ['111011'] ['111011'] ['111100'] ['111101'] ['111110'] ['111110'] ['1000000'] ['1000000'] ['1000001'] ['1000001'] [65]
possible better answer: http://stackoverflow.com/a/52027576
type: Question
has answer: http://stackoverflow.com/a/52027576
has comment: http://stackoverflow.com/comment/91004600
has comment: http://stackoverflow.com/comment/91005049
score: 0
answer count: 2
has title: Not getting the entire list back when converting from binary to decimal
has answer: http://stackoverflow.com/a/52027327
has comment: http://stackoverflow.com/comment/91004623
has comment: http://stackoverflow.com/comment/91005104
tagged with: python
linked to: http://stackoverflow.com/q/33390493
has comment: http://stackoverflow.com/comment/91004586

http://stackoverflow.com/q/52096451
tagged with: python
has title: Prediction Model to predict when the future events will happen next month
upvote count: 0
has body: I have to develop a Prediction Model using Python to predict if a site will crash next month or not depending on the occurances in the last 6 monthes. Input Parameters are: Environment(Dev,Prod,Test), Region(NA,APAC,EMEA) and the Date of the month. I am using matplotlib, pandas and numpy. It will be a 2D Data Frame or a 3D Panel in Pandas. I am not sure as input parameters are 3 - Region, Env and Date. I think below Machine Learning Algorithm should be used: from sklearn.linear_model import LinearRegression Please correct me if I am wrong.
has comment: http://stackoverflow.com/comment/91143104
downvote count: 1
type: Question
tagged with: numpy
score: -1
tagged with: pandas
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/52096568
tagged with: prediction
type: UnansweredQuestion

http://stackoverflow.com/comment/90991586
comment on: http://stackoverflow.com/q/52020597
has text: One question per question, please. StackOverflow is Q&A, not 3Q&3A.
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91160734
score: 1
comment on: http://stackoverflow.com/q/52104673
type: QuestionComment
has text: have you tried adding some prints in your code to see where it goes and what really happends?
type: Comment

http://stackoverflow.com/comment/90891937
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51970640
has text: Of course it throws the same error. Try the other regex.

http://stackoverflow.com/comment/90967312
has text: @alexdma: then I don't know - if you say that `openssl version` shows `DES-CBC3-SHA` as available you should also be able to set and use it as `DEFAULT_CIPHERS` as long as the same openssl library is used in both cases.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51993543
type: Comment

http://stackoverflow.com/q/51991933
has title: Bio7 import modules
has answer: http://stackoverflow.com/a/52009144
has comment: http://stackoverflow.com/comment/90933498
type: Question
answer count: 3
tagged with: bio7
tagged with: dataflow
has answer: http://stackoverflow.com/a/52001099
has answer: http://stackoverflow.com/a/51992514
score: 0
type: UnansweredQuestion
has body: I try to using Bio7 dataflow. It's is possible get data frame from R and using in Python scripts. I try to use the following code import pandas as df print("here we are") df=RServeUtil.fromR("iris") print(df) but I have some error in import statment.
tagged with: python

http://stackoverflow.com/a/51997389
has comment: http://stackoverflow.com/comment/90971540
has comment: http://stackoverflow.com/comment/90944295
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/51997171
upvote count: 5
has comment: http://stackoverflow.com/comment/90944428
type: Answer
has comment: http://stackoverflow.com/comment/90943980
has comment: http://stackoverflow.com/comment/90943975
has comment: http://stackoverflow.com/comment/90944372
has comment: http://stackoverflow.com/comment/90969306
has comment: http://stackoverflow.com/comment/90944336
has comment: http://stackoverflow.com/comment/106763679
score: 5
has comment: http://stackoverflow.com/comment/90944340
has body: Numba v1 You might have to install numba with pip install numba Then use numbas jit compiler via the njit function decorator from numba import njit @njit def distances(point, points): return ((points - point) ** 2).sum(1) ** .5 @njit def find_my_circle(point, circles): points = circles[:, :2] radii = circles[:, 2] dist = distances(point, points) mask = dist &lt; radii i = mask.argmax() return i if mask[i] else -1 @njit def find_my_circles(points, circles): n = len(points) out = np.zeros(n, np.int64) for i in range(n): out[i] = find_my_circle(points[i], circles) return out ids = np.append(df_1.ID.values, np.nan) i = find_my_circles(points, df_1'x', 'y', 'R'.values) df_2['host_circle'] = ids[i] df_2 ID x y host_circle 0 3 1 2 1.0 1 4 3 5 NaN 2 5 9 9 2.0 This iterates row by row... meaning one point at a time it tries to find the host circle. Now, that part is still vectorized. And the loop should be very fast. The massive benefit is that you don't occupy tons of memory. Numba v2 This one is more loopy but short circuits when it finds a host from numba import njit @njit def distance(a, b): return ((a - b) ** 2).sum() ** .5 @njit def find_my_circles(points, circles): n = len(points) m = len(circles) out = -np.ones(n, np.int64) centers = circles[:, :2] radii = circles[:, 2] for i in range(n): for j in range(m): if distance(points[i], centers[j]) &lt; radii[j]: out[i] = j break return out ids = np.append(df_1.ID.values, np.nan) i = find_my_circles(points, df_1'x', 'y', 'R'.values) df_2['host_circle'] = ids[i] df_2 Vectorized But still problematic c = ['x', 'y'] centers = df_1[c].values points = df_2[c].values radii = df_1['R'].values i, j = np.where(((points[:, None] - centers) ** 2).sum(2) ** .5 &lt; radii) df_2.loc[df_2.index[i], 'host_circle'] = df_1['ID'].iloc[j].values df_2 ID x y host_circle 0 3 1 2 1.0 1 4 3 5 NaN 2 5 9 9 2.0 Explanation Distance from any point from the center of a circle is ((x1 - x0) ** 2 + (y1 - y0) ** 2) ** .5 I can use broadcasting if …
accepted answer of: http://stackoverflow.com/q/51997171

http://stackoverflow.com/q/52046864
accepted answer: http://stackoverflow.com/a/52075170
has answer: http://stackoverflow.com/a/52048467
has body: I am programming on web app where I am trying to display in List View user's name but I always get just id. Here is the code of List View: activities = Activity.objects \ .annotate(day=ExtractDay('created'), month=ExtractMonth('created'), year=ExtractYear('created'))\ .values('user', 'day', 'month', 'year') \ .annotate(total=Count('user')) \ .order_by('user') \ Getting user: for activities_data in activities: user = activities_data['user'] Code of model: class Activity(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, verbose_name=_('user'), on_delete=models.CASCADE) I really try everything but I don't know how to deal with that. Could you help me how to get full user name?
tagged with: listview
answer count: 3
downvote count: 0
has title: Get user name not just ID in View List
favorite count: 0
has answer: http://stackoverflow.com/a/52046972
tagged with: django
has answer: http://stackoverflow.com/a/52075170
tagged with: python
possible better answer: http://stackoverflow.com/a/52046972
type: AnsweredQuestion
tagged with: list
score: 1
upvote count: 1
type: Question

http://stackoverflow.com/comment/91055780
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52050946
has text: I do not use the whole raccoon repo,I am making my own model for a different detection, I just want to use a file to convert my xml files to csv ones. The path that I set is the path to the images in my directory, everything is correct. Also I have both the test and train folders in my directory but still thank you for the response :)

postgresql
tags question: http://stackoverflow.com/q/52022551
tags question: http://stackoverflow.com/q/51964024
tags question: http://stackoverflow.com/q/52070240
tags question: http://stackoverflow.com/q/52101757
tags question: http://stackoverflow.com/q/52017465
tags question: http://stackoverflow.com/q/52015380
tags question: http://stackoverflow.com/q/52036566
tags question: http://stackoverflow.com/q/52098561
tags question: http://stackoverflow.com/q/52067058
tags question: http://stackoverflow.com/q/51958257
tags question: http://stackoverflow.com/q/52093022
tags question: http://stackoverflow.com/q/52111363
tags question: http://stackoverflow.com/q/52023587
tags question: http://stackoverflow.com/q/51982285
tags question: http://stackoverflow.com/q/52050191
tags question: http://stackoverflow.com/q/51988051
tags question: http://stackoverflow.com/q/52025871
tags question: http://stackoverflow.com/q/52012623
tags question: http://stackoverflow.com/q/52094791
tags question: http://stackoverflow.com/q/52070326
tags question: http://stackoverflow.com/q/52073307
tag name: postgresql
tags question: http://stackoverflow.com/q/51983257
tags question: http://stackoverflow.com/q/52056772
tags question: http://stackoverflow.com/q/52041430
tags question: http://stackoverflow.com/q/52048778
tags question: http://stackoverflow.com/q/51992864
tags question: http://stackoverflow.com/q/52087698
type: Tag
tags question: http://stackoverflow.com/q/52081498
tags question: http://stackoverflow.com/q/52050605
tags question: http://stackoverflow.com/q/52012308
tags question: http://stackoverflow.com/q/52061554
tags question: http://stackoverflow.com/q/52037356
tags question: http://stackoverflow.com/q/52098712
tags question: http://stackoverflow.com/q/52019939

http://stackoverflow.com/q/52003882
type: Question
score: 0
answer count: 1
favorite count: 0
has title: Create object which has keys with function type value
has comment: http://stackoverflow.com/comment/90957383
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/52003979
has comment: http://stackoverflow.com/comment/90957112
upvote count: 1
tagged with: python
downvote count: 1
duplicate of: http://stackoverflow.com/q/48398461
has body: I am working in one Python program where I want to create one object like we do in JavaScript. var obj = {"sum":function(a,b){return a+b;}}` Can I do a similar thing in Python?
has comment: http://stackoverflow.com/comment/90957421
linked to: http://stackoverflow.com/q/48398461
has comment: http://stackoverflow.com/comment/90957065

http://stackoverflow.com/a/52068280
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/52067933
has body: You have a problem with string-formatting. You seemingly didn't test the steps your algorithm is composed of in isolation, so you didn't know where to watch for the error. These are possible solutions for your problem: song_amount = 18 songs_in_folder = "nameless- Milk Crown On Sonnetica" '[%d] %s' % (song_amount, songs_in_folder) # '[18] nameless- Milk Crown On Sonnetica' '[{}] {}'.format(song_amount, songs_in_folder) # '[18] nameless- Milk Crown On Sonnetica' # or for Python 3.6+ f'[{song_amount}] {songs_in_folder}' # '[18] nameless- Milk Crown On Sonnetica' The main takeaway should be, that you test every step possible before you compose a lenghty function out of it.
type: Answer
downvote count: 0
score: 1
accepted answer of: http://stackoverflow.com/q/52067933
upvote count: 1

http://stackoverflow.com/comment/91100106
type: QuestionComment
score: 3
has text: Try `args.file_liste`
comment on: http://stackoverflow.com/q/52075236
type: Comment

http://stackoverflow.com/a/52102409
type: Answer
has comment: http://stackoverflow.com/comment/91155752
answers question: http://stackoverflow.com/q/52102254
has comment: http://stackoverflow.com/comment/91156284
has comment: http://stackoverflow.com/comment/91156520
has comment: http://stackoverflow.com/comment/91157306
has comment: http://stackoverflow.com/comment/91157266
has comment: http://stackoverflow.com/comment/91156568
has body: There are a few errors in your code, the main one being that your optional argument should be a boolean flag. Here is how you could implement it. def prange(start, stop, step=1, reverse=False): fst = list(range(start, stop, step)) if reverse: return (fst, list(reversed(fst))) else: return (fst,) print(*prange(3, 6, reverse=True)) Output [3, 4, 5] [5, 4, 3]
accepted answer of: http://stackoverflow.com/q/52102254
has comment: http://stackoverflow.com/comment/91156026
score: 0
has comment: http://stackoverflow.com/comment/91155829
has comment: http://stackoverflow.com/comment/91157037
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/91156869
has comment: http://stackoverflow.com/comment/91156621

http://stackoverflow.com/comment/90889833
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51966356
has text: The catetgory/urls.py is as follows: `urlpatterns = [ url(r'^(?P<slug>[\w-]+)/$', SubcategoryListView.as_view()), path('kids/<slug:slug>/', ProductListView.as_view()), ]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)`

http://stackoverflow.com/comment/91125626
has text: Also, are you expecting to find timestamps in the future? Because otherwise, testing that the creation time is before *now* is a little pointless; aside from narrow race conditions (files created between `to_date = datetime.datetime.now()` and the `glob.glob` call), nothing should be created after *now*, and in the rare cases it occurs (immediately after a clock sync that moves the clock backwards or the like), you probably still want to treat them as "created in the last 24 hours".
score: 0
comment on: http://stackoverflow.com/q/52087620
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/90896815
type: Comment
has text: @Goose_ I missed the `fire_rate` definition. The `last_shot` is indeed defined in the the `if` statement, but it's evaluated in the condition, then defined in the block. So unless it's defined somewhere else first, you won't get to the part where it's defined, because you'll first have to evaluate `time.Time() - last_shot > player.fire_rate` before you get to where `last_shot` is defined.
comment on: http://stackoverflow.com/a/51971459
score: 0
type: AnswerComment

http://stackoverflow.com/comment/91041265
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52044429
type: Comment
has text: Method 1 does not work? It returns all the dates between start and end rather than displaying missing dates?

http://stackoverflow.com/comment/91163727
comment on: http://stackoverflow.com/q/52031708
score: 0
has text: Oh whoops, I missed that. Did you install Tensorflow using the instructions here? https://medium.com/tensorflow/tensorflow-1-9-officially-supports-the-raspberry-pi-b91669b0aa0 or https://www.tensorflow.org/install/install_raspbian
type: Comment
type: QuestionComment

http://stackoverflow.com/a/51995022
upvote count: 3
has comment: http://stackoverflow.com/comment/90988766
has body: Let's try this: df = pd.DataFrame({'Country':['France']*4+['China']*4,'Progress':['Develop','Middle','Operate','Start']*2,'NumTrans':np.random.randint(100,900,8),'TransValue':np.random.randint(10000,9999999,8)}) df = df.set_index(['Country','Progress']).T print(df) Source Dataframe: Country France China Progress Develop Middle Operate Start Develop Middle Operate Start NumTrans 603 661 251 110 747 780 390 346 TransValue 8662422 5226407 4679673 2589011 695373 5655969 2079905 7878596 Set as category and define order: df.columns = df.columns.set_levels([df.columns.levels[0], df.columns.levels[1].astype('category').reorder_categories(['Start','Develop','Middle','Operate'])]) #Sort the dataframe using category dtype df = df.sort_index(axis=1) print(df) Output: Country China France Progress Start Develop Middle Operate Start Develop Middle Operate NumTrans 346 747 780 390 110 603 661 251 TransValue 7878596 695373 5655969 2079905 2589011 8662422 5226407 4679673 Update Testing Missing a progress step for country. df = pd.DataFrame({'Country':['France']*4+['China']*4,'Progress':['Develop','Middle','Operate','Start']*2,'NumTrans':np.random.randint(100,900,8),'TransValue':np.random.randint(10000,9999999,8)}) df = df.set_index(['Country','Progress']).T df2 = df.drop(('China','Operate'), axis=1) df2 Input Dataframe Country France China Progress Develop Middle Operate Start Develop Middle Start NumTrans 672 496 319 394 346 402 462 TransValue 6341768 5832091 9580341 5739947 6399118 6826113 1501382 Astype and sort: df2.columns = df2.columns.set_levels([df.columns.levels[0], df2.columns.levels[1].astype('category').reorder_categories(['Start','Develop','Middle','Operate'])]) #Sort the dataframe using category dtype df2 = df2.sort_index(axis=1) print(df2) Output: Country China France Progress Start Develop Middle Start Develop Middle Operate NumTrans 359 496 191 886 685 814 581 TransValue 1369593 8810118 5527613 8970396 1424341 8017561 7749721
type: Answer
has comment: http://stackoverflow.com/comment/90960673
score: 3
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51994771
has comment: http://stackoverflow.com/comment/90973112
has comment: http://stackoverflow.com/comment/90972901
has comment: http://stackoverflow.com/comment/90960255
answers question: http://stackoverflow.com/q/51994771
type: AcceptedAnswer

http://stackoverflow.com/a/52020058
answers question: http://stackoverflow.com/q/52018545
upvote count: 2
type: AcceptedAnswer
has body: Basically, the response object will return one or many Reservation objects. response=ec2.describe_instances() You don't really have to worry about Reservations, other than for the purpose of iterating them. To delve into more detail, you could have a look at this past question, https://serverfault.com/questions/749118/aws-ec2-what-is-a-reservation-id-exactly-and-what-does-it-represent So your first block of code is an appropriate way of listing the instance ID's of all EC2 instances. The second block of code is iterating through the keys in the response object, which is a dictionary, response=ec2.describe_instances() for x in response: print(x) Here's the Boto documentation for the EC2 service, where you can find more info on the response object, https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/ec2.html#EC2.Client.describe_instances
type: Answer
score: 2
accepted answer of: http://stackoverflow.com/q/52018545
downvote count: 0

http://stackoverflow.com/comment/90963956
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52006681
has text: Besides, `Test.a.name` and `Test.a.value` *also* work, so it appears `_name_` and `_value_` are just synonyms for `name` and `value`, respectively.
score: 0

http://stackoverflow.com/comment/90927653
score: 1
comment on: http://stackoverflow.com/q/51988947
has text: `header = ['Activity, Charge per hour']; table.append(header)` -- this is the issue. I'm guessing you mean `header = ['Activity', 'Charge per hour']`.
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/90973435
has text: @JChao Did you try to time your solution with a really long string?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52011112
score: 0

http://stackoverflow.com/a/53872957
has body: Answering my own question. The following method should be much faster than the one in my question, but slower than @coldspeed's method. It can be a good alternative when data types of the levels of the index are not the same. df.set_index(['g1', 'g2']).reindex(pd.MultiIndex.from_tuples(itertools.product(df.g1, df.g2))) A rough speed comparison: coldspeed: 100% this: 135% the one in the question: 270%
answers question: http://stackoverflow.com/q/52104737
score: 0
type: Answer

http://stackoverflow.com/q/51994256
has comment: http://stackoverflow.com/comment/90946997
tagged with: pyspark
downvote count: 5
has title: What are the best practices around accessing RDD's in Spark SQL API?
tagged with: apache-spark
answer count: 1
favorite count: 0
type: UnansweredQuestion
tagged with: python
upvote count: 0
score: -5
has body: When using pyspark's SQL API, I sometimes see people recommend accessing the underlying RDD to perform a transformation. What is Spark's intentional usage around this? They say the RDD API will be removed in Spark 3.0, so should all code being written today avoid using the underlying RDD's, as a matter of both form and future comparability?
type: Question
tagged with: apache-spark-sql
has answer: http://stackoverflow.com/a/51994521

http://stackoverflow.com/comment/91112229
type: AnswerComment
comment on: http://stackoverflow.com/a/52080794
has text: also how to give column name to this?
score: 0
type: Comment

http://stackoverflow.com/comment/90947175
has text: But then it creates are error "unindent does not match any outer idendatation level"
comment on: http://stackoverflow.com/a/51984129
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/91129927
type: QuestionComment
has text: I am adding some data to the question . please see it @Joe
score: 0
comment on: http://stackoverflow.com/q/52089716
type: Comment

http://stackoverflow.com/a/52022524
accepted answer of: http://stackoverflow.com/q/52022499
has body: This will return the longest list in the list values: max(values, key=len)
downvote count: 0
score: 37
type: AcceptedAnswer
upvote count: 37
answers question: http://stackoverflow.com/q/52022499
type: Answer

http://stackoverflow.com/q/52059072
tagged with: python-3.5
answer count: 1
tagged with: python
has answer: http://stackoverflow.com/a/52059156
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/52059156
type: Question
has body: I m trying to create a class in python 3.5 here is the class file import numpy as np import cv2 from threading import Thread class perstrans: def __init__(self,a,img,s): self.name=a self.imx = img.shape[1] self.imy = img.shape[0] self.src = np.float32( [[28, 198], [252, 198], [203, 140], [79, 141]], [[28, 198], [252, 198], [203, 140], [79, 141]]) self.dst = np.float32( [[0, imy], [imx, imy], [imx, 0], [0, 0]]) self.pmat = cv2.getPerspectiveTransform(self.src[s[1]], self.dst) return None def transfer(self,image): Thread(target=self.perstr, args=(image)).start() def perstr(self,imaga): self.h, self.w = imaga.shape[:2] self.res = cv2.warpPerspective(imaga, m, (w,h), flags=cv2.INTER_LINEAR) return self def getres(self): return self.res But when i initialize it like here i get the following error import cv2 import numpy as np import perstrans cap = WebcamVideoStream(0).start() img = cap.read() img = cv2.resize(img,(resizex,resizey)) h, w = img.shape[:2] trns=perstrans.perstrans("angle",img,0) .... Traceback (most recent call last): File "main.py", line 39, in &lt;module&gt; trns=perstrans.perstrans("angle",img,0) File "/home/huzeyfe/Desktop/robotaksi data/line tracking/duzenlenmis/v2/perstrans.py", line 12, in __init__ [[28, 198], [252, 198], [203, 140], [79, 141]]) TypeError: function takes at most 1 argument (2 given) Thanks Note: This question might be duplicate but most of the questions i saw there was the self missing in function decleration and i couldnt find anything like mine
has title: python3 class argument error
tagged with: class
has comment: http://stackoverflow.com/comment/91068403
score: 0

http://stackoverflow.com/a/51970178
has comment: http://stackoverflow.com/comment/90916394
has body: With RegEx a = re.findall('\)?[^()]*\(?', s) excluded = a[::2] included = a[1::2] print(included, excluded, sep='\n') ['hahaha', 'hehehe', ''] ['apple banana lemmon (', ') dog cat whale (', ') red blue black'] Take care of empty strings a = re.findall('\)?[^()]*\(?', s) excluded = [*filter(bool, a[::2])] included = [*filter(bool, a[1::2])] print(included, excluded, sep='\n') ['hahaha', 'hehehe'] ['apple banana lemmon (', ') dog cat whale (', ') red blue black'] No RegEx from itertools import cycle def f(s): c = cycle('()') a = {'(': 1, ')': 0} while s: d = next(c) i = s.find(d) if i &gt; -1: j = a[d] yield d, s[:i + j] s = s[i + j:] else: yield d, s break included = [] excluded = [] for k, v in f(s): if k == '(': excluded.append(v) else: included.append(v) print(included, excluded, sep='\n') ['hahaha', 'hehehe'] ['apple banana lemmon (', ') dog cat whale (', ') red blue black'] Same idea without overwriting s from itertools import cycle def f(s): c = cycle('()') a = {'(': 1, ')': 0} j = 0 while True: d = next(c) i = s.find(d, j) if i &gt; -1: k = a[d] yield d, s[j:i + k] j = i + k else: yield d, s[j:] break included = [] excluded = [] for k, v in f(s): if k == '(': excluded.append(v) else: included.append(v) print(included, excluded, sep='\n') ['hahaha', 'hehehe'] ['apple banana lemmon (', ') dog cat whale (', ') red blue black']
downvote count: 0
has comment: http://stackoverflow.com/comment/90916587
type: Answer
score: 3
upvote count: 3
answers question: http://stackoverflow.com/q/51969716

http://stackoverflow.com/a/52094812
type: Answer
upvote count: 1
answers question: http://stackoverflow.com/q/52094672
score: 1
has body: The problem is that status is not guaranteed to have a value. If you pass x=0, your loop doesn't run, and then you return status. What would its value be? If eg, you change your loop to range(2, 10) its runs fine (it doesn't make sense in your case, just trying to show the problem). However, since you just append the returned value to a list, don't use a global. Just return the value.
downvote count: 0

http://stackoverflow.com/comment/91102291
score: 3
has text: Possible duplicate of [Finding the index of an item given a list containing it in Python](https://stackoverflow.com/questions/176918/finding-the-index-of-an-item-given-a-list-containing-it-in-python)
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52076336

http://stackoverflow.com/comment/90889405
type: Comment
has text: On that note what would be the drawbacks if using a local variable in a restart like this? I honestly do not know. Is it a memory issue?
score: 0
comment on: http://stackoverflow.com/a/51969402
type: AnswerComment

http://stackoverflow.com/q/52046815
tagged with: python
linked to: http://stackoverflow.com/q/40620585
has answer: http://stackoverflow.com/a/60434538
type: AnsweredQuestion
upvote count: 3
accepted answer: http://stackoverflow.com/a/60434538
has answer: http://stackoverflow.com/a/75097796
type: Question
has body: Suppose I have an expression of the form . I know that I can simplify the expression like so: . However, sympy.simplify and sympy.factor both return the original expression. To work around this, I've been operating on the expression at a low level: factor_map = defaultdict(set) additive_terms = expr.as_coeff_add()[-1] for term1, term2 in combinations(additive_terms, 2): common_terms = ( set(term1.as_coeff_mul()[-1]) &amp; set(term2.as_coeff_mul()[-1]) ) if common_terms: common_factor = sympy.Mul(*common_terms) factor_map[common_factor] |= {term1, term2} factor_map now looks like so: { a: {a⋅x, -a⋅y}, b: {b⋅x, -b⋅y}, c: {-c⋅x, c⋅y}, x: {a⋅x, b⋅x, -c⋅x}, y: {-a⋅y, -b⋅y, c⋅y} } I sort it by the number of operations represented by the terms: factor_list = sorted( factor_map.items(), key = lambda i: (i[0].count_ops() + 1) * len(i[1]) )[::-1] I then just rebuild the expression: used = set() new_expr = 0 for item in factor_list: factor = item[0] appearances = item[-1] terms = 0 for instance in appearances: if instance not in used: terms += instance.as_coefficient(factor) used.add(instance) new_expr += factor * terms for term in set(additive_terms) - used: new_expr += term This gives new_expr = d + x*(a + b - c) + y*(-a - b + c). Not great, but better. I can also improve on this by dividing each combination of additive terms by each other, checking if the result is a number, and using that information to further reduce the output to new_expr = d + (x - y)*(a + b - c). I've also tried to apply sympy.factor to every possible combination of additive terms, but obviously that blows up very quickly for any reasonably big expression. Edit: Here's an implementation that uses sympy.factor on all partitions of the set of additive terms (partitions function borrowed from this answer): def partition(collection): if len(collection) == 1: yield [ collection ] return first = collection[0] for smaller in partition(collection[1:]): # insert `first` in each of the subpartition's subsets for…
score: 3
has title: Partially factoring an expression in Sympy
has answer: http://stackoverflow.com/a/52047556
answer count: 3
tagged with: sympy
possible better answer: http://stackoverflow.com/a/52047556
downvote count: 0
linked to: http://stackoverflow.com/q/19368375
favorite count: 0

http://stackoverflow.com/a/52098503
has comment: http://stackoverflow.com/comment/91147496
has body: You can use str.split: a = [['1/8/2018', 71], ['10/8/2018', 76], ['11/8/2018', 6], ['12/8/2018', 60], ['13/8/2018', 81], ['14/8/2018', 74], ['15/8/2018', 7], ['16/8/2018', 77], ['17/8/2018', 81], ['18/8/2018', 69], ['19/8/2018', 66], ['2/8/2018', 81], ['20/8/2018', 74], ['21/8/2018', 88], ['22/8/2018', 92], ['23/8/2018', 90], ['24/8/2018', 84], ['25/8/2018', 66], ['26/8/2018', 64], ['27/8/2018', 82], ['28/8/2018', 82], ['29/8/2018', 79], ['3/8/2018', 8], ['4/8/2018', 64], ['5/8/2018', 64], ['6/8/2018', 12], ['7/8/2018', 8], ['8/8/2018', 83], ['9/8/2018', 77]] new_a = sorted(a, key=lambda x:[int(i) for i in x[0].split('/')]) Output: [['1/8/2018', 71], ['2/8/2018', 81], ['3/8/2018', 8], ['4/8/2018', 64], ['5/8/2018', 64], ['6/8/2018', 12], ['7/8/2018', 8], ['8/8/2018', 83], ['9/8/2018', 77], ['10/8/2018', 76], ['11/8/2018', 6], ['12/8/2018', 60], ['13/8/2018', 81], ['14/8/2018', 74], ['15/8/2018', 7], ['16/8/2018', 77], ['17/8/2018', 81], ['18/8/2018', 69], ['19/8/2018', 66], ['20/8/2018', 74], ['21/8/2018', 88], ['22/8/2018', 92], ['23/8/2018', 90], ['24/8/2018', 84], ['25/8/2018', 66], ['26/8/2018', 64], ['27/8/2018', 82], ['28/8/2018', 82], ['29/8/2018', 79]]
score: 2
has comment: http://stackoverflow.com/comment/91147398
downvote count: 0
upvote count: 2
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/52098464
answers question: http://stackoverflow.com/q/52098464
type: Answer

http://stackoverflow.com/a/52203805
upvote count: 5
has comment: http://stackoverflow.com/comment/91365656
has comment: http://stackoverflow.com/comment/91360125
score: 5
downvote count: 0
type: Answer
has body: First, let me attempt a less technical and less rigorous version of @jpp's explanation. Generally speaking, when you attempt to insert a numpy array into a pandas dataframe, pandas expects them to have the same rank and dimension (e.g. both are 4x2, although it can also be OK if the rank of the numpy array is lower than the pandas section. It's OK, for example, if the pandas dimension is 4x2 and the numpy dimension is 4x1 or 2x1 -- just read up on numpy broadcasting for more info). The point of the preceding is simply that when you try to put a 3x3 numpy array into a pandas column of length 3 (basically 3x1), pandas doesn't really have a standard way to handle that, and the inconsistent behavior is simply a result of that. It would perhaps be better if pandas always raised an exception, but generally speaking pandas attempts to do something, but it just might not be something useful. Second, (and I realize this is not a literal answer) in the long run I can guarantee you'll be much much better off if you don't spend a lot of time working out the gory details of cramming two dimensional arrays into single pandas columns. Instead, just follow a more typical pandas approach like the following, which will produce code that (1) behaves more predictably, (2) is more readable, and (3) runs much faster. x = np.arange(1,10).reshape(3,3) y = x * 10 z = x * 100 df = pd.DataFrame( np.hstack((x,y)), columns=['x1 x2 x3 y1 y2 y3'.split()] ) # x1 x2 x3 y1 y2 y3 # 0 1 2 3 10 20 30 # 1 4 5 6 40 50 60 # 2 7 8 9 70 80 90 df.loc[:,'x1':'x3'] = z # x1 x2 x3 y1 y2 y3 # 0 100 200 300 10 20 30 # 1 400 500 600 40 50 60 # 2 700 800 900 70 80 90 I kept this as a simple index but it looks perhaps like what you are trying to do is set up a more hierarchical structure, and pandas can help there, with a feature called a MultiIndex. In this case the result is cleaner syntax but note that it can be more complicated to use in other cases (not worth going into details here): df = pd.DataFrame( np.hsta…
answers question: http://stackoverflow.com/q/52080334

http://stackoverflow.com/a/52048751
accepted answer of: http://stackoverflow.com/q/52048314
has body: Your problem reduces to being able to find elementwise minimum of f1 and f2. Numpy has numpy.minimum that does exactly this. So the following code gives the desired plot: import matplotlib.pyplot as plt import numpy as np x = np.array(np.linspace(0, 10, 1000)) f1 = eval('-x+10') f2 = eval('x') f3 = np.minimum(f1, f2) plt.plot(x, f1, label='f1') plt.plot(x, f2, label='f2') plt.fill_between(x, f3, alpha=.5) plt.legend() plt.show()
type: Answer
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/52048314
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/52081318
tagged with: python
tagged with: computer-vision
upvote count: 4
type: AnsweredQuestion
downvote count: 0
has body: I've got a set of 3D-points in a projective space and I want to transform them into a metric 3D space so that I could measure distances in meters. In order to do so, I need a 3D to 3D homography, which is a 4x4 matrix with 15 degrees of freedom (so I need 5 3D-points to get 15 equations). I have a set of these 5 3D-points from the projective space and their corresponding 5 3D-points aligned in the metric space (which I expect the 5 projective points to be transformed to). I can't figure out how to estimate the homography matrix. At first I tried: A=np.vstack([p1101.T, p1111.T, p0101.T, p0001.T, p0011.T]) b=np.array([[1,1,0,1], [1,1,1,1], [0,1,0,1], [0,0,0,1], [0,0,1,1]]) x, _, _, _ = np.linalg.lstsq(A,b) H = x.T where p1101 is a [X,Y,Z,1] point which corresponds to [1,1,0,1] in the 3D metric space, etc.. However, this is not correct since I'm in projective space, so I need to create somehow an equation set where I divide the rows of H with its last or something like that. I thought maybe there is an implemented method that will do it for me, for example in opencv, but didn't find. Any help would be appreciated.
type: Question
tagged with: opencv
score: 4
tagged with: numpy
answer count: 1
has title: Computing 3D-homography with 5 3D-points
favorite count: 0
has answer: http://stackoverflow.com/a/52463107
accepted answer: http://stackoverflow.com/a/52463107

http://stackoverflow.com/q/51984011
score: 0
answer count: 1
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/90917413
has body: My python script suddenly stops when it executes a certain piece of code and before that it was working fine but now it like crashes when it executes it Here is my code: import random; from time import sleep while True: if 'playerName' in locals() or 'playerName' in globals(): continue else: print('What is your name?') playerName = input() print(f'Hi there, {playerName}, welcome to this math game.') sleep(2) print('This game can make yourself custom equations to test your math. (only addition.)') sleep(2) print('Set the limit for numbers. (example. 1000 and 1234)') limit1 = int(input()) limit2 = int(input()) number1 = random.randint(limit1, limit2) number2 = random.randint(limit1, limit2) answer = number1 + number2 print(f'Here is the question: {number1} + {number2}') sleep(1.5) print('Do you know the answer for this?') playerAnswer = input() if int(str(playerAnswer)) == answer: print(f'Good job, {playerName} You answered correctly!') elif int(str(playerAnswer)) != answer: print('Nope the answer is ' + str(int(answer)) + '.') print('Do you want to restart? (y/n)') restart = input() if restart == 'y': continue else: print('Goodbye') break It stops at the very end once it finishes one round. Can someone help me with this?
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51984129
accepted answer: http://stackoverflow.com/a/51984129
type: Question
has title: My python script suddenly stops

http://stackoverflow.com/q/52090826
type: Question
tagged with: opencv
linked to: http://stackoverflow.com/q/37182774
has comment: http://stackoverflow.com/comment/91132056
answer count: 1
linked to: http://stackoverflow.com/q/9710520
favorite count: 0
has title: Passing OpenCv Mat from C++ to Python
type: UnansweredQuestion
tagged with: python
linked to: http://stackoverflow.com/q/30388170
has answer: http://stackoverflow.com/a/57175508
score: 8
tagged with: c++
downvote count: 0
linked to: http://stackoverflow.com/q/29758662
has body: I need to send an OpenCv image from C++ to Python to do some processing on it. The Mat will be received through the code but for simplicity I am using imread here for the question. What I did in the C++ part of the code was: #include &lt;Python.h&gt; #include &lt;arrayobject.h&gt; #include &lt;iostream&gt; #include &lt;opencv2/opencv.hpp&gt; #define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION using namespace cv; using namespace std; int main(int argc, char *argv[]) { QCoreApplication a(argc, argv); Mat image = imread("test.jpg"); Py_Initialize(); PyObject *pName, *pModule, *pDict, *pFunc, *pArgs, *pValue; pName = PyUnicode_FromString("prog"); if (pName == NULL) { PyErr_Print(); return 0; } pModule = PyImport_Import(pName); if (pModule == NULL) { PyErr_Print(); return 0; } pDict = PyModule_GetDict(pModule); pFunc = PyDict_GetItemString(pDict, "add"); if (pFunc == NULL) { PyErr_Print(); return 0; } pArgs = PyTuple_New(1); import_array (); npy_intp dimensions[3] = {image.rows, image.cols, image.channels()}; pValue = PyArray_SimpleNewFromData(image.dims + 1, (npy_intp*)&amp;dimensions, NPY_UINT8, image.data); PyTuple_SetItem(pArgs, 0, pValue); PyObject* pResult = PyObject_CallObject(pFunc, pArgs); if(pResult == NULL) cout&lt;&lt;"Calling the add method failed"&lt;&lt;endl; long result = PyLong_AsLong(pResult); cout&lt;&lt;"Result = "&lt;&lt;result&lt;&lt;endl; Py_Finalize(); return 0; } This code compiles and runs. For the Python part: import cv2 import numpy as np def add (a): print ("Contents of a :") print (a) # mat_array = cv2.fromarray(a, numpy.float32) vis0 = cv.fromarray(a) return 0 The Python code receives the numpy array from C++ (I think) and when I print the contents of a, I have an output (so I think I am receiving the image from C++). Now I need to convert the data in a to a cv2 Mat in Python so that I can work on it. Once I reach the mat_array = cv2.fromarray(a, numpy.float32) line or vis0 = cv.fromarray(a) the code crashes with the following output: Excepti…
upvote count: 8

http://stackoverflow.com/comment/91096943
comment on: http://stackoverflow.com/q/52073181
type: QuestionComment
has text: @Andersson I don't know Python, But Ruby has the similar for loop as well, It wouldn't execute the `driver.find_elements` every-time, it starts to execute on the collection which has been returned by `driver.find_elements` so it goes to stale for sure.
score: 0
type: Comment

http://stackoverflow.com/q/52072311
downvote count: 3
tagged with: fpdf
type: Question
upvote count: 4
answer count: 1
score: 1
has body: I am trying to direct download the generated file by fpdf.output('myfilename.pfd','D') in the browser using Django view. for single python file it works properly but I am unable to do it into the Django view
tagged with: python
favorite count: 0
has answer: http://stackoverflow.com/a/52075118
has title: How to download fpdf output file in django
type: UnansweredQuestion
tagged with: django
tagged with: django-views

http://stackoverflow.com/a/51994300
type: Answer
upvote count: 3
score: 3
has comment: http://stackoverflow.com/comment/90938695
answers question: http://stackoverflow.com/q/51994045
has comment: http://stackoverflow.com/comment/90938743
downvote count: 0
has body: Here is an almost vectorized solution, the only non-vectorized operation is creating your mask, which is mostly vectorized, but you have to create one per column. m = np.column_stack([t[col].duplicated() for col in t]) out = t.mask(m) pd.DataFrame({'mean': np.mean(out), 'sem':ss.sem(out, nan_policy='omit').data}) mean sem c1 2.5 0.645497 c2 2.0 0.577350 c3 1.5 0.500000 c4 1.0 0.000000 I don't have enough memory to test this on your size DataFrame, but here is a sample on 1-million row DataFrame: t = pd.concat([t]*250000) In [649]: %%timeit ...: m = np.column_stack([t[col].duplicated() for col in t]) ...: out = t.mask(m) ...: pd.DataFrame({'mean': np.mean(out), 'sem':ss.sem(out, nan_policy='omit').data}) ...: 326 ms ± 10.4 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
has comment: http://stackoverflow.com/comment/90938947

http://stackoverflow.com/comment/90885519
type: AnswerComment
type: Comment
has text: I'm not using python. I thought you know python enough to fix syntax errors. Check it again.
score: 0
comment on: http://stackoverflow.com/a/51966639

http://stackoverflow.com/q/51962690
has answer: http://stackoverflow.com/a/52353983
tagged with: python
has body: I am currently working on scanned images with Windows 7, Python 3.6 and pytesseract. The images contain text and table regions - it looks somewhat like this: https://tex.stackexchange.com/questions/49300/wrap-text-around-a-tabular. I want to get the coordinates of the table regions in order to crop the images down to that part. Apparently, tesseract defines regions with different properties (PolyBlockTypes see https://tesseract.patagames.com/help/html/T_Patagames_Ocr_Enums_PolyBlockType.htm) - but I can't figure out how to get that information with pytesseract. Can anyone help me? I would like to solve this by either using pytesseract or another python function. EDIT: My current approach is pytesseract.image_to_data(image='&lt; ... &gt;', config='-c gapmap_debug=1') The configuration gapmap_debug=1 doesn't seem to have any effect though ... at least I don't get an output. Am I missing something? More configuration options can be found at http://www.sk-spell.sk.cx/tesseract-ocr-parameters-in-302-version
tagged with: python-tesseract
score: 1
has comment: http://stackoverflow.com/comment/94434641
tagged with: image-processing
type: Question
upvote count: 1
answer count: 1
downvote count: 0
favorite count: 0
linked to: http://stackoverflow.com/q/51626003
has title: Finding table regions with pytesseract
type: UnansweredQuestion

http://stackoverflow.com/q/52033003
has answer: http://stackoverflow.com/a/53177058
downvote count: 0
has body: I'm using django-rest-framework-simplejwt and was wondering if it's possible to return a token after registering a user? This post has a solution for another jwt package and I was wondering how I could do something similar for simplejwt? thanks
tagged with: django-rest-framework
score: 4
answer count: 3
tagged with: python
favorite count: 0
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/52039132
has comment: http://stackoverflow.com/comment/91016668
has comment: http://stackoverflow.com/comment/91016246
tagged with: django
tagged with: jwt
has answer: http://stackoverflow.com/a/52040014
has title: return token after registration with django-rest-framework-simplejwt
linked to: http://stackoverflow.com/q/37622616
has comment: http://stackoverflow.com/comment/91016559
type: Question
upvote count: 4

http://stackoverflow.com/q/52109221
has body: I am testing dataframes for equality. df_diff=(df1!=df2) I get df_diff which is same shape as df*, and contains boolean True/False. Now I would like to keep only the columns and rows of df1 where there was at least a different value. If I simply do df1=[df_diff.values] I get all the rows where there was at least one True in df_diff, but lots of columns originally had False only. As a second step, I would like then to be able to replace all the values (element-wise in the dataframe) which were equal (where df_diff==False) with NaNs. example: df1=pd.DataFrame(data=[[1,2,3],[4,5,6],[7,8,9]]) df2=pd.DataFrame(data=[[1,99,3],[4,5,99],[7,8,9]]) I would like to get from df1 0 1 2 0 1 2 3 1 4 5 6 2 7 8 9 to 1 2 0 2 NaN 1 NaN 6
has answer: http://stackoverflow.com/a/52109248
has title: How to compare two dataframes and filter rows and columns where a difference is found
type: Question
tagged with: equality
has comment: http://stackoverflow.com/comment/91169119
upvote count: 2
tagged with: pandas
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/91169261
favorite count: 0
accepted answer: http://stackoverflow.com/a/52109248
tagged with: python
score: 2
type: AnsweredQuestion

http://stackoverflow.com/comment/90974131
has text: @Aran-Fey *What is `__weakref__`* is not *What is weakref*? That question mentions nothing about built-in types.
type: Comment
comment on: http://stackoverflow.com/q/52011430
score: 0
type: QuestionComment

http://stackoverflow.com/a/55208642
answers question: http://stackoverflow.com/q/51991974
score: 3
downvote count: 0
has body: Another approach is to use duck typing here. If all you care about is that it behaves like a dead weakref with respect to the self._ref() call, then you can do self._ref = lambda : None This is what I ended up using when I had a similar desire to have a property that would return a cached value if it was available, but None otherwise. I initialized it with this lambda function. Then the property was @property def ref(self): return self._ref() Update: Credit to @Aran-Fey, who I see posted this idea as a comment to the question, rather than as an answer.
upvote count: 3
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/51991974
type: Answer

http://stackoverflow.com/a/52058395
score: 27
has body: Role mentions in Discord are triggered like this: &lt;@&amp;ROLE_ID&gt; Where ROLE_ID is the ID of the role you are trying to mention. Get the ID of the Moderators role, add it to the string accordingly and the bot will mention the role as you would from the Discord client. This method also works for webhooks.
type: Answer
upvote count: 27
answers question: http://stackoverflow.com/q/52042695
downvote count: 0
has comment: http://stackoverflow.com/comment/137987182

http://stackoverflow.com/comment/91073916
comment on: http://stackoverflow.com/q/52060572
has text: aah.. i see what you mean! that clear up few thing. if i rename .env_original to .env, pipenv take the bullet and my server runs fine. but since i am moving with encrypted dot file i need to have actual package handling task for me and that point it get fails.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/51973604
score: 0
has body: You can use split as said in above answers. import re a = 'avg yearly income 25,07,708.33 ' b = 'current balance 1,25,000.00 in cash\n' c = 'target savings 50,00,000.00 within next five years 1,000,000.00 ' aa = re.split(r'(\d+(?:,\d+)*(?:\.\d{1,2}))', a) bb = re.split(r'(\d+(?:,\d+)*(?:\.\d{1,2}))', b) cc = re.split(r'(\d+(?:,\d+)*(?:\.\d{1,2}))', c) print(aa) print(bb) print(cc) You can get output like ['avg yearly income ', '25,07,708.33', ' '] ['current balance ', '1,25,000.00', ' in cash\n'] ['target savings ', '50,00,000.00', ' within next five years ', '1,000,000.00', ' ']
type: Answer
answers question: http://stackoverflow.com/q/51973338

http://stackoverflow.com/comment/91003843
type: QuestionComment
type: Comment
score: 1
comment on: http://stackoverflow.com/q/52026789
has text: You are opening `file1` but reading the built-in function name `file`. Please make sure the posted code is *exactly* the code you are asking about.

http://stackoverflow.com/q/52010524
upvote count: 2
has comment: http://stackoverflow.com/comment/90971950
tagged with: pyqt5
type: AnsweredQuestion
score: 2
has body: So I have this code: from PyQt5.QtWidgets import QMainWindow, QApplication, QPushButton, QWidget, QAction, QTabWidget, QVBoxLayout, QHBoxLayout, QComboBox, QLabel from PyQt5.QtGui import QIcon from PyQt5.QtCore import pyqtSlot from lang import getLang import sys, os, configparser config = configparser.ConfigParser() config.read("Settings.ini") # Config get setting and change setting #print(config.get("Main", "language")) #config.set("Main", "language", "danish") #with open("Settings.ini", "w") as cfg_file: #config.write(cfg_file) class App(QMainWindow): def __init__(self): super().__init__() # Window Settings self.x, self.y, self.w, self.h = 0, 0, 300, 200 self.setGeometry(self.x, self.y, self.w, self.h) self.window = MainWindow(self) self.setCentralWidget(self.window) self.setWindowTitle("Window title") # Window Title self.show() class MainWindow(QWidget): def __init__(self, parent): super(QWidget, self).__init__(parent) layout = QVBoxLayout(self) # Run this after settings self.lang = getLang(config.get("Main", "language")) # Initialize tabs tab_holder = QTabWidget() # Create tab holder tab_1 = QWidget() # Tab one tab_2 = QWidget() # Tab two # Add tabs tab_holder.addTab(tab_1, self.lang["tab_1_title"]) # Add "tab1" to the tabs holder "tabs" tab_holder.addTab(tab_2, self.lang["tab_2_title"]) # Add "tab2" to the tabs holder "tabs" # Create first tab tab_1.layout = QVBoxLayout(self) tab_2.layout = QVBoxLayout(self) # Buttons button_start = QPushButton(self.lang["btn_start"]) button_stop = QPushButton(self.lang["btn_stop"]) button_test = QPushButton(self.lang["btn_test"]) # Button Extra button_start.setToolTip("This is a tooltip for the button!") # Message to show when mouse hover button_start.clicked.connect(self.on_click) button_stop.clicked.connect(self.on_click) button_test.clicked.connect(self.on_click) #button_start.setEnabled(False) # comboBox label_language = QLabel("Language") combo_language = QComboBox(self) combo_language.addItem(self.lang["language_danish"]…
has title: widgets placement in tabs
type: Question
tagged with: pyqt
has answer: http://stackoverflow.com/a/52010823
answer count: 1
downvote count: 0
tagged with: python
favorite count: 0
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/52010823
tagged with: qtabwidget

http://stackoverflow.com/q/51987955
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51992735
has comment: http://stackoverflow.com/comment/90927360
accepted answer: http://stackoverflow.com/a/51992735
answer count: 1
has comment: http://stackoverflow.com/comment/90926554
has title: Connecting docker port and ip from another docker
has comment: http://stackoverflow.com/comment/90926312
tagged with: docker
score: 0
tagged with: python
has body: I have one running docker which is for postgres running as below. $ sudo docker container ls CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES 505ab3ffc4b1 postgres "docker-entrypoint..." 26 minutes ago Up 26 minutes 0.0.0.0:5432-&gt;5432/tcp posttest I have another docker, in which a python file is running and trying to connect to postgres which is connecting to localhost:5432 and it failed by following error: $sudo docker run test could not connect to server: Connection refused Is the server running on host "localhost" (127.0.0.1) and accepting TCP/IP connections on port 5432? Inside my test Dockerfile, it is connecting to localhost:5432, How can I connect it to another dockers ip and port? I am new to docker,so please help
has comment: http://stackoverflow.com/comment/90926448
has comment: http://stackoverflow.com/comment/90926734
tagged with: dockerfile
type: Question
has comment: http://stackoverflow.com/comment/90926916

http://stackoverflow.com/a/52050971
has body: It can be done without a loop using just join and map : &gt;&gt;&gt; print('\n'.join(map(str,a))) But, if it is a loop that you are looking for, then using return is the wrong way to go about it, as return would give back the control from the function in its first encounter itself. Instead, use yield or yield from : yield from iterable is essentially just a shortened form of for item in iterable: yield item &gt;&gt;&gt; def looping(): a = [25,50,75,100, 200, 300] yield from a &gt;&gt;&gt; for ele in looping(): print(ele) #driver values : IN : a = [25,50,75,100, 200, 300] OUT: 25 50 75 100 200 300
upvote count: 1
answers question: http://stackoverflow.com/q/52050732
downvote count: 0
type: Answer
score: 1

http://stackoverflow.com/a/59461056
type: Answer
score: -1
downvote count: 1
upvote count: 0
has body: brew install graphviz worked for me.
answers question: http://stackoverflow.com/q/51980938

http://stackoverflow.com/q/51997475
has title: Python. Get dictionary values in "for loop"
has body: I'm trying to work with different APIs and with Binance API I can do itthis way: for coin in data: binance_prices.update( { coin["symbol"]: coin["price"]} ) But Poloniex API's structure is different. I've tried for coin_name in data: for coin in data[coin_name]: print(coin) and for coin_name in data: for coin in data[coin_name]: print(coin[0]) and other different version but none of them worked. I don't understand how to get values for every coin and add them to my dictionary
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51997512
answer count: 2
possible better answer: http://stackoverflow.com/a/51997514
tagged with: api
has answer: http://stackoverflow.com/a/51997512
score: 0
has comment: http://stackoverflow.com/comment/90944150
tagged with: python
has answer: http://stackoverflow.com/a/51997514
type: Question

http://stackoverflow.com/q/52022242
downvote count: 4
upvote count: 0
has answer: http://stackoverflow.com/a/52022591
has comment: http://stackoverflow.com/comment/90995167
type: UnansweredQuestion
score: -4
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/52022539
has body: x = 60 y = 300 platform_name = "Platform" platform_parts = 1 %s.Platform(x,y, "edge_left") % platform_name+"_"+str(platform_parts) This is supposed to create a platform from my Platform class with the name Platform_1, but instead it gives a syntax error, pointing at the %s part. Does anyone know what I'm doing wrong here and how it's supposed to be?
tagged with: python-3.x
answer count: 2
has title: Making a class object with a variable in its name, not working
tagged with: python
has comment: http://stackoverflow.com/comment/90995290
has comment: http://stackoverflow.com/comment/90994767

http://stackoverflow.com/comment/90948748
has text: Do not update your question with the code attempts suggested in answers. Leave your original code
type: Comment
score: 2
comment on: http://stackoverflow.com/q/51999680
type: QuestionComment

http://stackoverflow.com/comment/91057618
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52052299
has text: I have the correct indentation code while running. I am getting the output. But when I try to run .tif image format (which is about 110MB) I am getting this error which says 'out of memory' error. I dont know where I am going wrong.

http://stackoverflow.com/comment/91100575
type: QuestionComment
type: Comment
has text: on the 5th row you get ABC as 24 and not 2. how do you decide to take value for ABC from which column? right or left ?
comment on: http://stackoverflow.com/q/52075353
score: 0

http://stackoverflow.com/a/52049966
type: Answer
answers question: http://stackoverflow.com/q/52049773
score: 1
has body: In your code, try replacing: for val in range(len(lst)): val = int(lst[val]) with: result = [] for row in lst: row_list = [] for i in row.split(): val = int(i.strip()) row_list.append(var) result.append(row_list) or more succintly: result = [[int(i.strip()) for i in row.split()] for row in lst]
upvote count: 1
downvote count: 0

http://stackoverflow.com/q/52106244
tagged with: console-application
answer count: 2
has comment: http://stackoverflow.com/comment/91282020
tagged with: tui
tagged with: urwid
has answer: http://stackoverflow.com/a/52174629
downvote count: 0
has title: How do you combine multiple TUI forms to write more complex applications?
favorite count: 0
has body: I would like to write a program with a Text-based User Interface (TUI) that consists of several forms. The first form contains a "list". Each list element represents a button. If the respective button is pressed, another form should appear in which one can enter the data for the list entry. Then the first form is displayed again (with updated list entries). Here is my attempt, which uses the library npyscreen but does not return to the first form. The code does also not contain the logic to change the list item. #! /usr/bin/env python3 # coding:utf8 import npyscreen # content headers = ["column 1", "column 2", "column 3", "column 4"] entries = [["a1", "a2", "a3", "a4"], ["b1", "b2", "b3", "b4"], ["c1", "c2", "c3", "c4"], ["d1", "d2", "d3", "d4"], ["e1", "e2", "e3", "e4"]] # returns a string in which the segments are padded with spaces. def format_entry(entry): return "{:10} | {:10} | {:10} | {:10}".format(entry[0], entry[1] , entry[2], entry[3]) class SecondForm(npyscreen.Form): def on_ok(self): self.parentApp.switchFormPrevious() # add the widgets of the second form def create(self): self.col1 = self.add(npyscreen.TitleText, name="column 1:") self.col2 = self.add(npyscreen.TitleText, name="column 2:") self.col3 = self.add(npyscreen.TitleText, name="column 3:") self.col4 = self.add(npyscreen.TitleText, name="column 4:") class MainForm(npyscreen.Form): def on_ok(self): self.parentApp.switchForm(None) def changeToSecondForm(self): self.parentApp.change_form("SECOND") # add the widgets of the main form def create(self): self.add(npyscreen.FixedText, value=format_entry(headers), editable=False, name="header") for i, entry in enumerate(entries): self.add(npyscreen.ButtonPress, when_pressed_function=self.changeToSecondForm, name=format_entry(entry)) class TestTUI(npyscreen.NPSAppManaged): def onStart(self): self.addForm("MAIN", MainForm) self.addForm("SECOND", SecondForm, name="Edit row") def onCleanExit(self): npyscreen.notify_wait("Goodbye!") def change_form(self, name)…
tagged with: python
has answer: http://stackoverflow.com/a/53953516
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/52174629
score: 7
tagged with: npyscreen
has comment: http://stackoverflow.com/comment/91261077
upvote count: 7
possible better answer: http://stackoverflow.com/a/53953516
type: Question

image-processing
tags question: http://stackoverflow.com/q/52004133
tags question: http://stackoverflow.com/q/52052884
tags question: http://stackoverflow.com/q/52017297
tags question: http://stackoverflow.com/q/52062060
tags question: http://stackoverflow.com/q/51979554
tags question: http://stackoverflow.com/q/52045608
tags question: http://stackoverflow.com/q/52013574
tags question: http://stackoverflow.com/q/52047126
tags question: http://stackoverflow.com/q/52073964
tags question: http://stackoverflow.com/q/52020536
tags question: http://stackoverflow.com/q/52007898
tags question: http://stackoverflow.com/q/52037492
tags question: http://stackoverflow.com/q/52049865
tags question: http://stackoverflow.com/q/51986717
tags question: http://stackoverflow.com/q/52112399
tags question: http://stackoverflow.com/q/52069454
tags question: http://stackoverflow.com/q/52016616
tags question: http://stackoverflow.com/q/51974279
tags question: http://stackoverflow.com/q/52062580
type: Tag
tags question: http://stackoverflow.com/q/52091437
tags question: http://stackoverflow.com/q/52069367
tags question: http://stackoverflow.com/q/52021661
tags question: http://stackoverflow.com/q/52044149
tags question: http://stackoverflow.com/q/51995182
tags question: http://stackoverflow.com/q/52032296
tags question: http://stackoverflow.com/q/52047851
tag name: image-processing
tags question: http://stackoverflow.com/q/52001891
tags question: http://stackoverflow.com/q/51962690
tags question: http://stackoverflow.com/q/52071822
tags question: http://stackoverflow.com/q/52109710
tags question: http://stackoverflow.com/q/52085468
tags question: http://stackoverflow.com/q/52076168

http://stackoverflow.com/comment/91087207
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/52068188
has text: Your attempts are all copying the list, and then making three references to that copy, which isn’t any better than just making three references to the original list. If you move the `deepcopy` _outside_ the multiplication… but you’re still better off using a comprehension in the first place

http://stackoverflow.com/q/52079637
type: AnsweredQuestion
tagged with: scroll
has body: I have been trying to scroll the output of a script run via Ipython in a separate window/session created by tmux (off notebook, meaning that I am not using Ipython notebook as usual: I am just using Ipython). I see that, while the program is loading the output, I can’t scroll the window to see what has been published before, and can just visualize the latest results produced. Honestly, this problem comes totally unexpected because I usually use a notebook and have never encountered a similar issue. Could you help me please? Thanks in advance
tagged with: ipython
has answer: http://stackoverflow.com/a/52099637
type: Question
possible better answer: http://stackoverflow.com/a/52079720
has comment: http://stackoverflow.com/comment/91109420
has answer: http://stackoverflow.com/a/52079720
downvote count: 0
has title: Impossible to scroll Ipython (not notebook!) while producing output within tmux window
score: 4
upvote count: 4
answer count: 2
accepted answer: http://stackoverflow.com/a/52099637
tagged with: tmux
favorite count: 0
tagged with: python
tagged with: freeze

http://stackoverflow.com/q/52004515
has comment: http://stackoverflow.com/comment/90958417
tagged with: pandas
has comment: http://stackoverflow.com/comment/90958613
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/52004740
type: Question
tagged with: python
has body: id start end 1 2001 2005 2 2004 2007 output id date 1 2001 1 2002 1 2003 1 2004 1 2005 2 2004 2 2005 2 2006 2 2007 my logics df=pd.concat([pd.DataFrame({'start': pd.date_range(row.start, row.end, freq='AS'), 'id': row.id}, columns=['start', 'id']) for i, row in df.iterrows()], ignore_index=True) df1 = (pd.concat([pd.Series(r.id, pd.date_range(r.start, r.end, freq='AS')) for r in df.itertuples()]) .reset_index()) My data frame has minimum 300 000 rows so these are not the efficient solutions. Is there more efficient solution? note: start and end are annual, monthly,daily....formats. I have given annual example.
score: 0
answer count: 1
has comment: http://stackoverflow.com/comment/90958582
has title: Find all dates of particular row using python pandas

http://stackoverflow.com/q/52031971
has body: I don't fully understand how to use replace roles in discord.py. I have searched everywhere on the internet but I still can't seem to figure out how to implement it. I am trying to make it so the user can self assign roles but only have 1 role at a time. For example, if they had the role "1" and typed in a command to get role "2", I want the bot to replace role "1" with role "2" so they should only have role "2". I made sure the bots role is higher in the hierarchy than the roles I made for people to assign themselves and the bot has manage roles perms. I am not using rewrite and I'm using python 3.6.
type: Question
has title: replace_roles discord.py really confusing?
tagged with: discord.py
answer count: 2
upvote count: 0
score: -2
tagged with: replace
has answer: http://stackoverflow.com/a/53722526
favorite count: 0
type: UnansweredQuestion
downvote count: 2
tagged with: python
has answer: http://stackoverflow.com/a/52040611
tagged with: roles
tagged with: bots

http://stackoverflow.com/q/52082140
downvote count: 1
type: Question
type: AnsweredQuestion
score: 0
accepted answer: http://stackoverflow.com/a/52082219
answer count: 3
tagged with: pandas
has answer: http://stackoverflow.com/a/52082294
favorite count: 0
possible better answer: http://stackoverflow.com/a/52082294
has title: Pandas identifying repetition in subsequent columns and keeping first occurances
has body: I know how to get rid of duplicate rows in pandas, however my problem is slightly different. Let's assume I have a dataframe like this: product from stop_1 stop_2 stop_3 stop_4 stop_5 stop_6 stop_7 metal Portugal Spain France Ukraine Spain France Ukraine Spain fruit Spain France Italy dairy Italy Switzerland Italy Switzerland This is what I want to obtain: product from stop_1 stop_2 stop_3 stop_4 stop_5 stop_6 stop_7 metal Portugal Spain France Ukraine fruit Spain France Italy dairy Italy Switzerland How I could I get this?
tagged with: python
has answer: http://stackoverflow.com/a/52082401
has answer: http://stackoverflow.com/a/52082219
upvote count: 1

http://stackoverflow.com/comment/91072700
has text: I don't know python well enough to give you actual code, but basically you need to break up the file into separate chunks BEFORE giving it to the XML parser; to do this "breaking up" it's probably simplest in this case to read the file line by line and detect the <?xml?> declarations; when you hit such a declaration you can construct the previous XML entity and pass it in some form to the XML parser. You will just have to hope that there's nothing evil in the XML content, e.g. something in a CDATA section that can be confused with an XML declaration.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52054842

http://stackoverflow.com/q/51981090
tagged with: pandas
has title: How optimize this piece of code?
upvote count: 1
downvote count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/51981690
tagged with: python-3.x
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90914142
has body: my data looks like this it is list of dicts: wishlist_result[0] = {'userId': 19814, 'entityIds': [40, 45, 54, 322]} I am converting it into: user_id : 19814 entity_id : 40, user_id : 19814 entity_id : 45, user_id : 19814 entity_id : 54, user_id : 19814 entity_id : 322 wishlist_data = pd.DataFrame() for i in wishlist_result: wishlist_from_dict = pd.DataFrame.from_dict( wishlist_result[wishlist_result.index(i)]) wishlist_data = wishlist_data.append( wishlist_from_dict, ignore_index=True) wishlist_data = wishlist_data.rename( index=str, columns={ "userId": "user_id", "entityIds": "entity_id" }) This code is taking too long I have around 60k records like I mentioned above any way to get this conversion in less time ??
type: Question
possible better answer: http://stackoverflow.com/a/51981690
has answer: http://stackoverflow.com/a/51981559
accepted answer: http://stackoverflow.com/a/51981559
score: 0
answer count: 2

http://stackoverflow.com/a/52049653
has body: I don't know the robot framework but this is the XPath locator you want //a[.//div[@class='theme-cell-card Ace']] That will get you the A tags that contain a DIV that has the desired classes. You can get the href from that element along with the contained text. Since your question is tagged python, you can use something simple like aces = driver.find_elements_by_xpath("//a[.//div[@class='theme-cell-card Ace']]") for ace in aces print(ace.get_attribute("href")) print(ace.text)
accepted answer of: http://stackoverflow.com/q/52048943
answers question: http://stackoverflow.com/q/52048943
has comment: http://stackoverflow.com/comment/91085829
has comment: http://stackoverflow.com/comment/91068746
has comment: http://stackoverflow.com/comment/91050398
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/91085755
score: 0
type: Answer
has comment: http://stackoverflow.com/comment/91068641

http://stackoverflow.com/a/52085125
downvote count: 0
type: Answer
has body: You should validate user input via form before handing it to model. IntegerField would help you.
score: 1
answers question: http://stackoverflow.com/q/52082831
upvote count: 1

http://stackoverflow.com/q/52077548
has comment: http://stackoverflow.com/comment/91105116
has body: EDIT: data from cosiek.txt: time 20 speed 50 sth 30 car new I have a problem with importing data from my text (tab delimited) file to python script I got: name,value = line.split("\t") ValueError: not enough values to unpack (expected 2, got 1) this is my code and picture of cosiek44.txt variables = {} with open("cosiek44.txt") as f: for i,line in enumerate(f): if i &lt;=2: name,value = line.split("\t") variables[name] = float(value) else: name,value = line.split("\t") variables[name] = str(value) a=variables["time"] b=variables["speed"] c=variables["sth"] d=variables["new"]
has comment: http://stackoverflow.com/comment/91106349
has comment: http://stackoverflow.com/comment/91104990
type: Question
tagged with: for-loop
has title: How to import data from text file into python's loop
upvote count: 1
score: -2
linked to: http://stackoverflow.com/q/3277503
has comment: http://stackoverflow.com/comment/91104923
downvote count: 3
tagged with: http://stackoverflow.com/tag/csv
answer count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/91104958
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/52077972

http://stackoverflow.com/comment/91138689
has text: There is no `null` byte in Python. Primitive datatype such as byte can only have values in all languages I know. IMHO there's even no `byte` datatype in Python at all. So either you're talking about a byte sequence, which could be `None` or something else. Maybe it would be best to show your code.
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/52094226

http://stackoverflow.com/q/52109730
favorite count: 0
type: UnansweredQuestion
has title: Decision Trees - Taking a long time to process String values but working fine for float values. How to understand?
tagged with: python
upvote count: 0
tagged with: machine-learning
has body: I am trying to build a decision tree classifier using the code below from sklearn.tree import DecisionTreeClassifier clf = DecisionTreeClassifier() and my data is age type_income loan_purpose loan_amount offer 18 Student study 500 yes 18 Student study 600 yes 18 Student study 700 yes 18 Student study 800 yes . . . so the decision tree gives out an error saying that it can't convert Student into a float value. What can I do to resolve this? I don't want the data to be converted manually to float through preprocessing I want that the algorithm itself handles this issue. Is there any parameter to be passed which can fix this automatically?
has answer: http://stackoverflow.com/a/52109928
type: Question
score: -1
answer count: 2
has answer: http://stackoverflow.com/a/52110186
downvote count: 1
tagged with: decision-tree

http://stackoverflow.com/a/52031642
answers question: http://stackoverflow.com/q/52031553
upvote count: 3
score: 3
type: AcceptedAnswer
downvote count: 0
has body: heroku:config only sets environment variables on Heroku. To run your code locally you will have to set your environment variables locally. (They can be different in development and production. That's the whole idea—they're environment-specific.) There are several ways to do this. Here are two: On your local machine you can use a .env file containing data in the format VAR1=value VAR2=value2 and then run your application using Foreman, which will automatically read the .env file and set appropriate environment variables: foreman start You can set environment variables using something like direnv, which will read an .envrc file for your project whenever you cd into its directory and set environment variables accordingly. In this case you don't need to use Foreman; python app.py should work fine. There are editor and IDE plugins for direnv that can automate this in your editor as well.
accepted answer of: http://stackoverflow.com/q/52031553
type: Answer

http://stackoverflow.com/comment/124741555
score: 0
type: Comment
has text: Yes, you are right, @kriss. That's what is mentioned in the link I posted in the comment.
type: AnswerComment
comment on: http://stackoverflow.com/a/52000273

http://stackoverflow.com/q/52026823
favorite count: 0
upvote count: 2
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91151448
tagged with: python
score: 2
answer count: 0
tagged with: tensorflow
type: Question
has body: I modeled a two layered LSTM Keras model then I compared the output of the first LSTM layer with my simple python implementation of the LSTM layer by feeding in the same weights and Inputs. The results for the first sequence of a batch are similar but not same and from the second sequence the results deviates too far. Below is my keras model: For comparison of the Keras model I first created an intermediate layer where the intermediate layer outputs the result of the first layer with print(intermediate_output[0,0])for the first sequence and print(intermediate_output[0][1]) for the second sequence of the same batch then print(intermediate_output[0][127]) for the last sequence. inputs = Input(shape=(128,9)) f1=LSTM((n_hidden),return_sequences=True,name='lstm1')(inputs) f2=LSTM((n_hidden), return_sequences=False,name='lstm2')(f1) fc=Dense(6,activation='softmax',kernel_regularizer=regularizers.l2(lambda_loss_amount),name='fc')(f2) model2 = Model(inputs=inputs, outputs=fc) layer_name = 'lstm1' intermediate_layer_model = Model(inputs=model2.input, outputs=model2.get_layer(layer_name).output) intermediate_output = intermediate_layer_model.predict(X_single_sequence[0,:,:]) print(intermediate_output[0,0]) # takes input[0][9] print(intermediate_output[0][1]) # takes input[1][9] and hidden layer output of intermediate_output[0,0] print(intermediate_output[0][127]) Re-Implemented first layer of the same model: I defined LSTMlayer function where it does the same computation....after that weightLSTM loads the saved weights and x_t the same input sequence and later on h_t contains outputs for the next sequence. intermediate_out is a function corresponding to that of LSTM layer. def sigmoid(x): return(1.0/(1.0+np.exp(-x))) def LSTMlayer(warr,uarr, barr,x_t,h_tm1,c_tm1): ''' c_tm1 = np.array([0,0]).reshape(1,2) h_tm1 = np.array([0,0]).reshape(1,2) x_t = np.array([1]).reshape(1,1) warr.shape = (nfeature,hunits*4) uarr.shape = (hunits,hunits*4) barr.shape = (hunits*4,) ''' s_t = (x_t.…
has comment: http://stackoverflow.com/comment/91785073
has comment: http://stackoverflow.com/comment/91160053
has comment: http://stackoverflow.com/comment/91198698
tagged with: lstm
has comment: http://stackoverflow.com/comment/91764550
has title: Keras LSTM layer output and the output of a numpy LSTM implementation are similar but not same with the same weights and Input
downvote count: 0
tagged with: keras

http://stackoverflow.com/comment/91020822
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52028552
score: 0
has text: @abarnert Yes thats pretty much it. I also already saw that someone already started it. I would concentrate on doing it for linux to start with. Juding from your answer, that would probably mean that the implementation is different for all of these platforms and all of these architectures(atleast some of them) ?

http://stackoverflow.com/comment/90941887
score: 0
type: AnswerComment
has text: x[e] returns the value of x in e and ba.index() returns the index of x[e] in ba, key is parameter that sort receives and is the value that is used to sort the list
type: Comment
comment on: http://stackoverflow.com/a/51965149

http://stackoverflow.com/a/51973115
type: Answer
score: 2
upvote count: 2
has body: Instead of printing, just write to a file instead. with open('filename.txt', 'w') as f: f.write('{}\n'.format(email))
downvote count: 0
answers question: http://stackoverflow.com/q/51972554

http://stackoverflow.com/q/52015499
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90981370
answer count: 0
tagged with: keras
has body: I was trying to build my first Keras deep neural network on Tensorflow and want to deployed it using Flask. I took a sample data airline data and wanted to predict if the flight gets delayed or not. To start with, I took only sample columns : Year, Month, DayOfWeek, UniqueCarrier, FlightNum, Origin, Dest, Distance. Converted UniqueCarrier, Origin, Dest into numeric values using label encoder. Then after running the below program found the accuracy to be 93%. But when I run a prediction manually by sending the parameters through rest api then I always get 1 as output. Not sure as what needs to be done. Below is some of the code and Sample output: le = LabelEncoder() data["UniqueCarrier"] = le.fit_transform(data["UniqueCarrier"]) UniqueCarrier = list(le.classes_) print(UniqueCarrier) data["Origin"] = le.fit_transform(data["Origin"]) Carrier = list(le.classes_) print(Carrier) data["Dest"] = le.fit_transform(data["Dest"]) TailNum = list(le.classes_) print(TailNum) Data set up as predictors and target: rfDataOriginal = pd.DataFrame(data) Delay_YesNo = rfDataOriginal['IsDepDelayed'] rfDataOriginal.drop(['IsDepDelayed'], axis=1, inplace=True) Removing target variable: print('Dimension reduced to:') print(len(rfDataOriginal.columns)) Feature Scaling: from sklearn.preprocessing import StandardScaler sc = StandardScaler() X_train = sc.fit_transform(X_train) X_test = sc.transform(X_test) Creating the model: from keras.models import Sequential from keras.layers import Dense model = Sequential() model.add(Dense(15, input_dim=12, activation='relu')) model.add(Dense(15, activation='relu')) model.add(Dense(15, activation='relu')) model.add(Dense(1, activation='sigmoid')) model.summary() Compiling model: model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy']) Log for Tensorboard graph purpose: import keras tbCallBack = keras.callbacks.TensorBoard(log_dir='/tmp/keras_logs', write_graph=True) Fitting the model: model.fit(X_train, y_train, epochs=5, batch_size…
has comment: http://stackoverflow.com/comment/90984256
type: Question
tagged with: python
score: 0
tagged with: machine-learning
has title: Bad predictions but good model accuracy
tagged with: tensorflow
has comment: http://stackoverflow.com/comment/90984894

http://stackoverflow.com/comment/91144986
has text: don't forget a final yield to yield the end of the args
type: AnswerComment
comment on: http://stackoverflow.com/a/52096896
score: 0
type: Comment

http://stackoverflow.com/comment/91023133
has text: This is very helpful. Thank you for explaining it. Upon removing the with statement, the error went away. Although, I have hit an unusual issue where only the statistics of the file is going into the new file. The original file is not being copied into the file. It's almost as if the for loop was completely ignored for some reason
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52036451
type: AnswerComment

http://stackoverflow.com/q/52078191
tagged with: python
tagged with: pytest
has title: pytest fill list in setup and use for test cases
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91106621
type: Question
score: 0
has comment: http://stackoverflow.com/comment/91106395
has body: First of all: There are probably hundreds of answers to this already and I am sorry for asking it, but I just..do not understand. I want to use a list in certain test-cases which is parsed from a csv-file. Since I don't want to parse the list multiple times, I want to do that during the setup process. The pytest documentation recommends fixtures for that. I figure I use them like this: @pytest.fixture() def init_my_list(): return my_service.read_from_csv('my_file.csv') and then call when necessary: def test_get_info(): test_date = datetime.datetime(year=2018, month=8, day=15, hour=6) assert (some, values) == myservice.get_prediction_for_datetime(test_date, init_my_list) This returns TypeError: 'function' object is not iterable because the myservice.function iterates over the given list, but the fixture returns a function instead of a list. All I want is list which is created at the setup, and then can be used in my test cases. How do I achieve this simple task? Entire Traceback as requested: def get_prediction_for_datetime(dt: datetime, prediction_list: list) -> (int, float): try: result = next(x for x in prediction_list if dt.hour == x[0].hour and dt.day == x[0].day and dt.month == x[0].month and dt.year == x[0].year) E TypeError: 'function' object is not iterable
answer count: 1
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/91106988
has answer: http://stackoverflow.com/a/52078374
accepted answer: http://stackoverflow.com/a/52078374

http://stackoverflow.com/comment/91064107
type: AnswerComment
score: 0
type: Comment
has text: @neeraja - Why `NBR` and `CBK` are swapped? Ordering is `['RK', 'NBR', 'CBK']` in sample data in `df1`, or not?
comment on: http://stackoverflow.com/a/52052408

http://stackoverflow.com/a/66925056
type: Answer
score: 3
downvote count: 0
answers question: http://stackoverflow.com/q/51961233
has body: If you want to just print. You can simply use toarray() method and convert it to an array. Similarly, you can also convert it into a data frame to perform any pandas operations using the pandas Dataframe() method. X = sparse.csr_matrix(1./2.*np.array([[0.,1.],[1.,0.]])) print(X.toarray()) X_df =pd.DataFrame(X.toarray()) X_df
upvote count: 3

spyder
tag name: spyder
tags question: http://stackoverflow.com/q/52029706
tags question: http://stackoverflow.com/q/52026360
type: Tag
tags question: http://stackoverflow.com/q/51986128
tags question: http://stackoverflow.com/q/52109370
tags question: http://stackoverflow.com/q/52001599
tags question: http://stackoverflow.com/q/51969662
tags question: http://stackoverflow.com/q/52017163
tags question: http://stackoverflow.com/q/51967975

http://stackoverflow.com/comment/91051626
type: QuestionComment
comment on: http://stackoverflow.com/q/52050700
score: 0
has text: Checkout your traceback error. You were trying find length of a **None** object.
type: Comment

http://stackoverflow.com/comment/91014742
type: Comment
comment on: http://stackoverflow.com/q/52032189
type: QuestionComment
score: 0
has text: what is `r.text` and `r.status_code`?

http://stackoverflow.com/q/52064626
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/91079708
has body: I am trying get data of this site http://veiculos.fipe.org.br/ the json file I want to get is the one that appears on the right of the image url = "http://veiculos.fipe.org.br/api/veiculos/ConsultarValorComTodosParametros" data = {"codigoTabelaReferencia" : "215", "codigoMarca" : "2", "codigoModelo" : "4564", "codigoTipoVeiculo" : "1", "anoModelo" : "2015", "codigoTipoCombustivel " : "3", "tipoVeiculo" : "carro", "modeloCodigoExterno" : "", "tipoConsulta" : "tradicional" } c = requests.post(url,data=data) c.json() when the last line is executed this error meassege return: JSONDecodeError: Expecting value: line 2 column 1 (char 2) At the end of the code I want this dictionary to be returned: {"Valor":"R$ 14.421,00","Marca":"Alfa Romeo","Modelo":"145 Quadrifoglio 2.0","AnoModelo":1999,"Combustivel":"Gasolina","CodigoFipe":"006002-0","MesReferencia":"agosto de 2018 ","Autenticacao":"hsd0d2ycx5","TipoVeiculo":1,"SiglaCombustivel":"G","DataConsulta":"terça-feira, 28 de agosto de 2018 16:10"}
has comment: http://stackoverflow.com/comment/91080547
score: 0
linked to: http://stackoverflow.com/q/16877422
tagged with: python
has comment: http://stackoverflow.com/comment/91080139
has answer: http://stackoverflow.com/a/52064735
favorite count: 0
has comment: http://stackoverflow.com/comment/91079926
has answer: http://stackoverflow.com/a/52065188
possible better answer: http://stackoverflow.com/a/52064735
upvote count: 1
tagged with: python-requests
downvote count: 1
has comment: http://stackoverflow.com/comment/91080409
type: AnsweredQuestion
tagged with: http://stackoverflow.com/tag/json
accepted answer: http://stackoverflow.com/a/52065188
has title: Get a json of a post method

http://stackoverflow.com/q/51991021
has body: I know that header = np.array(["AA","AC"],dtype='U2') will create a numpy array containing strings that are made out of 2 letters. How does it difer compared to header = np.array(["AA","AC"],dtype='|U2') ?
linked to: http://stackoverflow.com/q/42264963
upvote count: 1
favorite count: 0
type: UnansweredQuestion
tagged with: python
answer count: 0
downvote count: 0
duplicate of: http://stackoverflow.com/q/42264963
score: 1
type: Question
tagged with: numpy
has title: What is the difference between |U and U regarding numpy dtype specifier for strings
has comment: http://stackoverflow.com/comment/90932176

http://stackoverflow.com/comment/91230585
type: Comment
has text: I tried to catch the exceptions by adding a ExceptionMiddleware, I'm getting the error "TypeError: __init__() missing 1 required positional argument: 'application'", Updated the same in the post.
comment on: http://stackoverflow.com/a/52110433
type: AnswerComment
score: 0

http://stackoverflow.com/q/51976328
has body: I'm trying to build a corpus from the .txt file found at this link. I believe the instances of \xad are supposedly 'soft-hyphens', but do not appear to be read correctly under UTF-8 encoding. I've tried encoding the .txt file as iso8859-15, using the code: with open('Harry Potter 3 - The Prisoner Of Azkaban.txt', 'r', encoding='iso8859-15') as myfile: data=myfile.read().replace('\n', '') data2 = data.split(' ') This returns an array of 'words', but '\xad' remains attached to many entries in data2. I've tried data_clean = data.replace('\\xad', '') and data_clean = data.replace('\\xad|\\xad\\xad','') but this doesn't seem to remove the instances of '\xad'. Has anyone ran into a similar problem before? Ideally I'd like to encode this data as UTF-8 to avail of the nltk library, but it won't read the file with UTF-8 encoding as I get the following error: UnicodeDecodeError: 'utf-8' codec can't decode byte 0xad in position 471: invalid start byte Any help would be greatly appreciated! Additional context: This is a recreational project with the aim of being able to generate stories based on the txt file. Everything I've generated thus far has been permeated with '\xad', which ruins the fun!
has comment: http://stackoverflow.com/comment/90903354
favorite count: 0
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90903099
has answer: http://stackoverflow.com/a/51976543
accepted answer: http://stackoverflow.com/a/51976543
has comment: http://stackoverflow.com/comment/90903073
type: Question
upvote count: 15
tagged with: encoding
downvote count: 0
answer count: 1
has title: Best way to remove '\xad' in Python?
score: 15
tagged with: str-replace
has comment: http://stackoverflow.com/comment/90903160
tagged with: unicode-escapes
has comment: http://stackoverflow.com/comment/90903380

http://stackoverflow.com/q/51957186
tagged with: python
has title: How to calculate Rolling Correlation with pandas?
has answer: http://stackoverflow.com/a/51957307
type: AnsweredQuestion
type: Question
upvote count: 22
answer count: 2
tagged with: dataframe
accepted answer: http://stackoverflow.com/a/51957307
score: 22
tagged with: pandas
downvote count: 0
favorite count: 0
has body: I understand how to calculate a rolling sum, std or average. Example: df['MA10'] = df['Asset1'].rolling(10).mean() But I don't understand the syntax to calculate the rolling correlation between two dataframes columns: df['Asset1'] and df['Asset2'] The documentation doesn't provide any example regarding the correlation. https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.rolling.html Any insights? Thanks!
tagged with: correlation
possible better answer: http://stackoverflow.com/a/76067820
has answer: http://stackoverflow.com/a/76067820

http://stackoverflow.com/comment/90883356
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51966650
has text: @Chris_Rands, yes, my mistake. I didn't realize at first that the indentation was so wrong.
score: 0

http://stackoverflow.com/comment/90897268
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/51973231
type: Comment
has text: A life lesson on [when not to use RegEx](https://stackoverflow.com/a/1732454/4743630). Use the modules recommended by Daniel or Jenny instead.

http://stackoverflow.com/comment/92357339
has text: This makes sense, yes, and agrees with my solution of using a try/except instead.
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52712708

http://stackoverflow.com/a/51958476
score: 0
has body: Let's break down your attempt to index the grid, listItem = grid[[itemNumber][elementNumber]] We first print the values of the variables; itemNumber and elementNumber are both 1 at this point. That makes this expression listItem = grid[[1][1]] To evaluate the expression grid[1][1]], we start with the index you gave,[1][1]; note the extra barckets. Working from the inside out,[1](the left-hand one) is a list with a single element, the integer1. You now try to access an element of this list, element1. However, since [1] is a list with only one element, its only valid index is0`. This is where your error shows up. The proper assignment is listItem = grid[itemNumber][elementNumber] This will evaluate grid[1][1], which is row 2, column 2 of your 7x7 grid.
type: Answer
answers question: http://stackoverflow.com/q/51958350

http://stackoverflow.com/comment/90919795
type: Comment
has text: @PageDavid Win10, MSVC2013 64bit. Switching to pointers makes no difference in release build here. My guess would be that the stdlib that g++ uses has some additional checks in vector operator[]...
comment on: http://stackoverflow.com/q/51982344
score: 0
type: QuestionComment

http://stackoverflow.com/comment/91005174
comment on: http://stackoverflow.com/q/52027498
has text: what exactly goes wrong here? what is `response.text`?
type: Comment
score: 1
type: QuestionComment

http://stackoverflow.com/comment/91120999
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52084979
has text: you're going to need to read in the file, opening it isn't enough. you'll have to do `f = open('diff.txt', 'r')` then `NEW_COMPANIES = f.read()`

http://stackoverflow.com/q/51987657
answer count: 2
has answer: http://stackoverflow.com/a/51988057
accepted answer: http://stackoverflow.com/a/51988057
downvote count: 1
has comment: http://stackoverflow.com/comment/90924810
favorite count: 0
has comment: http://stackoverflow.com/comment/90949394
possible better answer: http://stackoverflow.com/a/51987770
has answer: http://stackoverflow.com/a/51987770
tagged with: python
has body: I have output generated by python (u'PK_LampFactoryTest',) (u'DF__Thermosta__Enabl__7B264821',) (u'filestream_tombstone_2073058421',) (u'RetentionSettings',) (u'Alarms',) (u'syscommittab',) sqlquery = 'SELECT NAME FROM sys.objects' cursor.execute(sqlquery) #conn.commit() for row in cursor: print(row)
type: AnsweredQuestion
upvote count: 0
linked to: http://stackoverflow.com/q/9773121
type: Question
has comment: http://stackoverflow.com/comment/90927541
has title: I want to remove u from the output file
score: -1
has comment: http://stackoverflow.com/comment/90924808
has comment: http://stackoverflow.com/comment/90927784

http://stackoverflow.com/comment/91076104
score: 2
comment on: http://stackoverflow.com/q/52062896
type: Comment
type: QuestionComment
has text: Do you already know how to turn `'1, 2, 3'` into `['1', '2', '3']`?

http://stackoverflow.com/comment/92336815
type: Comment
comment on: http://stackoverflow.com/a/52702646
score: 0
type: AnswerComment
has text: @VPfB: sure, that's fine. I've added a link to a blog post that helped me make huge strides in understanding the concepts involved here.

http://stackoverflow.com/a/66328524
answers question: http://stackoverflow.com/q/52092881
has comment: http://stackoverflow.com/comment/117263107
type: Answer
upvote count: 1
downvote count: 1
score: 0
has body: img = tf.image.decode_png(file_bytes, channels=3) you can use decode_png for png files

http://stackoverflow.com/a/52195731
accepted answer of: http://stackoverflow.com/q/52108065
has body: Look at the last line of the stack trace. You are calling the “method”, but it’s just a wrapper for a corresponding method on self.instance and it’s that getattr that’s failing. The outer attribute lookup succeeded in creating the wrapper, which made hasattr happy, and the wrapper is indeed callable. The hasattr test would work if the getattr(self.instance, __name) were computed when the wrapper was created. If the wrapper’s only purpose is to be called (rather than, say, having methods of its own), it could perform a callable check of its own as well. But Python gives itself to EAFP, so here we are.
type: Answer
score: 0
answers question: http://stackoverflow.com/q/52108065
type: AcceptedAnswer

http://stackoverflow.com/a/52273403
score: 0
type: Answer
answers question: http://stackoverflow.com/q/52093695
has body: Generally, learning rate is too high when cost is increasing.

http://stackoverflow.com/q/51991220
type: UnansweredQuestion
has body: I have the following in my conftest.py file def pytest_collection_modifyitems(config,items): with open("C:\Users\xyz\mno\cli_automation\test_configuration\project\test_command.yml", 'r') as stream: data_loaded = yaml.load(stream) for i in items: if i.name == data_loaded.get("test_name"): i.add_marker(data_loaded.get("test_type")) pytest_runtest_call(i) I am unable to send the loaded yaml configuration details to my pytest_runtest_call . How can I achieve it ?
type: Question
has comment: http://stackoverflow.com/comment/90938030
tagged with: pytest
has title: How to send parameters to pytest_runtest_call
has comment: http://stackoverflow.com/comment/90942050
score: 0
tagged with: python
answer count: 0

http://stackoverflow.com/q/51963377
accepted answer: http://stackoverflow.com/a/51963732
has answer: http://stackoverflow.com/a/54233127
type: AnsweredQuestion
tagged with: conv-neural-network
score: 1
tagged with: machine-learning
upvote count: 1
has title: keras 'NoneType' object has no attribute '_inbound_nodes'
type: Question
answer count: 2
tagged with: deep-learning
has comment: http://stackoverflow.com/comment/90876984
downvote count: 0
tagged with: keras
favorite count: 0
has answer: http://stackoverflow.com/a/51963732
has comment: http://stackoverflow.com/comment/90877122
tagged with: python
possible better answer: http://stackoverflow.com/a/54233127
has body: I am trying to write a discriminator that evaluates patches of an image. Therefore I generate 32x32 non-overlapping patches from the input and then concatenate them on a new axis. The reason I am using a time-distributed layer is that at the end, the discriminator should evaluate the whole image as true or fake. Thus, I am trying to perform a forward pass on each patch individually and then averaging the discriminator output across the patches by the lambda layer: def my_average(x): x = K.mean(x, axis=1) return x def my_average_shape(input_shape): shape = list(input_shape) del shape[1] return tuple(shape) def defineD(input_shape): a = Input(shape=(256, 256, 1)) cropping_list = [] n_patches = 256/32 for x in range(256/32): for y in range(256/32): cropping_list += [ K.expand_dims( Cropping2D((( x * 32, 256 - (x+1) * 32), ( y * 32, 256 - (y+1) * 32)))(a) , axis=1) ] x = Concatenate(1)(cropping_list) x = TimeDistributed(Conv2D(4 * 8, 3, padding='same'))(x) # x = TimeDistributed(MaxPooling2D())(x) x = TimeDistributed(LeakyReLU())(x) # 16 x = TimeDistributed(Conv2D(4 * 16, 3, padding='same'))(x) x = TimeDistributed(MaxPooling2D())(x) x = TimeDistributed(LeakyReLU())(x) # 8 x = TimeDistributed(Conv2D(4 * 32, 3, padding='same'))(x) x = TimeDistributed(MaxPooling2D())(x) x = TimeDistributed(LeakyReLU())(x) # 4 x = TimeDistributed(Flatten())(x) x = TimeDistributed(Dense(2, activation='sigmoid'))(x) x = Lambda(my_average, my_average_shape)(x) return keras.models.Model(inputs=a, outputs=x) For some reason I get the following error: File "testing.py", line 41, in &lt;module&gt; defineD((256,256,1) ) File "testing.py", line 38, in defineD return keras.models.Model(inputs=a, outputs=x) File "/usr/local/lib/python2.7/dist-packages/keras/legacy/interfaces.py", line 91, in wrapper return func(*args, **kwargs) File "/usr/local/lib/python2.7/dist-packages/keras/engine/network.py", line 93, in __init__ self._init_graph_network(*args, **kwargs) File "/usr/local/lib/python2.7/dist-package…

http://stackoverflow.com/comment/90995655
score: 1
type: Comment
has text: Thanks, I'm still working on seeing the functions of different things in programming clear xD I tend to overcomplicate things much too often without considering a simple answer.
type: AnswerComment
comment on: http://stackoverflow.com/a/52022667

http://stackoverflow.com/comment/90896808
comment on: http://stackoverflow.com/q/51973067
type: Comment
type: QuestionComment
has text: @downvoter care to comment?
score: 0

http://stackoverflow.com/q/52099985
tagged with: python
type: AnsweredQuestion
upvote count: 0
has comment: http://stackoverflow.com/comment/91150833
favorite count: 0
type: Question
score: -2
has title: How to re.match or re.search numbers in Python
has body: I want to match exact double digit numbers after 1st decimal. So in string I don't have .12 but its still Matches. What mistake i am making here. import re str = "100.13.1" ##if(re.match("^100\.[6|7|8|9|10|11|12]", str)): if(re.search("^100\.[6|7|8|9|10|11|12]", str)): print("[Quit], Matches") else: print("[info], Not match")
accepted answer: http://stackoverflow.com/a/52100113
downvote count: 2
answer count: 1
has comment: http://stackoverflow.com/comment/91150642
has answer: http://stackoverflow.com/a/52100113

http://stackoverflow.com/comment/91091174
type: Comment
score: 8
has text: This code would be hard to use in production. If multiple users try it simultaneously, IntegrityError would be raised.
type: AnswerComment
comment on: http://stackoverflow.com/a/52070665

http://stackoverflow.com/q/52005164
has answer: http://stackoverflow.com/a/52005368
tagged with: countvectorizer
tagged with: python-3.x
has title: Issue with usages of `transform` vs. `fit_transform` in CountVectorizer
has comment: http://stackoverflow.com/comment/90959943
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/52005368
type: Question
has comment: http://stackoverflow.com/comment/90959926
tagged with: scikit-learn
has comment: http://stackoverflow.com/comment/90959989
score: 0
has body: I have successfully trained and tested a Logistic Regression model with CountVectorizer() as such: def train_model(classifier, feature_vector_train, label): # fit the training dataset on the classifier classifier.fit(feature_vector_train, label) return classifier def getPredictions (classifier, feature_vector_valid): # predict the labels on validation dataset predict = classifier.predict(feature_vector_valid) return metrics.accuracy_score(predict, valid_y) def createTrainingAndValidation(column): global train_x, valid_x, train_y, valid_y train_x, valid_x, train_y, valid_y = model_selection.train_test_split(finalDF[column], finalDF['DeedType1']) def createCountVectorizer(column): global xtrain_count, xvalid_count # create a count vectorizer object count_vect = CountVectorizer() count_vect.fit(finalDF[column]) # transform the training and validation data using count vectorizer object xtrain_count = count_vect.transform(train_x) xvalid_count = count_vect.transform(valid_x) createTrainingAndValidation('Test') createCountVectorizer('Test') classifier = train_model(linear_model.LogisticRegression(), xtrain_count, train_y, xvalid_count) predictions = getPredictions(classifier, xvalid_count) I was using a DataFrame called finalDF with all labelled text. Since this model is giving me 0.68 accuracy I was going to test it on a subset of the DataFrame with an unknown label. This was not included in the training and testing phase. I saved the trained model as bestClassifier. Now I got the subset of unknown text and tried to do the following: count_vect = CountVectorizer() count_vect.fit(unknownDf['Text']) text = unknownDf['Text'] xvalid_count = count_vect.transform(text) bestClassifier.predict(xvalid_count) finalDF has 800 rows while unknownDf has only 32 rows after what I do above.. How do I rectify this?
answer count: 1

http://stackoverflow.com/comment/91057813
score: 2
has text: It's unclear what you need. If you just pass all these as-is, then you're not missing anything later.
comment on: http://stackoverflow.com/q/52053792
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/90949801
type: QuestionComment
score: 0
has text: just print without `.text` attribute to see what it's like, then decide
comment on: http://stackoverflow.com/q/52000326
type: Comment

http://stackoverflow.com/q/52102318
score: 1
has body: According to the following table and the code which I constructed as an example, I require a proper code &amp; table from which we can obtain the values of the 'Quantity' &amp; 'Rate'(price) to be displayed as 'Subtotal' (Subtotal = Quantity * Rate). Its little bit confusing to understand the exact logic here. here my code is given bellow: from PyQt4 import QtGui, QtCore import sys class Example(QtGui.QWidget): def __init__(self): super(Example, self).__init__() self.initUI() def initUI(self): self. table = QtGui.QTableWidget(self) self.table.move(10,70) self.table.resize(500,300) self.table_item = QtGui.QTableWidgetItem() self.table.setRowCount(3) self.table.verticalHeader().hide() self.table.setColumnCount(6) self.table.setEditTriggers(QtGui.QAbstractItemView.NoEditTriggers) self.fnt = self.table.font() self.fnt.setPointSize(11) self.table.setFont(self.fnt) self.table.setHorizontalHeaderLabels(("S.no, Item Description,Qty,Rate(Rs:),Subtotal,"",").split(',')) self.table.setItem(0,0,QtGui.QTableWidgetItem("1")) self.table.setItem(0,1, QtGui.QTableWidgetItem("Acne-aid Wash Facial Cleansing")) self.table.setItem(0,3,QtGui.QTableWidgetItem("191.72")) self.table.setItem(0,5,QtGui.QTableWidgetItem("")) self.table.setItem(1,1,QtGui.QTableWidgetItem("Moisturizer")) self.table.setItem(1,3,QtGui.QTableWidgetItem("90")) self.table.setItem(1,5,QtGui.QTableWidgetItem("")) self.table.setItem(1,0,QtGui.QTableWidgetItem("2")) self.table.setItem(2,0,QtGui.QTableWidgetItem("3")) self.table.setItem(2,1,QtGui.QTableWidgetItem("Brightening eye cream")) self.table.setItem(2,3,QtGui.QTableWidgetItem("40")) self.table.setItem(2,5,QtGui.QTableWidgetItem("")) for x in range(0,4): self.spin = QtGui.QSpinBox() self.spin.setMinimum(1) self.spin.setMaximum(50) self.table.setCellWidget(x,2,self.spin) for x in range(0,4): self.btn = QtGui.QPushButton(self) self.btn.setIcon(QtGui.QIcon("trash1.png")) self.table.setCellWidget(x,5,self.btn) self.setWindowTitle("To do app") self.setGeometry(200,300,6…
type: Question
tagged with: pyqt4
has title: how to get the subtotal amount i.e according to user given in quantity spinbox of qtable widget in pyqt4?
tagged with: pyqt
upvote count: 1
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/52102807
accepted answer: http://stackoverflow.com/a/52102807
tagged with: python
type: AnsweredQuestion
downvote count: 0

http://stackoverflow.com/q/52035666
score: 2
has comment: http://stackoverflow.com/comment/91023613
favorite count: 0
upvote count: 2
tagged with: django
tagged with: html-email
tagged with: python
has answer: http://stackoverflow.com/a/52036300
answer count: 1
has title: Email encoding using Django
has body: My webapp stores Hebrew text in a Postgres DB and later sends it as an email. I can see that the text is stored well in the DB, but when sent as an email it look like gibberish: ×¢×•×‘×“ ×™×§×¨, ×–×”×• ×˜×¡×˜ ×©×œ ×”×”×ª×¨××•×ª ×”× ×©×œ×—×•×ª ×‘×¢×‘×¨×™×ª. I'm using urlllib to unquote the text from the DB urllib.unquote(text) and EmailSender to send the email: EmailSender().send_html( "my email subject", email_content, [email], headers=headers, fail_silently=True ) What can be causing that?
has comment: http://stackoverflow.com/comment/91024080
tagged with: encoding
downvote count: 0
type: UnansweredQuestion
type: Question

http://stackoverflow.com/comment/90939077
has text: If you can just use a `dbm` or `shelve`, this is trivial—just do that. If your keys aren't strings, or your values are huge or non-picklable objects, then you can't. In which case, this is basically a dup of the question @ScottMermelstein linked above, or at any rate you can use the answer from that question.
type: Comment
score: 2
comment on: http://stackoverflow.com/q/51994575
type: QuestionComment

http://stackoverflow.com/a/52009662
type: Answer
has body: Why not just remake the command using the arguments you parsed? It won't be exactly what you typed, but that might be nice as it will be in a common format. Ex (assuming the learning rate and batch size are stored in similarly named variables): command = "python3 main.py --learning-rate {} --batch-size {}".format(learning_rate, batch_size) Of course it will be a little more complicated if some commands are optional, but I assume in that case there would be a default value for these parameters, since your network would need those parameters every time.
answers question: http://stackoverflow.com/q/52009570
score: 0
has comment: http://stackoverflow.com/comment/90978236

http://stackoverflow.com/q/52067834
has answer: http://stackoverflow.com/a/66806822
type: Question
has comment: http://stackoverflow.com/comment/91085869
tagged with: python-2.7
upvote count: 3
answer count: 3
tagged with: pyjnius
has answer: http://stackoverflow.com/a/53888462
has body: I tried to install jnius Python module by typing 'pip install jnius' in CMD. This is the message I got: Complete output from command python setup.py egg_info: Traceback (most recent call last): File "&lt;string&gt;", line 1, in &lt;module&gt; File "c:\users\sm\appdata\local\temp\pip-install-vu2sb5\jnius\setup.py", line 111, in &lt;module&gt; raise Exception('Unable to determine JDK_HOME') Exception: Unable to determine JDK_HOME ---------------------------------------- Command "python setup.py egg_info" failed with error code 1 in c:\users\sm\appdata\local\temp\pip-install-vu2sb5\jnius\ I restarted CMD, but it didn't help.
favorite count: 0
has answer: http://stackoverflow.com/a/52076881
type: UnansweredQuestion
tagged with: python
has title: Jnius installation bug, "Unable to determine JDK_HOME"
score: 3
downvote count: 0

http://stackoverflow.com/a/51973160
has body: You have to calculate the difference between each element in aa and bb, and take the minimum: aa_nearest = bb[abs(aa[None, :] - bb[:, None]).argmin(axis=0)]
has comment: http://stackoverflow.com/comment/90898642
has comment: http://stackoverflow.com/comment/90905349
accepted answer of: http://stackoverflow.com/q/51972924
has comment: http://stackoverflow.com/comment/90897493
upvote count: 5
score: 5
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/90897317
has comment: http://stackoverflow.com/comment/90898500
answers question: http://stackoverflow.com/q/51972924
type: Answer

http://stackoverflow.com/comment/90971340
comment on: http://stackoverflow.com/q/51994563
type: Comment
score: 0
type: QuestionComment
has text: The threshold was there before I started removing outliers, and isn't the third quartile at around 0.05 whereas the threshold is above 0.25?

http://stackoverflow.com/a/52051697
score: 0
has body: here's my example a1 = [] a2 = [] a3 = [1,2,3] fa = [a1,a2,a3] print(len(fa[2])) also, check this out for referencing: Access item in a list of lists
answers question: http://stackoverflow.com/q/52051667
type: Answer

http://stackoverflow.com/comment/90917389
type: Comment
comment on: http://stackoverflow.com/q/51983870
score: 0
type: QuestionComment
has text: @SandeepKadapa no, they should be the same

http://stackoverflow.com/q/52006449
has answer: http://stackoverflow.com/a/52022276
tagged with: python
has body: I am playing with the python library mpmath, in particular evaluating the incomplete gamma function. This is part of a root finding routine but its evaluation is extremely slow for some combinations of complex-valued arguments. import mpmath as mp from mpmath import gammainc def Gamma(a,z0,z1): return gammainc(a,a=z0,b=z1,regularized=False) Here the evaluation of the mpmath.gammainc function gets stuck: &gt;&gt; Gamma(mp.mpc(12.5+17.5j), mp.mpf(0.0), mp.mpf(-12.5)) On the other hand, Mathematica returns me the result almost instantly: In[1]:= Gamma[12.5 + 17.5 I, 0, -12.5] Out[1]:= 2.38012*10^-7 + 5.54827*10^-7 I In other cases, for different arguments mpmath and Mathematica return the same output: Mathematica In[2]: Gamma[3.5 I, 0, 10] Out[2]:= 0.0054741 + 0.000409846 I Python mpmath &gt;&gt; Gamma(3.5j,0,10) mpc(real='0.0054741038497352953', imag='0.00040984640431357779') Do you have some idea of the reason of this behaviour? Can this be considered a problem of mpmath or is this a mathematical problem of quadrature? Unfortunately scipy does not offer an implementation of gamma functions for complex arguments, so it not an option.
upvote count: 4
type: UnansweredQuestion
has title: Difficulties in evaluating mpmath gammainc function
tagged with: gamma-function
downvote count: 0
type: Question
answer count: 1
score: 4
tagged with: numerical-integration
favorite count: 0
tagged with: mpmath

http://stackoverflow.com/comment/90964417
has text: I did the same thing with idxmin & idexmax for max and mins. But can't figure out a way to do average.
type: QuestionComment
comment on: http://stackoverflow.com/q/52007139
score: 0
type: Comment

http://stackoverflow.com/q/52106616
tagged with: python
tagged with: internationalization
has comment: http://stackoverflow.com/comment/91164165
possible better answer: http://stackoverflow.com/a/52106812
score: 0
has answer: http://stackoverflow.com/a/52106812
accepted answer: http://stackoverflow.com/a/52106960
has comment: http://stackoverflow.com/comment/91164373
has comment: http://stackoverflow.com/comment/91164173
tagged with: python-2.7
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91164276
has comment: http://stackoverflow.com/comment/91164142
has comment: http://stackoverflow.com/comment/91164120
tagged with: unicode
has answer: http://stackoverflow.com/a/52106960
type: Question
tagged with: timezone
has body: I have a colleague whose computer won't run a Python script that uses the dateutil.tz module; there is a timezone name '\xc3\xc0\xb9\xfa\xc9\xbd\xb5\xd8\xb1\xea\xd7\xbc\xca\xb1\xbc\xe4' that shows up and in dateutil.tz there is this code: def tzname_in_python2(namefunc): """Change unicode output into bytestrings in Python 2 tzname() API changed in Python 3. It used to return bytes, but was changed to unicode strings """ def adjust_encoding(*args, **kwargs): name = namefunc(*args, **kwargs) if name is not None and not PY3: name = name.encode() return name return adjust_encoding which breaks because the string in question is not ASCII. What is this string? It doesn't look like valid Unicode: &gt;&gt;&gt; a = '\xc3\xc0\xb9\xfa\xc9\xbd\xb5\xd8\xb1\xea\xd7\xbc\xca\xb1\xbc\xe4' &gt;&gt;&gt; a.decode('utf8') Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "c:\app\python\anaconda\2\envs\emblaze\lib\encodings\utf_8.py", line 16, in decode return codecs.utf_8_decode(input, errors, True) UnicodeDecodeError: 'utf8' codec can't decode byte 0xc3 in position 0: invalid continuation byte My python script contains timezone = dateutil.tz.tzlocal() and the resulting object fails to run timezone.tzname(some_timestamp) because of the non-ASCII nature of the timezone name.
has title: What is the timezone name '\xc3\xc0\xb9\xfa\xc9\xbd\xb5\xd8\xb1\xea\xd7\xbc\xca\xb1\xbc\xe4'?
answer count: 2

http://stackoverflow.com/q/51981121
tagged with: python
has comment: http://stackoverflow.com/comment/90912422
has comment: http://stackoverflow.com/comment/90912139
has body: I am attempting to parse small amounts of data from a large XML file (2G). For small files I would just use root_node.xpath('/the/specific/path/i/am/interested/in') but I have read that this is very memory consuming. For large files, this reference suggests the methods of implementing a target parser or using etree.iterparse. Although less memory consuming, these methods still iterate over the whole tree. Can lxml also be used to skip iterating through all irrelevant branches, i.e. avoiding the parser to enter them? For example when I have <irrelevant_to_me> 3000 lines, do not enter! </irrelevant_to_me> <irrelevant_to_me> 3000 lines, do not enter! </irrelevant_to_me> <irrelevant_to_me> 3000 lines, do not enter! </irrelevant_to_me> <irrelevant_to_me> 3000 lines, do not enter! </irrelevant_to_me> <irrelevant_to_me> 3000 lines, do not enter! </irrelevant_to_me> <irrelevant_to_me> 3000 lines, do not enter! </irrelevant_to_me> The parser should not even enter the <irrelevant_to_me>-Nodes (regardless of their name).
type: Question
has title: Is there a way in `lxml` to skip irrelevant branches when parsing
score: 0
tagged with: lxml
tagged with: parsing
tagged with: http://stackoverflow.com/tag/xml
answer count: 0
type: UnansweredQuestion

http://stackoverflow.com/comment/90968234
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/51992539
has text: Everything is looking ok there. One thing to note is that the callback function names are important, so your verbose one will not get called. Do you get any audio data in test.wav?

exception
tags question: http://stackoverflow.com/q/51996087
tags question: http://stackoverflow.com/q/52081929
tags question: http://stackoverflow.com/q/52108083
tags question: http://stackoverflow.com/q/51979432
tags question: http://stackoverflow.com/q/52085846
type: Tag
tags question: http://stackoverflow.com/q/51990413
tags question: http://stackoverflow.com/q/52067668
tags question: http://stackoverflow.com/q/51980564
tags question: http://stackoverflow.com/q/52101595
tags question: http://stackoverflow.com/q/52085506
tags question: http://stackoverflow.com/q/52058944
tags question: http://stackoverflow.com/q/52107781
tag name: exception
tags question: http://stackoverflow.com/q/51994464
tags question: http://stackoverflow.com/q/52039799
tags question: http://stackoverflow.com/q/52096592

http://stackoverflow.com/comment/91166602
comment on: http://stackoverflow.com/a/52107882
type: Comment
score: 1
has text: That code looks correct. What are the content of `global_dict` and `dict_2014` in your actual run? Which keys in `dict_2014` did not show up in `global_dict` after you run this code?
type: AnswerComment

http://stackoverflow.com/q/52057984
possible better answer: http://stackoverflow.com/a/53894286
has body: I want to find these three Prestige measures for an existing graph using python: Degree Prestige Proximity Prestige Rank Prestige Can I use networkx for this purpose? If not, then which library can I use and how can I do it. Any links or references are appreciated.
tagged with: python
has answer: http://stackoverflow.com/a/52067088
has title: Degree, Proximity and Rank Prestige
tagged with: networkx
type: AnsweredQuestion
tagged with: web-mining
has answer: http://stackoverflow.com/a/53894286
accepted answer: http://stackoverflow.com/a/52067088
type: Question
score: 0
answer count: 2

http://stackoverflow.com/q/51976204
type: Question
has title: Pandas dataframe, merge by intersection of spans?
has body: I would like to merge two dataframes based on overlap of spans (indicated by pairs (s,e), s- start of span, e - end of span), and while I have a pretty bad code for doing it, I would like to know if there is a good way to implement it. Here is example: df1 = pd.DataFrame({'s':[0,10,20,33,424,5345], 'e':[3,17,30,39,1000,10987], 'data1':[1,2,3,4,5,6]}) df2 = pd.DataFrame({'s':[1,45,0], 'e':[50,46,90], 'data2':[1,2,3]}) def overlap(a1,a2,b1,b2): if type(b1) == list or type(b1)==np.ndarray: assert(len(b1)==len(b2)) return np.asarray([overlap(a1,a2,b1[k],b2[k]) for k in range(len(b1))]) else: return max((a2-a1)+(b2-b1)+min(a1,b1)-max(b2,a2)+1,0) overlaps = [overlap(df1['s'].iloc[i],df1['e'].iloc[i],df2['s'].values,df2['e'].values)&gt;0 for i in range(len(df1))] df1['data2']=[df2['data2'][o].tolist() for o in overlaps] Output is: s e data1 data2 0 0 3 1 [1, 3] 1 10 17 2 [1, 3] 2 20 30 3 [1, 3] 3 33 39 4 [1, 3] 4 424 1000 5 [] 5 5345 10987 6 [] Edit: also, in my particular case I am guaranteed that for df1 spans are non-overlapping and sequential (ie s[i]>s[i-1], e[i]>s[i], e[i] &lt; s[i+1] ) Edit2: you can generate arbitrary amount of almost valid fake data (here we don't have guarantees on non-overlapping of spans in first df): N=int(1e3) sdf1=np.random.randint(0, high=10*N, size=(N,)) sdf1.sort() edf1=sdf1+np.random.randint(1, high=10, size=(N,)) data1=range(N) sdf2=np.random.randint(0, high=10*N, size=(N,)) edf2=sdf2+np.random.randint(1, high=10, size=(N,)) data2=range(N) df1 = pd.DataFrame({'s':sdf1, 'e':edf1, 'data1':data1}) df2 = pd.DataFrame({'s':sdf2, 'e':edf2, 'data2':data2})
has comment: http://stackoverflow.com/comment/90903172
score: 0
tagged with: pandas
answer count: 1
has comment: http://stackoverflow.com/comment/90903070
type: UnansweredQuestion
tagged with: python
tagged with: merge
has answer: http://stackoverflow.com/a/51977555

http://stackoverflow.com/comment/91041490
type: Comment
has text: Here are some non-stride_trcks solutions. https://stackoverflow.com/a/4947453/2823755, https://stackoverflow.com/a/42258242/2823755, https://stackoverflow.com/a/10906015/2823755
score: 0
comment on: http://stackoverflow.com/q/52044113
type: QuestionComment

http://stackoverflow.com/a/52117339
answers question: http://stackoverflow.com/q/52105543
has comment: http://stackoverflow.com/comment/137661639
has body: You approach of defining the circle in PlateCarree coordinates is not going to work, because this is a cartesian projection and a circle drawn on it is not necessarily circular in spherical geometry (unless the circle is at (0, 0) as you saw). Since you want the result to be circular in the Orthographic projection, you could draw the circle in native coordinates. This requires first defining your Orthographic projection centred on the centre of your circle, then computing what the radius of the circle (which you specify in degrees) would be in projection coordinates (distance from the centre of the projection). Doing it this way is convenient because it also gives you a neat way of determining the correct map extents. The example below computes the radius in orthographic coordinates by transforming a point 45 degrees north (or south if more convenient) away from the centre of the projection and gives the following: The full code is below: import numpy as np import cartopy.crs as ccrs import cartopy.feature as cfeature import matplotlib.pyplot as plt import matplotlib.patches as mpatches # example: draw circle with 45 degree radius around the North pole lat = 51.4198101 lon = -0.950854653584 r = 45 # Define the projection used to display the circle: proj = ccrs.Orthographic(central_longitude=lon, central_latitude=lat) def compute_radius(ortho, radius_degrees): phi1 = lat + radius_degrees if lat &lt;= 0 else lat - radius_degrees _, y1 = ortho.transform_point(lon, phi1, ccrs.PlateCarree()) return abs(y1) # Compute the required radius in projection native coordinates: r_ortho = compute_radius(proj, r) # We can now compute the correct plot extents to have padding in degrees: pad_radius = compute_radius(proj, r + 5) # define image properties width = 800 height = 800 dpi = 96 resolution = '50m' # create figure fig = plt.figure(figsize=(width / dpi, height / dpi), dpi=dpi) ax = fig.add_subplot(1, 1, 1, projection=proj) # Deliberately avoiding set_extent because it has some …
accepted answer of: http://stackoverflow.com/q/52105543
type: AcceptedAnswer
downvote count: 0
type: Answer
score: 11
has comment: http://stackoverflow.com/comment/100518339
has comment: http://stackoverflow.com/comment/100517647
upvote count: 11
has comment: http://stackoverflow.com/comment/91189689

http://stackoverflow.com/comment/90985006
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52017434
has text: That's a different question, and the answer is "because `os.mkdir` doesn't create the parent folders of the directory". You asked python to create `InputData/hc`. If no `InputData` folder exists, it can't do that.
score: 0

http://stackoverflow.com/comment/91141273
comment on: http://stackoverflow.com/q/52095337
has text: @DavidG: I wouldn't call it duplicate but similar.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52009202
has answer: http://stackoverflow.com/a/52009658
has title: Python Pandas compare values in multiple columns for partial duplicates and drop record
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/90969264
has comment: http://stackoverflow.com/comment/90969242
has answer: http://stackoverflow.com/a/52009471
has body: I need to create a function/expression that compares multiple columns ('Cust ID Count', 'Revenue' and possibly 'Family Name' for a record match and then keeps only the first record based on ascending order. Also, this function will be looking at 2 different scenarios where there are multiple similar records: Multiple records will match across all columns/series with the exception of 'street' (records 0 &amp; 1) Multiple records will match across all columns/series with the exception of 'street' and 'Family Name' (records 3 &amp; 4) I realize it looks like we can only use Cust ID count and Revenue as the matching parameters, but I would also like to use 'family name' as an option if possible. Dataset: idx Cust ID Count Family Name street Revenue 0 10 Smith spring 50 #match 1 10 Smith wilbur 50 #match 2 45 Jerry jane 35 #not a match 3 25 Cole mary 20 #match 4 25 Stein mary sue 20 #match Output: idx Cust ID Count Family Name street Revenue 0 10 Smith spring 50 #spring is kept due to alphabetical order 1 45 Jerry jane 35 #not a match 2 25 Cole mary 20 #mary is kept due to alphabetical order
tagged with: pandas
tagged with: python
score: 0
type: UnansweredQuestion

http://stackoverflow.com/q/52009543
tagged with: nose
has comment: http://stackoverflow.com/comment/90970255
score: 0
tagged with: import
has comment: http://stackoverflow.com/comment/90970403
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90970001
has comment: http://stackoverflow.com/comment/90969913
has title: How to import all functions from subdirectory into the main environment through the __init__.py file?
has body: I have a the following directory structure: mymodulename | mymodulename | mymodulename | __init__.py | mymodulename | io | io.py | mymodulename | io | __init__.py | mymodulename | io | data_type | tables.py In the following file, I was successfully able to do: | mymodulename | io | __init__.py from .data_type.tables import * and can now call like this: mymodulename.io.some_function However, I can't seem to do the following in | mymodulename | __init__.py from .io import * It works, when I start python and do mymodulename.some_function but it doesn't work when I run nosetests I get the following error: ModuleNotFoundError: No module named 'mymodulename.io'
has comment: http://stackoverflow.com/comment/90970218
answer count: 0
type: Question
tagged with: python
tagged with: module

http://stackoverflow.com/a/52003579
downvote count: 0
has comment: http://stackoverflow.com/comment/90957325
has comment: http://stackoverflow.com/comment/90957395
answers question: http://stackoverflow.com/q/52002905
type: Answer
upvote count: 1
has comment: http://stackoverflow.com/comment/90956594
score: 1
has comment: http://stackoverflow.com/comment/90968368
has comment: http://stackoverflow.com/comment/90957645
has comment: http://stackoverflow.com/comment/90958155
has body: First the mistake lies in the color parameter. It is hue parameter that do what you wanted. Check the code below: #For sorting the values in descending order df.sort_values('value',inplace=True,ascending=False) fig,ax = plt.subplots() fig.set_size_inches(16,8) #to get different colors for each of the variable assign the variable to hue g=sns.barplot(x='token',y='value',data=df, hue='variable',ax=ax) #Code for to put legend outside the plot box = ax.get_position() ax.set_position([box.x0, box.y0, box.width * 0.8, box.height]) # Put a legend to the right of the current axis ax.legend(loc='center left', bbox_to_anchor=(1, 0.5)) # Adding respective values to the top of each bar for p in ax.patches: ax.annotate("%d" % p.get_height(), (p.get_x() + p.get_width() / 2, p.get_height()), ha='center', va='center', fontsize=11, color='black', xytext=(0, 10), textcoords='offset points',fontweight='bold') #To save the plot as 'SO.png' plt.savefig('SO.png',dpi=100,bbox_inches='tight') plt.show() Code for legend is from link. The plot looks like:

http://stackoverflow.com/a/52007730
has comment: http://stackoverflow.com/comment/90966722
downvote count: 0
has comment: http://stackoverflow.com/comment/90967427
answers question: http://stackoverflow.com/q/52007577
type: AcceptedAnswer
has body: Just replace ax.legend(loc='left', bbox_to_anchor=(1, 0)) by ax.legend(loc=(1.05, 0.2)) You can modify the positions (1.05, 0.2) as per your desired location. The values here are in fractions.
has comment: http://stackoverflow.com/comment/90966234
upvote count: 2
type: Answer
accepted answer of: http://stackoverflow.com/q/52007577
score: 2
has comment: http://stackoverflow.com/comment/90965989
has comment: http://stackoverflow.com/comment/90966176
has comment: http://stackoverflow.com/comment/90966573

http://stackoverflow.com/comment/91077045
comment on: http://stackoverflow.com/q/52062162
type: Comment
type: QuestionComment
has text: It sounds like your question might actually be a duplicate of this: [Display three dots in the end of a Tkinter Label text](https://stackoverflow.com/q/51143777/7432)
score: 1

http://stackoverflow.com/q/51966824
has comment: http://stackoverflow.com/comment/90883744
accepted answer: http://stackoverflow.com/a/51966924
has comment: http://stackoverflow.com/comment/90883709
linked to: http://stackoverflow.com/q/28977618
has comment: http://stackoverflow.com/comment/90883771
has title: How to remove double quotes(") in csv file with Python?
tagged with: http://stackoverflow.com/tag/csv
has comment: http://stackoverflow.com/comment/90883907
has comment: http://stackoverflow.com/comment/90883791
tagged with: opencsv
favorite count: 0
possible better answer: http://stackoverflow.com/a/51971684
tagged with: python-3.x
has answer: http://stackoverflow.com/a/51971684
has comment: http://stackoverflow.com/comment/90884124
upvote count: 2
has body: My input in csv file is like below: ￼ “No” “ename” age “gender” “salary” 1 “aaa” 23 f 1000 2 “bbb” 24 m 2000 3 “ccc” 25 “f” 3000 4 “ddd” 35 m 4000￼ 5 “eee” 27 f 5000￼ Below code is written to remove quotes given in .csv file. import csv csv.register_dialect('myDialect', delimiter=',', doublequote=False, quoting=csv.QUOTE_NONE, skipinitialspace='True') f = open("pythonFiles/normal.csv", 'r') normal = csv.reader(f, dialect='myDialect') for data in normal: print(data, len(data)) The output is shown below. I want to remove all of the quotes. ['“No”', '“ename”', 'age', '“gender”', '“salary”'] ['1', '“aaa”', '23', 'f', '1000'] ['2', '“bbb”', '24', 'm', '2000'] ['3', '“ccc”', '25', '“f”', '3000'] ['4', '“ddd”', '35', 'm', '4000'] ['5', '“eee”', '27', 'f', '5000']
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51966924
score: 1
has comment: http://stackoverflow.com/comment/90883538
has comment: http://stackoverflow.com/comment/90884212
has comment: http://stackoverflow.com/comment/90883877
downvote count: 1
has comment: http://stackoverflow.com/comment/90883741
type: Question
answer count: 2

package.json
tag name: package.json
tags question: http://stackoverflow.com/q/52071852
type: Tag

http://stackoverflow.com/a/52034743
score: 1
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/52003436
has body: The solution was achieved by using a uniform as user BDL suggested in his comment. It is also possible to set attributes of vertices, as suggested here: http://www.labri.fr/perso/nrougier/python-opengl/
type: Answer
upvote count: 1
accepted answer of: http://stackoverflow.com/q/52003436

http://stackoverflow.com/q/52046579
accepted answer: http://stackoverflow.com/a/52049784
answer count: 1
tagged with: firebase
tagged with: firebase-authentication
tagged with: firebase-admin
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52049784
type: Question
has body: We're using Firebase for our user authentication. I can log a user in on the client side and then run the following from a python app: import firebase_admin import firebase_admin.auth from firebase_admin import credentials from datetime import datetime cred = credentials.Certificate('my_creds.json') app = firebase_admin.initialize_app(cred) firebase_admin.auth.revoke_refresh_tokens('some-user-id', app=app) u = firebase_admin.auth.get_user('some-user-id') print(datetime.fromtimestamp(u.tokens_valid_after_timestamp / 1000)) Which displays the current timestamp, and at least as far as I understand the managing user sessions documentation, it should be revoking the tokens. Which I thought should make it so any further operations I do on the client side would fail. This, however, is not true. I can pop open the console where 'some-user-id' has been logged in and run: firebase.database().ref('some/key').once('value').then(function(snap){ console.log(snap.val()); }); And after a moment, I will observe the value of some/key just fine. This is not fine. When I run firebase.auth().currentUser.reload() then it will actually disconnect my session and I won't be able to get that value any more. But I want to do something on the server side to make it so every subsequent request from the client will fail with an authentication problem. Is this possible? And if so, how can I do that?
tagged with: python
has title: (How) can you log a user out of firebase?
score: 0

http://stackoverflow.com/comment/91159364
comment on: http://stackoverflow.com/q/52049346
type: QuestionComment
type: Comment
has text: I'm using the Spyder environment which I believe uses the IPython console. Thanks for the tip. I'll see if I can work around that.
score: 0

http://stackoverflow.com/comment/90866556
score: 1
has text: The question reads: "I don't want to alter the data version of the data frame because it is the raw data."
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51958017

http://stackoverflow.com/comment/90866765
score: 2
has text: could your provide more details and a code sample of what you currently have?
comment on: http://stackoverflow.com/q/51958143
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52023312
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/52023619
type: AnsweredQuestion
has title: Appending list to pandas column
has body: I need to append the list idlist to the column in my table called EventID. The list needs to be appended in order, since I grabbed the ID's in order from the original HTML file. Right now my output looks like this: EventID EventDate EventName AmntTickets PriceRange 0 103577924 Thu, 10/11/2018 8:20 p.m. Philadelphia Eagles at New York Giants MetLif... 6655 $134.50 to $2,222.50 1 103577924 Thu, 10/11/2018 8:21 p.m. PARKING PASSES ONLY Philadelphia Eagles at New... 929 $20.39 to $3,602.50 EventID EventDate EventName AmntTickets PriceRange 0 103577925 Thu, 10/11/2018 8:20 p.m. Philadelphia Eagles at New York Giants MetLif... 6655 $134.50 to $2,222.50 1 103577925 Thu, 10/11/2018 8:21 p.m. PARKING PASSES ONLY Philadelphia Eagles at New... 929 $20.39 to $3,602.50 I need it to look like this: EventID EventDate EventName AmntTickets PriceRange 0 103577924 Thu, 10/11/2018 8:20 p.m. Philadelphia Eagles at New York Giants MetLif... 6655 $134.50 to $2,222.50 1 103577925 Thu, 10/11/2018 8:21 p.m. PARKING PASSES ONLY Philadelphia Eagles at New... 929 $20.39 to $3,602.50 My code: import pandas as pd from bs4 import BeautifulSoup import requests import lxml.html as lh import pprint import re with open("htmltabletest.html", encoding="utf-8") as f: data = f.read() soup = BeautifulSoup(data, 'lxml') pd.set_option('display.max_rows', 500) pd.set_option('display.max_columns', 500) pd.set_option('display.width', 1000) dfs = pd.read_html(soup.prettify()) df = dfs[0] dfz=df.rename(columns = {'Event date Time (local)':'EventDate'}).rename(columns = {'Event name Venue':'EventName'}).rename(columns = {'Tickets listed':'AmntTickets'}).rename(columns = {'Price range':'PriceRange'}).rename(columns = {'Unnamed: 0':'EventID'}) idlist = [] for se in soup.find_all('span', id=re.compile(r'min')): se = (str(se)) seeme1 = se.replace('<span id="se-','') seeme, sep, tail = seeme1.partition('-') idlist.append(seeme) for p in idlist: dfz = dfz.assign(EventID=p) print(dfz) my html file (htmltabletest.html): …
type: Question
score: 0
answer count: 1
has answer: http://stackoverflow.com/a/52023619
tagged with: beautifulsoup
tagged with: pandas
tagged with: python

http://stackoverflow.com/q/52083160
upvote count: 2
has body: Maybe it is not an appropriate title but let me explain my problem. Following is my dataframe: company manager_1 manager_2 manager_3 manager_4 manager_5 manager_6 _manager_7 Ford AB AC AD AE AF AG AH BMW BA BC BD BE BF FIAT CA CB CD CE CF CG Mercedes BC GA GB I need to convert these different columns into a single one and based on the order I want to create a additional column. What I need is basically this (I don't care about company names as it is just a toy example) name order AB 7 AC 6 AD 5 AE 4 AF 3 AG 2 AH 1 BA 5 BC 4 BD 3 BE 2 BF 1 Actually, the manager_7 is the first manager of the company, so it takes to number 1 e.g. for AH, corresponding number is 1. I tried to transpose the columns, but couldn't get the output that I want. Any help?
answer count: 2
favorite count: 0
tagged with: pandas
has answer: http://stackoverflow.com/a/52083964
tagged with: python
score: 2
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/52083309
downvote count: 0
has title: Pandas calculating order based on columns
type: Question
has answer: http://stackoverflow.com/a/52083309
possible better answer: http://stackoverflow.com/a/52083964
has comment: http://stackoverflow.com/comment/91116760

http://stackoverflow.com/comment/90965191
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/52007401
has text: @PatrickHaugh that's not the issue, `i` is all numbers between the first and last prime. The bigger problem is that `num += 2` is executed no matter what on each iteration
score: 0

http://stackoverflow.com/q/52110144
has body: I am trying to extend the calendar module to color days according to a passed pd.Series, whose index is the dates and whose value is a color code (0 to 10). I'm not deep enough into OOP to do this. The TextCalendar class has a method formatyear, which in turn calls a method formatweek. My current solution is to define a class ColoredTextCalendar(TextCalendar) whose __init__() sets a class property date_to_color (a pandas Series of color codes, with the date as index). I then basically copy-and-pasted the original formatyear and formatweek methods, and changed only two or three lines in them: formatyear now calls formatweek with additional parameters year and month, so that this method knows what actual date it is formatting (previously it just printed a 7-day calendar week like 12 13 14 15 16 17 18). And formatweek now looks up the corresponding color code in its class property date_to_color and colors each day's string accordingly. What I'm doing kind of works, but it feels wrong, like there should be a simpler, more straightforward solution. Copy-and-pasting a long method and changing only a few lines feels wrong - that's not how you usually do OOP, right?
favorite count: 0
has title: How to override methods in Python to pass additional arguments?
type: UnansweredQuestion
upvote count: 1
has comment: http://stackoverflow.com/comment/91172509
tagged with: oop
score: 1
tagged with: overriding
has comment: http://stackoverflow.com/comment/91173324
type: Question
has comment: http://stackoverflow.com/comment/91172628
has answer: http://stackoverflow.com/a/52111191
downvote count: 0
tagged with: class
has comment: http://stackoverflow.com/comment/91172450
answer count: 1
linked to: http://stackoverflow.com/q/3394835
has comment: http://stackoverflow.com/comment/91172407
tagged with: python

http://stackoverflow.com/a/51976897
has comment: http://stackoverflow.com/comment/90904022
has comment: http://stackoverflow.com/comment/90904066
has body: Let me ignore your second attempt for now, because the first one was a lot closer to working: def counter(self, func): def wrapper(): wrapper.counter += 1 return func(wrapper.counter) wrapper.counter = 0 return wrapper @counter def _populate_profile_dict(self, count): # ... The reason this doesn't work is that decorator syntax is trying to do this: _populate_profile_dict = counter(_populate_profile_dict) … but counter is defined to take two arguments, not one, self and a function. There's obviously no self here. In fact, even the class itself doesn't exist yet, much less any methods. You're calling it with just the function, so that's what it needs to take. And if you just remove that self parameter, the decorator part will work just fine: def counter(func): def wrapper(): wrapper.counter += 1 return func(wrapper.counter) wrapper.counter = 0 return wrapper Now, that counter is no longer useful as a method on instances of the class—but that's fine, since you never intend to use it that way. Meanwhile, it's perfectly useful as a normal function while the class is still being defined. And that's exactly the way you want to use it. It might be a bit confusing that counter ends up looking like a public method of Profile instances, even though it's not actually callable that way, which is pretty confusing. But you can solve that by either renaming it to _counter, or doing a del counter at the very end of the class definition. Anyway, the decorator part works, but there's a second problem: def wrapper(): This defines a function with no parameters. But you're trying to create something that can be called as a normal instance method, so it's going to be passed a self argument. You need to accept that self argument, and you also need to pass it on to the wrapped function. So: def counter(func): def wrapper(self): wrapper.counter += 1 return func(self, wrapper.counter) # etc. And now, everything works as (I think) you intended. While we're at it, this code is a bit weird: def …
has comment: http://stackoverflow.com/comment/90904345
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/51976665
downvote count: 0
has comment: http://stackoverflow.com/comment/90904188
type: Answer
accepted answer of: http://stackoverflow.com/q/51976665
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/90904100

http://stackoverflow.com/comment/90946840
type: Comment
score: 0
has text: I have dict , i want to append the values to the choice[1]
comment on: http://stackoverflow.com/a/51998621
type: AnswerComment

http://stackoverflow.com/comment/90918887
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51984223
score: 0
has text: That's the only difference I know, and from my perspective, its not necessarily an advantage

http://stackoverflow.com/q/51966528
has answer: http://stackoverflow.com/a/51966734
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51967089
possible better answer: http://stackoverflow.com/a/51966734
upvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/90883058
tagged with: indexing
has title: python: Add list elements based on original indexing (while updating list)
has body: I have a sequence like this: ABCDEFGHIJKL I would like to insert the strings: '-(c0)-' after elements 1 and 3 '-(c1)-' after elements 2 and 4 '-(c2)-' after elements 5 and 6 This is the kind of code I was writing: list_seq = list('ABCDEFGHIJKL') new_list_seq = list('ABCDEFGHIJKL') start_end = [(1,3), (2,4), (5,6)] for index,i in enumerate(start_end): pair_name = '-(c' + str(index) + ')-' start_index = int(i[0]) end_index = int(i[1]) new_list_seq.insert(start_index, pair_name) new_list_seq.insert(end_index, pair_name) print ''.join(new_list_seq) The output I would want is: AB-(c0)-C-(c1)-D-(c0)-E-(c1)-F-(c2)-G-(c2)-HIJKL (where c0 was inserted after 1 and 3 positions, c1 was inserted after 2 and 4, and c2 was inserted after 5 and 6). But the output I get is: A-(c0)--(c1)-B-(c1)--(c2)--(c2)--(c0)-CDEFGHIJKL I think possibly the problem is that as I incorporate an item into the string, the indices change, so then all subsequent inclusions after the first one are not in the right positions? Could anyone explain how to do this properly?
accepted answer: http://stackoverflow.com/a/51967089
answer count: 2
downvote count: 0
score: 1
favorite count: 0
tagged with: python

http://stackoverflow.com/comment/91020330
type: QuestionComment
type: Comment
has text: Could you please post the error as text instead of a screenshot?
comment on: http://stackoverflow.com/q/52035147
score: 0

http://stackoverflow.com/a/52065377
upvote count: 2
score: 2
downvote count: 0
answers question: http://stackoverflow.com/q/52065315
type: Answer
has body: You can set Month to be an ordered categorical of all the months of the year: months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'] df['Month'] = pd.Categorical(df['Month'], categories = months, ordered=True) Then, when you do your groupby, they will be ordered: &gt;&gt;&gt; df.groupby(["Month","Day"]).min() count Data_Value Month Day Jan 1 NaN NaN 4 NaN NaN 6 NaN NaN 7 NaN NaN 14 NaN NaN 15 NaN NaN 17 NaN NaN 18 NaN NaN 19 59.0 94.0 21 NaN NaN 22 NaN NaN 24 40.0 33.0 25 9.0 33.0 26 22.0 61.0 27 NaN NaN 28 NaN NaN 30 NaN NaN Feb 1 NaN NaN 4 NaN NaN 6 NaN NaN 7 NaN NaN 14 NaN NaN ..... It might be easier just to get your month abbreviations from the calendar module, though: import calendar months = [calendar.month_abbr[i] for i in range(1,13)] &gt;&gt;&gt; months ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']

http://stackoverflow.com/comment/90919726
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51984993
has text: `ham` is removed for `Badger` ?
score: 0

http://stackoverflow.com/comment/91141041
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52095347
has text: should i add the code to my full project? Because the code i just posted was just a example
score: 0

http://stackoverflow.com/comment/91044222
has text: Have you checked boto3?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52046518

http://stackoverflow.com/comment/91202549
type: Comment
comment on: http://stackoverflow.com/a/52123934
has text: Thank you for your answer. I already have Python3 (Python 3.6.3) installed and when I run it from command line I get some rectangles instead of the chinese characters, but I can copy and paste it to a text file and I'll get the chinese characters. It still doesn't work for my php file.
type: AnswerComment
score: 0

http://stackoverflow.com/comment/90907111
comment on: http://stackoverflow.com/a/51978685
score: 0
has text: First why both years and values to sets? Where is range? If failed if missing more years also.
type: AnswerComment
type: Comment

http://stackoverflow.com/a/52973985
has comment: http://stackoverflow.com/comment/107881345
upvote count: 41
downvote count: 2
has comment: http://stackoverflow.com/comment/126077697
has comment: http://stackoverflow.com/comment/139821973
has comment: http://stackoverflow.com/comment/92912170
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/107881606
accepted answer of: http://stackoverflow.com/q/52026405
has comment: http://stackoverflow.com/comment/92883545
has body: get_query_results only returns 1000 rows. How can I use it to get two million rows into a Pandas dataframe? If you try to add: client.get_query_results(QueryExecutionId=res['QueryExecutionId'], MaxResults=2000) You will obtain the next error: An error occurred (InvalidRequestException) when calling the GetQueryResults operation: MaxResults is more than maximum allowed length 1000. You can obtain millions of rows if you obtain the file directly from your bucket s3 (in the next example into a Pandas Dataframe): def obtain_data_from_s3(self): self.resource = boto3.resource('s3', region_name = self.region_name, aws_access_key_id = self.aws_access_key_id, aws_secret_access_key= self.aws_secret_access_key) response = self.resource \ .Bucket(self.bucket) \ .Object(key= self.folder + self.filename + '.csv') \ .get() return pd.read_csv(io.BytesIO(response['Body'].read()), encoding='utf8') The self.filename can be: self.filename = response['QueryExecutionId'] + ".csv" Because Athena names the files as the QueryExecutionId. I will write you all my code that takes a query and return a dataframe with all the rows and columns. import time import boto3 import pandas as pd import io class QueryAthena: def __init__(self, query, database): self.database = database self.folder = 'my_folder/' self.bucket = 'my_bucket' self.s3_input = 's3://' + self.bucket + '/my_folder_input' self.s3_output = 's3://' + self.bucket + '/' + self.folder self.region_name = 'us-east-1' self.aws_access_key_id = "my_aws_access_key_id" self.aws_secret_access_key = "my_aws_secret_access_key" self.query = query def load_conf(self, q): try: self.client = boto3.client('athena', region_name = self.region_name, aws_access_key_id = self.aws_access_key_id, aws_secret_access_key= self.aws_secret_access_key) response = self.client.start_query_execution( QueryString = q, QueryExecutionContext={ 'Database': self.database }, ResultConfiguration={ 'OutputLocation': self.s3_output, } ) self.filename = response['QueryExecutio…
score: 39
answers question: http://stackoverflow.com/q/52026405
has comment: http://stackoverflow.com/comment/98141191
has comment: http://stackoverflow.com/comment/92960260
type: Answer

http://stackoverflow.com/a/52042803
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/52036759
score: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/52036759
has body: You simply have the lines in the wrong order: import turtle bob = turtle.Turtle() print(bob) bob.fd(1000) turtle.mainloop() The final turtle.mainloop() line turns control over to tkinter's event loop so any lines after that won't get executed until the window is closed and the turtle environment has been torn down. I.e. it's usually the last thing you do in a turtle program.

http://stackoverflow.com/q/52025036
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52025124
accepted answer: http://stackoverflow.com/a/52025124
tagged with: import
type: Question
has title: Python: default variable in definition not defined when importing module
answer count: 1
score: 0
tagged with: python
has body: Let's say I have a module foo.py that contains the following function: def bar(var=somedict): print(var) In my main program, main.py, I import this module, define the variable somedict and then run the function bar: from foo import * somedict = 'foobar' bar() The idea is that somedict is passed along as default parameter without having to specify it explictly (which I'd like to avoid for the actual program I'm writing). However, Python throws a NameError: name 'somedict' is not defined. How can I still import the module and have the desired 'passing along of the default variable'? Thanks!
tagged with: module

http://stackoverflow.com/comment/91047337
type: QuestionComment
comment on: http://stackoverflow.com/q/52047934
type: Comment
has text: @macroland Without `plt.show()` the figure does not pop up. But in the GUI, the figure is empty.
score: 0

http://stackoverflow.com/a/52062651
has comment: http://stackoverflow.com/comment/91075961
upvote count: 2
type: Answer
has body: Since you're working with 2-dimensional matrices, I'd suggest using numpy. Then, in your case, you can just use np.diag: &gt;&gt;&gt; import numpy as np &gt;&gt;&gt; matrix = np.array([[1,4,7],[2,5,8],[3,6,9]]) &gt;&gt;&gt; matrix array([[1, 4, 7], [2, 5, 8], [3, 6, 9]]) &gt;&gt;&gt; np.diag(matrix) array([1, 5, 9]) However, @jpp's solution is more generalizable. My solution is useful in your case because you really just want the diagonal of your matrix.
score: 2
has comment: http://stackoverflow.com/comment/91075985
answers question: http://stackoverflow.com/q/52062560
downvote count: 0

http://stackoverflow.com/comment/91047990
comment on: http://stackoverflow.com/q/52031590
score: 0
type: Comment
type: QuestionComment
has text: I thought I could use `self.stacked.addWidget ()` to construct the widget and load it as a function.

http://stackoverflow.com/a/52092468
has comment: http://stackoverflow.com/comment/91135696
score: 0
type: AcceptedAnswer
has body: You use different encryption keys In Java System.out.println(EncryptUtil.AESEncode("1234567812345678", "python&amp;java")); See the code: KeyGenerator keygen = KeyGenerator.getInstance("AES"); keygen.init(128, new SecureRandom(encodeRules.getBytes())); SecretKey original_key = keygen.generateKey(); byte[] raw = original_key.getEncoded(); If you print the raw key, you will get fd839759956ba4a47922e8ee7c902f52 (HEX encoded), that's the encryption key If you would like to use the provided key directy, you should use byte[] raw = encodeRules.getBytes(); // (assuming encodeRules has 16 bytes) How do I edit my PYTHON code make the cipher_text equals JAVA encryption That's tricky.. you may have a look how SecureRandom works, but IMHO it's easier to fix the Java implementation to create a key you expect Regardless that I'd consider the implementation not secure enough - using ECB and simple key.
type: Answer
accepted answer of: http://stackoverflow.com/q/52089796
answers question: http://stackoverflow.com/q/52089796
has comment: http://stackoverflow.com/comment/91135544

http://stackoverflow.com/comment/90958043
type: Comment
type: QuestionComment
score: 0
has text: have a look at https://stackoverflow.com/a/12011486/1758363 - it creates a suite cleanly. pay attention you should not introduce new mocks/setups in suite - merely just assemblee existing tests.
comment on: http://stackoverflow.com/q/52004090

http://stackoverflow.com/comment/91118932
has text: dear @eyllanesc
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/52026352

http://stackoverflow.com/comment/90986558
has text: only while and if. I mean i only learned while and if statement in the course until now. So i assume i only can use them. Is getting annoying for me puiff lol
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52017976

http://stackoverflow.com/comment/90956225
type: Comment
has text: Updated the answer
type: AnswerComment
score: 1
comment on: http://stackoverflow.com/a/52003060

http://stackoverflow.com/comment/98689426
type: AnswerComment
comment on: http://stackoverflow.com/a/56022428
type: Comment
has text: Thanks for encouraging words :D I'll do my best.
score: 0

http://stackoverflow.com/comment/91143382
type: QuestionComment
comment on: http://stackoverflow.com/q/52096590
score: 1
has text: Did you install those and open Jupyter notebook in the same environment or working in a different environment?
type: Comment

http://stackoverflow.com/comment/90950609
comment on: http://stackoverflow.com/q/52000418
score: 0
type: Comment
type: QuestionComment
has text: i have really no idea how to write it down to python

http://stackoverflow.com/comment/90967322
type: Comment
has text: Indeed, @FHTMitchel, using lambdas worked for me.
comment on: http://stackoverflow.com/q/52007830
score: 0
type: QuestionComment

http://stackoverflow.com/comment/91014921
score: 1
type: AnswerComment
has text: @LunchBox using this to change your original df , then using the same method `df.A=df.A.str.extract('>(.*?)<',expand=True)[0].fillna(df.A)`
comment on: http://stackoverflow.com/a/52032157
type: Comment

http://stackoverflow.com/q/52049335
accepted answer: http://stackoverflow.com/a/52049473
tagged with: python
type: AnsweredQuestion
type: Question
has answer: http://stackoverflow.com/a/52049473
possible better answer: http://stackoverflow.com/a/52049580
has answer: http://stackoverflow.com/a/52049580
score: 0
answer count: 2
tagged with: pandas
has title: Summing certain columns with multiindex column dataframe
has body: I have a dataframe that is created from a pivot table, and looks similar to this: import pandas as pd d = { ('company1', 'False Negative'): {'April- 2012': 112.0, 'April- 2013': 370.0, 'April- 2014': 499.0, 'August- 2012': 431.0, 'August- 2013': 496.0, 'August- 2014': 221.0}, ('company1', 'False Positive'): {'April- 2012': 0.0, 'April- 2013' 544.0, 'April- 2014': 50.0, 'August- 2012': 0.0, 'August- 2013': 0.0, 'August- 2014': 426.0}, ('company1', 'True Positive'): {'April- 2012': 0.0, 'April- 2013': 140.0, 'April- 2014': 24.0, 'August- 2012': 0.0, 'August- 2013': 0.0,'August- 2014': 77.0}, ('company2', 'False Negative'): {'April- 2012': 112.0, 'April- 2013': 370.0, 'April- 2014': 499.0, 'August- 2012': 431.0, 'August- 2013': 496.0, 'August- 2014': 221.0}, ('company2', 'False Positive'): {'April- 2012': 0.0, 'April- 2013': 544.0, 'April- 2014': 50.0, 'August- 2012': 0.0, 'August- 2013': 0.0, 'August- 2014': 426.0}, ('company2', 'True Positive'): {'April- 2012': 0.0, 'April- 2013': 140.0, 'April- 2014': 24.0, 'August- 2012': 0.0, 'August- 2013': 0.0,'August- 2014': 77.0} } df = pd.DataFrame(d) company1 company2 FN FP TP FN FP TP April- 2012 112 0 0 112 0 0 April- 2013 370 544 140 370 544 140 April- 2014 499 50 24 499 50 24 August- 2012 431 0 0 431 0 0 August- 2013 496 0 0 496 0 0 August- 2014 221 426 77 221 426 77 I'm looking to iterative over the upper level of the multiindex column to create a sum column for each company: FSUM = FN + FP SUM = FN + FP + TP company1 company2 FN FP TP FSUM SUM FN FP TP FSUM SUM April- 2012 112 0 0 112 112 112 0 0 112 112 April- 2013 370 544 140 914 1054 370 544 140 914 1054 April- 2014 499 50 24 549 573 499 50 24 549 573 August- 2012 431 0 0 431 431 431 0 0 431 431 August- 2013 496 0 0 496 496 496 0 0 496 496 August- 2014 221 426 77 647 724 221 426 77 647 724 I don't know the company names beforehand, so it will need to loop

http://stackoverflow.com/q/52091844
tagged with: python-2.7
accepted answer: http://stackoverflow.com/a/52092211
downvote count: 0
answer count: 1
has title: python display remaining values after dividing the matrix
favorite count: 0
has body: i = [1,2,3,4,5,6,7,8,9,10] def ndiv(l,n): return [l[s:e] for s, e in zip(range(0,len(l)+1,n),xrange(n,len(l)+1,n))] for i in xrange(1,15,1): print "CLUSTER {}".format((ndiv(l,i))) #print CLUSTER [[1], [2], [3], [4], [5], [6], [7], [8], [9], [10], [11], [12], [13], [14], [15], [16], [17]] CLUSTER [[1, 2], [3, 4], [5, 6], [7, 8], [9, 10], [11, 12], [13, 14], [15, 16]] CLUSTER [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12], [13, 14, 15]] CLUSTER [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]] CLUSTER [[1, 2, 3, 4, 5], [6, 7, 8, 9, 10], [11, 12, 13, 14, 15]] CLUSTER [[1, 2, 3, 4, 5, 6], [7, 8, 9, 10, 11, 12]] CLUSTER [[1, 2, 3, 4, 5, 6, 7], [8, 9, 10, 11, 12, 13, 14]] CLUSTER [[1, 2, 3, 4, 5, 6, 7, 8], [9, 10, 11, 12, 13, 14, 15, 16]] CLUSTER [[1, 2, 3, 4, 5, 6, 7, 8, 9]] Coding up to now. After dividing, the remaining values are not shown omitted.But I want to have the prices shown after we split them(EX.if divide '3' ->before [[1, 2, 3, 4, 5], [6, 7, 8, 9, 10], [11, 12, 13, 14, 15]] / after [[1, 2, 3, 4, 5], [6, 7, 8, 9, 10], [11, 12, 13, 14, 15],[16],[17] ).How can I divide and then show the remaining numbers one by one?
tagged with: python
type: AnsweredQuestion
score: 1
has answer: http://stackoverflow.com/a/52092211
upvote count: 1
type: Question

tkinter
tags question: http://stackoverflow.com/q/51975723
tags question: http://stackoverflow.com/q/52083431
tags question: http://stackoverflow.com/q/52047607
tags question: http://stackoverflow.com/q/52058971
tags question: http://stackoverflow.com/q/52085525
tags question: http://stackoverflow.com/q/52087285
tags question: http://stackoverflow.com/q/51964325
tags question: http://stackoverflow.com/q/52074140
tags question: http://stackoverflow.com/q/52101034
tags question: http://stackoverflow.com/q/52058277
tags question: http://stackoverflow.com/q/52107844
tags question: http://stackoverflow.com/q/51965602
tags question: http://stackoverflow.com/q/52074995
tags question: http://stackoverflow.com/q/51971921
tags question: http://stackoverflow.com/q/52001532
tag name: tkinter
tags question: http://stackoverflow.com/q/52029870
tags question: http://stackoverflow.com/q/51973653
tags question: http://stackoverflow.com/q/51997542
tags question: http://stackoverflow.com/q/52021737
tags question: http://stackoverflow.com/q/52081828
tags question: http://stackoverflow.com/q/52029928
tags question: http://stackoverflow.com/q/52060306
tags question: http://stackoverflow.com/q/51991406
tags question: http://stackoverflow.com/q/51967673
tags question: http://stackoverflow.com/q/52047926
tags question: http://stackoverflow.com/q/51991048
tags question: http://stackoverflow.com/q/52026038
tags question: http://stackoverflow.com/q/52031267
tags question: http://stackoverflow.com/q/52075207
tags question: http://stackoverflow.com/q/52007906
tags question: http://stackoverflow.com/q/51975792
tags question: http://stackoverflow.com/q/52037428
tags question: http://stackoverflow.com/q/52060925
tags question: http://stackoverflow.com/q/52020472
tags question: http://stackoverflow.com/q/52100460
tags question: http://stackoverflow.com/q/51990726
tags question: http://stackoverflow.com/q/51976374
tags question: http://stackoverflow.com/q/52065190
tags question: http://stackoverflow.com/q/52010473
tags question: http://stackoverflow.com/q/52085033
tags question: http://stackoverflow.com/q/52015991
tags question: http://stackoverflow.com/q/51960505
tags question: http://stackoverflow.com/q/52094210
tags question: http://stackoverflow.com/q/52028438
tags question: http://stackoverflow.com/q/52043575
tags question: http://stackoverflow.com/q/52059974
tags question: http://stackoverflow.com/q/51991748
tags question: http://stackoverflow.com/q/52011219
tags question: http://stackoverflow.com/q/51984299
tags question: http://stackoverflow.com/q/52053307
tags question: http://stackoverflow.com/q/52034106
tags question: http://stackoverflow.com/q/52008289
tags question: http://stackoverflow.com/q/52108184
tags question: http://stackoverflow.com/q/52039621
tags question: http://stackoverflow.com/q/52108073
tags question: http://stackoverflow.com/q/51986128
tags question: http://stackoverflow.com/q/52048543
tags question: http://stackoverflow.com/q/51978710
tags question: http://stackoverflow.com/q/52058774
tags question: http://stackoverflow.com/q/52033378
tags question: http://stackoverflow.com/q/52035453
tags question: http://stackoverflow.com/q/52061933
tags question: http://stackoverflow.com/q/52019880
tags question: http://stackoverflow.com/q/52015845
tags question: http://stackoverflow.com/q/52060301
tags question: http://stackoverflow.com/q/52067256
tags question: http://stackoverflow.com/q/51962467
tags question: http://stackoverflow.com/q/52015836
tags question: http://stackoverflow.com/q/51977982
tags question: http://stackoverflow.com/q/52062162
tags question: http://stackoverflow.com/q/51997365
tags question: http://stackoverflow.com/q/52021882
tags question: http://stackoverflow.com/q/52018496
tags question: http://stackoverflow.com/q/52013486
tags question: http://stackoverflow.com/q/52015321
tags question: http://stackoverflow.com/q/52009769
tags question: http://stackoverflow.com/q/52021753
tags question: http://stackoverflow.com/q/51968897
tags question: http://stackoverflow.com/q/52054584

http://stackoverflow.com/comment/90888770
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51965420
has text: ok that is the problem.`response = client.describe_instances(InstanceIds = [instance_id])` fixes the problem.Thanks,by the way I want to know what does inst[0] contains, I am new to python and still learning it

http://stackoverflow.com/q/52070175
tagged with: sql-server
tagged with: pandas
answer count: 1
has title: INSERT Pandas Dataframe to SQL-Server using Python - Jupyter Notebook
accepted answer: http://stackoverflow.com/a/52089532
favorite count: 0
upvote count: 2
tagged with: python
score: 2
type: AnsweredQuestion
has body: Till now, I've been requesting data from my SQL-server, using an API, php file basically and using the requests module in Python. So here's my code for that: # importing the requests library import requests # api-endpoint URL = "https://******.co.in/******/queryRandom.php" # location given here token= '***************' query= 'SELECT userId,createdAt,.... FROM xyz WHERE date &gt;= CURDATE() - INTERVAL 60 DAY' # defining a params dict for the parameters to be sent to the API PARAMS = {'token':token, 'query':query} # sending get request and saving the response as response object r = requests.post(url = URL, data = PARAMS) df=pd.DataFrame(r.json()) df.head() Now after I'm done with my work, I formed a dataframe like this: Sl.No. date nameofthepic 1 26-08-2018 10-must-see-waterfalls-in-karnataka-8081714182d8 2 26-08-2018 a-month-in-backpack-one-girl-one-goal-to-explore-the-himalayas-22813ee67e15 3 26-08-2018 a-month-in-backpack-one-girl-one-goal-to-explore-the-himalayas-week-1-8d113ee673db 4 26-08-2018 a-month-in-backpack-one-girl-one-goal-to-explore-the-himalayas-week-1-22b13ee67b87 5 26-08-2018 backpacking-for-a-month-in-the-himalayas-week-1-30813ee674a6 Now using the similar requests module, is there a way I can write something like this: INSERT INTO table_name... and upload the dataframe into the SQL table. The main problem I'm not able to figure out is: i) How do I upload the dataframe column values into the table in one go? ii) If its not possible through requests module, is there any other way I can upload the Pandas dataframe values into SQL-server table directly from jupyter-notebook using Python code?
type: Question
has answer: http://stackoverflow.com/a/52089532
downvote count: 0

http://stackoverflow.com/q/52016983
favorite count: 0
tagged with: keyerror
possible better answer: http://stackoverflow.com/a/52017103
has answer: http://stackoverflow.com/a/52017069
accepted answer: http://stackoverflow.com/a/52017069
tagged with: python
type: AnsweredQuestion
upvote count: 3
type: Question
has answer: http://stackoverflow.com/a/52017103
score: 3
linked to: http://stackoverflow.com/q/25833613
has body: So I am using a for loop to determine if a specific key exists in a array. But so far every method I tried didn't work for what I am trying to accomplish. My code looks as follow: for i in range(1,len(opslag)): info_product = 'https://examplesite.com/'+str(opslag[i])+'.json' info_get = session.get(info_product) text_info_prdt = info_get.text json_info_prdt =json.loads(text_info_prdt) if json_info_prdt['product']['metafields']['meta_title_nl'] in json_info_prdt['product']['metafields']: print(json_info_prdt['product']['metafields']['meta_title_nl']) else: print(json_info_prdt['product']['id']) So the value in this case json_info_prdt['product']['metafields']['meta_title_nl'] , doesn't exist in every array I am trying to loop through. So sometimes the if else statement will work, and the value will be printed. But sometimes the value json_info_prdt['product']['metafields']['meta_title_nl'] doesn't exist at all and gives me a KeyError. So What I want to do is to get all the ID's of the products that return a KeyError but I don't want the loop to stop but to continue till it's finished. So I also don't want the loop to restart itself because that's pointless. My JSON looks as follow: { product:{ article_code:"", barcode:"", brand_id:null, created_at:"2017-07-07T12:49:23+02:00", data01:"", data02:"", data03:"", delivery_date_id:null, has_custom_fields:true, has_discounts:false, has_matrix:false, hits:0, hs_code:null, id:52847777, image_id:130661048, is_visible:true, price_excl:0, price_incl:0, price_old_excl:0, price_old_incl:0, product_set_id:383078, product_type_id:null, search_context:"", shop_id:240359, sku:"", supplier_id:null, updated_at:"2018-07-10T10:53:15+02:00", variants_count:4, visibility:"visible", weight:0, custom_fields:[ ], variants:[ ], product_relations:[ ], product_categories:[ ], product_discounts:[ ], product_type:null, product_filter_values:[ ], product_bundles:[ ], metafields:{ meta_title_nl:"Big House", meta_title_en:"cxzcxzcxz", meta_description_…
tagged with: http://stackoverflow.com/tag/json
has title: How to check if a value exists in JSON array and continue loop
answer count: 2
tagged with: for-loop
tagged with: arrays
downvote count: 0

http://stackoverflow.com/comment/91129399
comment on: http://stackoverflow.com/q/52088331
score: 0
type: Comment
type: QuestionComment
has text: cannot reproduce your issue, could you provide a [mcve]?

http://stackoverflow.com/comment/91044653
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52046754
has text: Yes. But the biggest clue is the error message. `'Series' objects are mutable, thus they cannot be hashed`. In order to determine duplicity, you have to be able to hash. `Series` objects are not hashable like the messages says. tuples generally are and therefore are a good target class to run the same logic.
type: AnswerComment

http://stackoverflow.com/a/52080465
answers question: http://stackoverflow.com/q/52080433
upvote count: 3
has comment: http://stackoverflow.com/comment/91111484
has comment: http://stackoverflow.com/comment/91111355
score: 3
has comment: http://stackoverflow.com/comment/91110963
downvote count: 0
has comment: http://stackoverflow.com/comment/91110942
has body: You can unpack in the tuple literal using * and switch out and for for to have a nested for loop in a list comprehension. You also don't need == True in an if block. G3 = [(i,*j) for i in Primes for j in G2 if dig_sum(i,j) and con_test(i,j)] n.b. this may not work in older versions of python. I'm not sure when it was introduced.
type: Answer

http://stackoverflow.com/comment/91173986
type: Comment
comment on: http://stackoverflow.com/a/52111555
score: 1
type: AnswerComment
has text: In python 2 you would use `xrange()` here, not `range()` *because* `range()` returns a list.

http://stackoverflow.com/q/52067458
favorite count: 0
tagged with: python-3.x
tagged with: clint
type: Question
tagged with: python
answer count: 1
upvote count: 1
has body: I am using the Python package named Clint to prettify the inputs necessary in my application. In the package you can access the module validators and use it combined with prompt to properly ask users to input data. I was looking for a possibility to implement a custom validator in Clint, due to a relatively short list of built-in classes of validators in the module: [FileValidator, IntegerValidator, OptionValidator, PathValidator, RegexValidator, ValidationError] So I wrote the code bellow: from clint.textui import prompt, validators class NumberValidator(object): message = 'Input is not valid.' def __init__(self, message=None): if message is not None: self.message = message def __call__(self, value): """ Validates the input. """ try: if int(value) &gt; 10: return value else: raise ValueError() except (TypeError, ValueError): raise validators.ValidationError(self.message) answer = prompt.query(f'Insert range in days:', '365', validators=[NumberValidator("Must to be &gt; 10")], batch=False) print(answer) It works, but I found the solution a bit messy. That is because using this solution I have to create a new class every time I need to perform a new different type of validation. I think it would be better if somehow the class could be dynamic using decorators, accepting a new function each time it would be initiated. But I found myself really bad in the decorators' subject. So I ask you to help me to make a more Pythonic solution to this problem.
has title: How to create a Custom Validator in Python Clint Module
has answer: http://stackoverflow.com/a/52071514
type: UnansweredQuestion
tagged with: command-line-interface
tagged with: validation
downvote count: 0
score: 1

http://stackoverflow.com/comment/91015007
comment on: http://stackoverflow.com/a/52032348
has text: Thanks, this is a great answer too! I didn't know sets can be used this way
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/90940647
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51994766
has text: When you googled that error message, what did you find?

http://stackoverflow.com/comment/90882821
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51965798
has text: `r1=re.findall(r'(?:vertices\s+)?(\([\w\,]+\))', s, re.DOTALL)`
score: 0

http://stackoverflow.com/q/52082325
tagged with: inheritance
tagged with: python-2.7
score: 0
has body: For ease of programming, I am looking to implement something like this: SpecialCaseChildClass.apply_to_all_members_of_child_class.any_method_of_parent() Even more awesome would be an implementation in which I can supply a list of arguments that allows me to iterate arguments: SpecialCaseChildClass.apply_to_all.any_method_of_Parent( argument1_of_parent_method = range(number_of_children), argument2_of_parent_method = range(number_of_children)) So my suggestion in words: (How) can I put an apply_to_all_members_of_class object/method between child and parent methods in command chain? I have tried to implement this functionality with a class method: class SpecialCaseChildClass(Parent): registry = [] def __init__(self, **kwargs, *args): super().__init__(self, **kwargs, *args) registry.append(self) @classmethod def apply_to_all(cls, any_function, *args, **kwargs): [any_function(child, *args, **kwargs) for child in cls.registry] which would allows the following: SpecialCaseChildClass.apply_to_all_members_of_child_class(ParentClass.any_Parent_method, *args, *kwargs) but that is not as pretty as simple addition to the chain. Is such a thing possible relatively simply? Is it even desirable?
tagged with: python
tagged with: python-3.x
answer count: 0
type: UnansweredQuestion
tagged with: design-patterns
has comment: http://stackoverflow.com/comment/91115179
has title: How can I most beautifully apply the methods of a parent class to all (registered) instances?
has comment: http://stackoverflow.com/comment/91152226
has comment: http://stackoverflow.com/comment/91117803
type: Question
has comment: http://stackoverflow.com/comment/91151823

http://stackoverflow.com/q/52097001
favorite count: 0
has comment: http://stackoverflow.com/comment/91144174
upvote count: 1
tagged with: django
downvote count: 1
type: AnsweredQuestion
tagged with: django-forms
tagged with: django-widget
has answer: http://stackoverflow.com/a/52097168
type: Question
has title: Change model form field to text input widget
answer count: 1
has comment: http://stackoverflow.com/comment/91144200
score: 0
tagged with: python
accepted answer: http://stackoverflow.com/a/52097168
has body: I want to change the 'trans_recipient' field widget from being a dropdown, into being a text-input field. In the case of a large I've tried the following : class SafeTransactionForm(forms.ModelForm): ''' SafeTranSactionForm ''' trans_recipient = forms.CharField(widget=forms.TextInput(attrs={'class': 'special'})) class Meta: model = SafeTransaction fields = [ 'trans_recipient', 'subject', 'arbitrator_name', 'payment_condition', 'amount_to_pay'] That produces this : and although the widget itself has changed, actually trying to use it produces a value error as such : without my incorrect one-line attempt at changing the widget : class SafeTransactionForm(forms.ModelForm): ''' SafeTranSactionForm ''' class Meta: model = SafeTransaction fields = [ 'trans_recipient', 'subject', 'arbitrator_name', 'payment_condition', 'amount_to_pay'] the dropdown: I've tried playing around with syntax, trying to update the widget within the meta class, I've mostly ended up with syntax errors and I've not been able to find examples of this specific case after some Google searches. Insight and explanations are very much welcome and appreciated. EDIT: Now I am getting an error : ValueError: invalid literal for int() with base 10: 'inbox' Stack Trace : UpdateView class : class SafeTransUpdateView(UpdateView): ''' This view lets the user Update a SafeTransaction receipt then send an automatic email to the email address ''' form_class = SafeTransactionForm model = SafeTransaction template_name = "myInbox/safeTrans_update.html" def __init__(self, *args, **kwargs): self.request = kwargs.pop('request', None) super(SafeTransUpdateView, self).__init__(*args, **kwargs) def form_valid(self, form): trans = form.save(commit=False) trans.save() ### Send an email to the user upon transaction update. usr_obj = User.objects.get(customuser=trans.trans_recipient) user_mail = usr_obj.email from_email = 'timi.ogunkeye@gmail.com' contents = "This transaction [ " +trans.payment_condition+" ] has been updated !" …

http://stackoverflow.com/comment/91175260
comment on: http://stackoverflow.com/q/52112142
type: QuestionComment
score: 0
has text: I tried multiple different user agents using the switcher plugin and they all seem to work. When I try adding the user agent string to my program I still get the same error.
type: Comment

http://stackoverflow.com/comment/90991195
has text: @fmw42 Sorry, yes - I forgot that bit because I ent out and did something else in the middle of answering. The original image was poorly trimmed. I'll add the trimmed one for you to play with.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52019617
type: AnswerComment

http://stackoverflow.com/q/51993906
has comment: http://stackoverflow.com/comment/90938004
tagged with: output
downvote count: 1
type: Question
has body: I'm currently working on a chat application with Python, but am currently facing an annoying problem. When the user is inputting a message to the console, while an another user is sending messages, the input message of the first user gets split into multiple lines. I attached a picture of the problem. As you can see, the input is being intercepted with the output of the console. Any idea how to prevent this? For the input, I was holding down Z while a friend was sending messages to the channel. As you can see, It's being interrupted by the messages that are appearing. Edit: import colorama from termcolor import cprint colorama.init() green = '\33[92m' reset = '\033[0m' def receive_messages(): while True: data = s.recv(1024).decode() #s is a previously defined socket ind = data.index("&gt;") + 1 usr = data[:ind] raw = data[ind:] cprint(green + usr + green + reset + raw + reset) threading.Thread(target = receive_messages).start() username = #opens the file where the username is stored: &lt;username&gt; while True: txt = input() s.send((username + " " + txt).encode()) What I want is the input text to be locked in one line and not split into many.
has comment: http://stackoverflow.com/comment/90937665
has title: Input text in the console being split into multiple lines by the output of the program
accepted answer: http://stackoverflow.com/a/51994155
answer count: 1
score: 1
has comment: http://stackoverflow.com/comment/90937683
tagged with: console
favorite count: 0
upvote count: 2
has comment: http://stackoverflow.com/comment/90937806
tagged with: python
has comment: http://stackoverflow.com/comment/90938046
has comment: http://stackoverflow.com/comment/90937748
has comment: http://stackoverflow.com/comment/90937908
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51994155
linked to: http://stackoverflow.com/q/25342420

http://stackoverflow.com/comment/93337012
score: 1
has text: @phung-duy-phong I realized why is this happened. Some of the values was numeric. In this case `df['temp'] = df['name'].astype('str') + df['table_num'].astype('str')` do a trick in just few sec. Thanks for help again :)
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52072607

http://stackoverflow.com/q/52105564
tagged with: python
accepted answer: http://stackoverflow.com/a/52120995
type: AnsweredQuestion
tagged with: sqlalchemy
type: Question
has comment: http://stackoverflow.com/comment/91188585
has body: I am new to both python and SQLAlchemy. I am on python 3 I created a class testtbl to manipulate tables. One function is the update where I pass : myfilter = {'origin_source_id':'MX01’}. find this row in mysql table where origin_source_id = ‘MX01' updatevalue = {'origin_source_id':'CAL01’} replace the found origin_source_id by ‘CAL01; The call testtbl.update_row(myfilter,updatevalue) The function def update_row(self,locaterowfilter,updatevalue): self.Session.query( self.TableClass ).filter_by( **locaterowfilter ).update( updatevalue ) I receive the following error target_cls = query._mapper_zero().class_ AttributeError: 'NoneType' object has no attribute ‘class_’ I have no idea how to deal with it. Is there a better way to do that?
score: 0
has answer: http://stackoverflow.com/a/52120995
answer count: 1
has title: SQLAlchemy updating a value in a row dynamically after filter_by
has comment: http://stackoverflow.com/comment/91171732

http://stackoverflow.com/a/51993696
answers question: http://stackoverflow.com/q/51978648
type: AcceptedAnswer
downvote count: 0
type: Answer
has body: You can use a converter to resolve the User object of your victim automatically. @bot.command() async def spam(ctx, victim: discord.User, amount, *, message): for _ in range(amount): await victim.send(message) You can then use their name, id, or a mention to specify them: !spam Denard 1 spam spam spam !spam @Denard 1 spam spam spam !spam 1234 1 spam spam spam
accepted answer of: http://stackoverflow.com/q/51978648
upvote count: 3
score: 3

http://stackoverflow.com/q/52010357
tagged with: python
has comment: http://stackoverflow.com/comment/90971788
score: 2
has comment: http://stackoverflow.com/comment/90971732
tagged with: mysql
has title: Cannot connect to MySQL with MySQLdb in Python, can connect from command line
type: Question
downvote count: 0
has body: I'm having trouble connecting to my local MySQL database in python, but have no problem connecting from the command line. When I try this: db = MySQLdb.connect(host="localhost", user="username", passwd="password", db="dbname", port=3306, unix_socket="/var/run/mysqld/mysqld.sock") I get the following error: OperationalError: (2002, "Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)") I get the same error when I don't explicitly pass in the socket path. I get a similar error when I use 127.0.0.1 instead of localhost as the host (also removing the unix socket argument): OperationalError: (2003, "Can't connect to MySQL server on '127.0.0.1' (111)") I know that MySQL is running, as when I can connect to the database from the command line no problem with mysql -u username -p dbname. I also know MySQL is listening on 127.0.0.1, when I run mysql -h 127.0.0.1 -p I can connect as well. I'm also sure it's listening on port 3306.
has comment: http://stackoverflow.com/comment/90971647
has comment: http://stackoverflow.com/comment/90971913
has comment: http://stackoverflow.com/comment/90972033
favorite count: 0
answer count: 0
upvote count: 2
type: UnansweredQuestion

http://stackoverflow.com/comment/91023613
score: 0
type: Comment
type: QuestionComment
has text: Is there any specific motive for use of **urllib**?
comment on: http://stackoverflow.com/q/52035666

http://stackoverflow.com/comment/115780390
type: AnswerComment
comment on: http://stackoverflow.com/a/55532036
has text: this didnot work for me. IPython.display.YouTubeVideo module worked for me
score: 0
type: Comment

http://stackoverflow.com/q/52025887
favorite count: 0
score: 0
downvote count: 1
tagged with: python
has body: I have this directory containing 50 files and I want to read each file and store all text of that file in a index of my list so after some research I wrote the following code but it gives me error at this line : filedata[i]=filee.read() IndexError: list assignment index out of range Here is the code: import os filedata = list() for dirpath, dirnames, filenames in os.walk('Doc50'): print(filenames[4]) i=1 for file in filenames: fpath = os.getcwd() fpath = os.path.join(fpath, str(dirpath)) fpath = os.path.join(fpath, str(filenames[i])) filee = open(fpath,mode='r') print("value of i: " + str(i)) filedata[i]=filee.read() filee.close() i=i+1 print(filedata) I am new in python so pardon me if you find this code lengthy and if it could be done in more optimized way please let me know.
has title: Error in reading all files present in a folder
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91001910
possible better answer: http://stackoverflow.com/a/52026054
has answer: http://stackoverflow.com/a/52026054
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/52026106
upvote count: 1
accepted answer: http://stackoverflow.com/a/52026106

http://stackoverflow.com/comment/90922906
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51986526
has text: yes his approach looks very good too. both are more readable than my first piece of code
type: AnswerComment

http://stackoverflow.com/comment/90947864
comment on: http://stackoverflow.com/q/51999334
has text: I thhink you are only missing putting the actual file line in the body of that loop: `for %%F IN requirements.txt DO conda install --yes %%F`. But specifying the file when creating the env is more straight forward
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91071347
score: 0
type: QuestionComment
has text: @DavideR. i added the extra info
comment on: http://stackoverflow.com/q/52058611
type: Comment

http://stackoverflow.com/comment/91154761
score: 0
type: Comment
comment on: http://stackoverflow.com/q/52099601
type: QuestionComment
has text: After I pass in the username and password I need to click a button. That's why.

http://stackoverflow.com/comment/91054901
comment on: http://stackoverflow.com/q/52009682
score: 1
has text: Just a remark: the salt in your code is not supposed to be same as the key. Either generate a deterministic *non-repeating* sequence, or use SecureRandom to generate it; then transmit it along with the encrypted message.
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52051779
tagged with: python-3.x
answer count: 0
type: UnansweredQuestion
has title: python queue.Queue(block=True, timeout=.001) has 9-13 ms delay in windows vs Ubuntu
upvote count: 1
tagged with: python
score: 1
has body: I have found that using timeout with a python queue.Queue() results in an 9-13ms delay in Windows over Ubuntu in python 3.6.5 Does that make sense? import datetime import queue q = queue.Queue() print(datetime.datetime.now()) try: msg = q.get(block=True, timeout=.001) except: print(datetime.datetime.now()) Window 10, Python 3.6.5 2018-08-28 02:20:20.374122 2018-08-28 02:20:20.388434 time 14ms Ubuntu 16.04, Python 3.6.5 2018-08-28 06:21:01.305297 2018-08-28 06:21:01.306404 time 1.1ms
type: Question
downvote count: 0
favorite count: 0

http://stackoverflow.com/comment/90963354
has text: Oh thankyou for that! I was not aware that you could use `pygame.key.get_pressed()` like that! Also, thankyou for that advice, it certainly would help clean up my code!
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52006416

http://stackoverflow.com/a/51960374
upvote count: 1
has body: An alternative method is to define a class with printX as an inner function. class thread: def __init__(self, time, message): self.time = time self.message = message def printX(self): threading.Timer(int(self.time), self.printX).start() print(str(self.message)) thread(3,"test message").printX() while True: print("Rest of the program continues") sleep(1)
answers question: http://stackoverflow.com/q/51959909
downvote count: 0
type: Answer
score: 1

http://stackoverflow.com/q/52021628
tagged with: pandas
tagged with: elasticsearch
favorite count: 0
type: UnansweredQuestion
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/90994300
tagged with: nosql
answer count: 0
has comment: http://stackoverflow.com/comment/91000461
has comment: http://stackoverflow.com/comment/90997658
has title: Fill in missing timestamp data in elasticsearch database
downvote count: 1
has comment: http://stackoverflow.com/comment/91018916
type: Question
has body: I have a GPS device reporting positions every second. The positions over time end up being stored in an elasticsearch database as a geo_point/@timestamp combination. As is the nature of GPS, a position may not be reported at a particular time (for example if the device loses lock). What is the best way to fill the missing positions so that I have a position for every @timestamp? More specifically, how can I create the missing documents in the elasticsearch database so I have a position value every second? I have looked into linear interpolation between adjacent points using elasticsearch-py and pandas, but not had a any luck. How can I achieve this? Sample code would be greatly appreciated.
score: 0

http://stackoverflow.com/q/52085191
has answer: http://stackoverflow.com/a/68211588
type: Question
has answer: http://stackoverflow.com/a/58882108
has answer: http://stackoverflow.com/a/72719258
has answer: http://stackoverflow.com/a/53667554
has answer: http://stackoverflow.com/a/78886198
tagged with: python
tagged with: pyodbc
has answer: http://stackoverflow.com/a/69620010
has answer: http://stackoverflow.com/a/78974639
upvote count: 29
answer count: 16
has body: I've written a short python script which tries to import the pyodbc extension package so I can access my SQL table. import pyodbc as pyodbc cnxn = pyodbc.connect('Driver={SQL Server};' 'Server=DESKTOP-UO8KJOP;' 'Database=ExamplePFData' 'Trusted_Connection=yes;') I have definitely installed the extension by using: pip install pyodbc. And when I go to install it again, cmd says: Requirement already satisfied: pyodbc in ... and I've found the pyd file in my directories. I have also tried installing pypyodbc, which didn't work. The error I get is: Traceback (most recent call last): File "C:\Users\Jerry\Documents\Python\SQLembed.py", line 5, in &lt;module&gt; import pyodbc as pyodbc ModuleNotFoundError: No module named 'pyodbc' (where line 5 is the 'import pyodbc' line) I have tried copying the pyodbc.cp37-win_amd64.pyd file into my Python Scripts folder and into the folder where my pip.exe file is. Currently python is my Python37 folder. pyodbc.cp37-win_amd64.pyd is in Python > Lib > site-packages. Can anyone help me fix this error please so that I can import pyodbc? Do all of the python extensions/modules that I install via pip need to be in the same folder/directory as python.exe?
has answer: http://stackoverflow.com/a/55841769
has answer: http://stackoverflow.com/a/74863568
has answer: http://stackoverflow.com/a/55630516
has answer: http://stackoverflow.com/a/52085981
has answer: http://stackoverflow.com/a/74001070
linked to: http://stackoverflow.com/q/21054656
has answer: http://stackoverflow.com/a/60117348
type: UnansweredQuestion
has title: ModuleNotFoundError: No module named 'pyodbc' when importing pyodbc into py script
has comment: http://stackoverflow.com/comment/91124017
score: 29
has answer: http://stackoverflow.com/a/75704801
tagged with: sql-server
tagged with: sql
has answer: http://stackoverflow.com/a/70969822
tagged with: sqlite
downvote count: 0
has answer: http://stackoverflow.com/a/78365049
favorite count: 0

http://stackoverflow.com/a/58871067
type: Answer
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/128315856
upvote count: 2
has comment: http://stackoverflow.com/comment/116553475
has body: You can do with openpyxl module also Here is the modified code import base64 import io import openpyxl with open('encoded_data.txt','rb') as d: data=d.read() print(data) decrypted=base64.b64decode(data) print(decrypted) xls_filelike = io.BytesIO(decrypted) workbook = openpyxl.load_workbook(xls_filelike) sheet_obj = workbook.active max_col = sheet_obj.max_column max_row = sheet_obj.max_row # Will print all the row values for i in range(1, max_row +1): for j in range(1, max_col + 1): cell_obj = sheet_obj.cell(row = i, column = j) print cell_obj.value, print ",", "Inorder to seperate the cells using comma for readability print ""
answers question: http://stackoverflow.com/q/52075814
has comment: http://stackoverflow.com/comment/128462630

http://stackoverflow.com/comment/91050280
comment on: http://stackoverflow.com/a/52047431
has text: I did completely misunderstand. Thanks for the clarification.
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/91034766
has text: We have a Manager GUI that kicks off the workers on startup. We take the stdout and stderr and display them in the GUI. This all works like a charm under Windows 10. I'm trying to get it all to behave in Linux and that is where the pain started.
comment on: http://stackoverflow.com/q/52010330
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91179260
type: AnswerComment
comment on: http://stackoverflow.com/a/52110108
type: Comment
has text: @ImportanceOfBeingErnest I have edited the answer. Please look if this seems correct.
score: 0

http://stackoverflow.com/comment/91086645
type: QuestionComment
comment on: http://stackoverflow.com/q/52067655
has text: I have asked for an MCVE, if your code does not reproduce the problem it is not an MCVE, please take the time and provide what I have asked for to help you and thus save us time.
score: 0
type: Comment

http://stackoverflow.com/q/51972291
answer count: 1
type: UnansweredQuestion
tagged with: django
tagged with: python
has body: How do you create a sum of child nodes into a a parent node for multiple levels in an accounting hierarchy with Python/Django? I currently have an app which displays the sum of individual accounts, but these values are not added to parent level accounts. The app has the following models: from django.db import models class accounts(models.Model): account_nr = models.IntegerField(null=True) account_name = models.CharField(max_length=100) account_parent_nr = models.IntegerField(null=True) class transactions(models.Model): transaction_id = models.CharField(max_length=100) account_ID = models.ForeignKey(accounts, on_delete=models.CASCADE) debit_value = models.DecimalField(max_digits=10, decimal_places=2) credit_value = models.DecimalField(max_digits=10, decimal_places=2) Some sample data is: account_nr account_name account_parent_nr 1000 current assets null 1001 cash 1000 1002 bank 1000 1010 debtors 1000 1011 debtor 1 1010 1012 debtor 2 1010 3000 stock null 3010 category 1 3000 3011 product a 3010 3012 product b 3010 ... 0010 equity null 0011 owner x 0010 0012 owner y 0010 Sample data for transactions would be: transaction_id account_id debit_value credit_value 1 1001 100 0 1 0011 0 100 2 1002 100 0 2 0011 0 100 3 1011 100 0 3 0011 0 100 4 1012 100 0 4 0011 0 100 5 3011 50 0 5 3012 50 0 5 0012 0 100 The following view is used: from django.shortcuts import render from django.db.models import Sum from .models import accounts, transactions def home(request): account_query = accounts.objects.all() \ .annotate(Sum('transactions__debit_value')) \ .annotate(Sum('transactions__credit_value')) \ .order_by('account_nr') args = {'account_queryx': account_query} return render(request, 'home.html', args) And the following template: {% extends "base.html" %} {% block content %} Account Omschrijving Debit Credit {% for account_query in account_queryx %} {{ account_query.account_nr }} {{ account_query.account_name }} {{ account_query.transactions__debit_value__sum}} {{ account_query.tra…
has answer: http://stackoverflow.com/a/51975704
tagged with: recursion
type: Question
has title: Sum of child nodes in accounting hierarchy in django/python
score: 0

http://stackoverflow.com/comment/90919838
type: Comment
type: QuestionComment
has text: Yes - edited, I'm sorry for having asked the question ambiguously
comment on: http://stackoverflow.com/q/51984993
score: 0

http://stackoverflow.com/comment/90889546
comment on: http://stackoverflow.com/q/51969361
type: Comment
type: QuestionComment
has text: Could you please post the exact error the IDE is complaining? Also: which line in your code would be line 37?
score: 0

http://stackoverflow.com/q/52075353
has comment: http://stackoverflow.com/comment/91105729
favorite count: 0
score: 0
tagged with: pandas
tagged with: python
has comment: http://stackoverflow.com/comment/91106671
has comment: http://stackoverflow.com/comment/91100531
answer count: 0
has comment: http://stackoverflow.com/comment/91101702
upvote count: 3
type: UnansweredQuestion
has body: I want to replace ABC with the value of next column for that particular row. If ABC lies in last column then value should be from previous column. If nan is present then it should be not be replaced by any other value. In-fact, we have to do this operation till nan if present. Dataframe is as given below: C1 C2 C3 ……. C47 C48 C49 C50 1 0 ABC 15 ……. 29 ABC 90 50 2 ABC ABC 7 ……. 26 10 ABC 30 3 ABC ABC ABC ……. ABC ABC ABC ABC 4 6 20 32 ……. 18 44 ABC ABC 5 2 ABC 24 ……. 16 27 29 ABC 6 23 4 49 ……. 11 52 33 9 7 17 12 2 ……. ABC 31 nan nan 8 ABC nan nan ……. nan nan nan nan 9 34 36 2 ……. 19 ABC nan nan output should be: C1 C2 C3 ……. C47 C48 C49 C50 1 0 15 15 ……. 29 90 90 50 2 7 7 7 ……. 26 10 30 30 3 0 0 0 ……. 0 0 0 0 4 6 20 32 ……. 18 44 44 44 5 2 24 24 ……. 16 27 29 29 6 23 4 49 ……. 11 52 33 9 7 17 12 2 ……. 31 31 nan nan 8 0 nan nan ……. nan nan nan nan 9 34 36 2 ……. 19 19 nan nan Please note ABC will be 0 only when there is no value present in rest of the columns for that particular row.
has title: Want to replace value in one column from another column based on specific condition in python
downvote count: 3
has comment: http://stackoverflow.com/comment/91106686
type: Question
has comment: http://stackoverflow.com/comment/91100575

http://stackoverflow.com/q/52027037
accepted answer: http://stackoverflow.com/a/52027077
has comment: http://stackoverflow.com/comment/91004320
downvote count: 0
answer count: 1
tagged with: string
has body: I am trying to convert a string input to a float after the input is given. Leaving the option to do something with the input if it is a string. I have tried some things but they give back the following error: "TypeError: can't multiply sequence by non-int of type 'float' on line 8" Below is code that works, but I want to keep the input a string and convert to float after the input is given: def computepay(h,r): if h&lt;=40: return h*r else: return h*r+((h-40)*b) h = float(input("Enter Hours:")) r = float(input("Enter Rate:")) b = 0.5*r p = computepay(h,r) print(p) How would this be done correctly? Thanks!
favorite count: 0
has comment: http://stackoverflow.com/comment/91005065
tagged with: python-3.x
has answer: http://stackoverflow.com/a/52027077
tagged with: input
tagged with: python
type: AnsweredQuestion
has title: Custom function: converting string inputs to float after the input
score: 1
upvote count: 1
type: Question

http://stackoverflow.com/comment/91122825
type: QuestionComment
comment on: http://stackoverflow.com/q/52086208
score: 0
has text: Can you add `df.head().to_dict()` to the question. I think it's ambiguous as to how `'time_cost'` is stored in your `DataFrame`
type: Comment

http://stackoverflow.com/comment/90929379
score: 2
has text: Probably `door = 'locked\n'`, not `door = 'locked'`. Always log your *actual* values (ie. `print("Door status: %r" % (door,))`) to allow debugging before you escalate to asking questions here. :)
comment on: http://stackoverflow.com/q/51989896
type: Comment
type: QuestionComment

http://stackoverflow.com/a/52104706
upvote count: 2
has body: You are constantly filling the screen with white in your mainloop. The Player class only draws on __init__. This means that the rect is drawn for a split second and then covered over by white. Your assumption about the code in __init__ automatically being called is correct. These methods with double underscores are called by python in special cases, they are called magic methods. You can find a list of them here. def __init__(self): pygame.sprite.Sprite.__init__(self) # The rect drawing part was moved from here. def update(self): # You were previously assigning this to a variable, this wasn't necessary. pygame.draw.rect(game.screen, black, [self.lead_x, self.lead_y, self.block_size, self.block_size]) You will need to call the new update method in the mainloop after you fill the screen. while True: game.fill_screen(white) player.update()
has comment: http://stackoverflow.com/comment/91160865
has comment: http://stackoverflow.com/comment/91160805
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/52104513
downvote count: 0
type: Answer
score: 2
has comment: http://stackoverflow.com/comment/91160973
answers question: http://stackoverflow.com/q/52104513

http://stackoverflow.com/comment/91097994
has text: @IljaEverilä Yes, I know. I have already read the specific thread on the VALUES construct. My main issue, as I mentioned earlier, is that I want to predefine the number of columns and the column names of the generated table. Sorry if I am making it a bit hard for you, but it's my first post here and I am trying to get to grips. Thank you very much for the super fast replies.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52073307

http://stackoverflow.com/a/51986696
type: Answer
answers question: http://stackoverflow.com/q/51986378
has body: When you say "Wrap a function in another function", I hear decorator. Take a look at the following code: import functools def decorator(func): @functools.wraps(func) def wrap(*args, **kwargs): self.csn(0) func(*args, **kwargs) self.csn(1) return wrap Put this decorator over the self.spidev.xfer2(txbuffer) function with the syntax @decorator in the same way @functools is used above. Anytime you want to wrap a function in this manner you simply need to put the decorator over the function declaration.
score: 0

http://stackoverflow.com/comment/91146942
comment on: http://stackoverflow.com/q/51967633
score: 0
type: Comment
type: QuestionComment
has text: My mistake: the file was apparently too large; now re-uploaded the same file, just gzipped. @J. Blackadar the kernel is definitely not busy; it displays the black window and continues to work, but nothing ever appears in the black display region.

http://stackoverflow.com/q/51994006
has answer: http://stackoverflow.com/a/60742900
has title: Create Clustered Columnstore index(MS SQL Server) using SqlAlchemy?
type: Question
tagged with: database
tagged with: sqlalchemy
has answer: http://stackoverflow.com/a/60746029
answer count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/95295008
has body: How to create Clustered Columnstore index on a table using SqlAlchemy python library? I can see support for clustered indexes in the docs here but could not find how to add columnstore keyword to it.
favorite count: 0
tagged with: sql-server
tagged with: python
linked to: http://stackoverflow.com/q/56662626
score: 2
upvote count: 2
type: UnansweredQuestion
tagged with: orm

http://stackoverflow.com/q/51978079
has body: i hope this isn't a duplicate. I searched through other entries and none seemed to address the problem i'm seeing. We have an AWS Lambda function written in Python 3.6. The Lambda function is executed through API Gateway using the Lambda proxy integration. The function is initiated without problem and the processing executes without a problem. However, no matter what we seem to do in trying to send a response, the client receives "{"message": "Internal server error"}" I don't know that it's important, but the client for our test is Postman. We've stripped out all of our business logic and isolated the code that does the return and we still get have the same problem. the code is: import json def lambdaTest(event, context) response = {} dummybody = {'body':'something'} response['statusCode'] = 200 response['body'] = dummybody response["headers"] = {"Content-Type": "application/json"}, return json.dumps(response) i'm sure I'm doing something wrong that's simple as I don't seem many posts about this problem. I would very much appreciate any help. Thanks.
type: UnansweredQuestion
upvote count: 1
tagged with: python
has title: AWS Lambda Integration Response in API Gateway - {"message": "Internal server error"}
has answer: http://stackoverflow.com/a/51988078
score: 1
has comment: http://stackoverflow.com/comment/90915053
tagged with: response
type: Question
answer count: 1
has comment: http://stackoverflow.com/comment/90920557
downvote count: 0
tagged with: aws-api-gateway
tagged with: amazon-web-services
favorite count: 0

http://stackoverflow.com/comment/91026664
type: QuestionComment
comment on: http://stackoverflow.com/q/52038163
score: 1
has text: Did you change the setting [AUTH_USER_MODEL](https://docs.djangoproject.com/en/2.1/ref/settings/#std:setting-AUTH_USER_MODEL)?
type: Comment

http://stackoverflow.com/a/52081853
has comment: http://stackoverflow.com/comment/91115918
has comment: http://stackoverflow.com/comment/91116197
downvote count: 0
type: Answer
upvote count: 1
score: 1
has body: Because rmarkdown is not among the default packages loaded with each R session such as utils, base, and stats, you need to call library(rmarkdown) line in your Python command call which runs outside your R script. Consider also using Python's subprocss.Popen, a better handler for command line calls, to even capture console and error output with better quote handling (and even add Rscript to PATH environment variable and avoid specifying the full directory to the executable). from subprocess import Popen, PIPE # COMMAND WITH THREE ARGUMENTS cmd = ["C:/PROGRA~1/R/R-3.5.1/bin/x64/Rscript.exe", "-e", "Sys.setenv(RSTUDIO_PANDOC='C:/Program Files (x86)/Pandoc'); library(rmarkdown); rmarkdown::render('../Filter Tool/report.Rmd')" p = Popen(cmd, stdin=PIPE, stdout=PIPE, stderr=PIPE) output, error = p.communicate() if p.returncode == 0: print('R OUTPUT:\n {0}'.format(output)) else: print('R ERROR:\n {0}'.format(error))
answers question: http://stackoverflow.com/q/52065886

http://stackoverflow.com/comment/91096355
type: QuestionComment
has text: Did you import it as shown in the code? `import tableauserverclient as TSC` ?
score: 0
comment on: http://stackoverflow.com/q/52073244
type: Comment

http://stackoverflow.com/comment/90960069
type: Comment
comment on: http://stackoverflow.com/a/52004230
type: AnswerComment
has text: I thought that it worked like the `cycler` in mplstyle, but I see that it didn't. Thank you!
score: 0

http://stackoverflow.com/comment/91102057
comment on: http://stackoverflow.com/a/52076204
score: 0
type: AnswerComment
has text: Okay, that's great, thank you. And do you think I should actually get rid of the `algorithm` folder, where `genetic.py` defines a class to solve TSP with genetic algorithm and the `params.py` is just a file with one dataclass?
type: Comment

http://stackoverflow.com/q/51969476
type: Question
has answer: http://stackoverflow.com/a/51974410
has answer: http://stackoverflow.com/a/51969707
downvote count: 0
has answer: http://stackoverflow.com/a/51974474
favorite count: 0
answer count: 3
tagged with: pandas
has body: I have two input dataframes, df1 and df2: id first last size A 1978-01-01 1979-01-01 2 B 2000-01-01 2000-01-01 1 C 1998-01-01 2000-01-01 3 D 1998-01-01 1998-01-01 1 E 1999-01-01 2000-01-01 2 id token A ZA.00 B As.11 C SD.34 My desired output: id first last size ZA.00 1978-01-01 1979-01-01 2 As.11 2000-01-01 2000-01-01 1 SD.34 1998-01-01 2000-01-01 3 D 1998-01-01 1998-01-01 1 E 1999-01-01 2000-01-01 2 If df2['id'] matches df1['id'] then replace df1['id'] with df2['token']. How can I achieve this?
upvote count: 2
type: UnansweredQuestion
tagged with: python
score: 2
has title: How to compare two Dataframes on a column and replace with other column value

http://stackoverflow.com/q/51975617
answer count: 1
tagged with: web-frameworks
tagged with: gunicorn
tagged with: python
has title: Common web servers/frameworks for deploying python machine learning models?
has body: I noticed both Databricks MLFlow and Amazon Sagemaker both make use of the combination of Nginx, Gunicorn, and Flask. I was wondering if that tends to be the standard stack for deploying machine learning models (e.g. Scikit-learn, Tensorflow, Keras). If so, is there are reason those are used over alternatives like Tornado? If not, is there a "standard stack"
has comment: http://stackoverflow.com/comment/90912671
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/20766684
type: Question
has answer: http://stackoverflow.com/a/51981597
tagged with: webserver
accepted answer: http://stackoverflow.com/a/51981597
tagged with: tornado
score: 0

queue
tags question: http://stackoverflow.com/q/52090339
tags question: http://stackoverflow.com/q/52045596
tags question: http://stackoverflow.com/q/52094432
type: Tag
tags question: http://stackoverflow.com/q/52091113
tags question: http://stackoverflow.com/q/52075515
tag name: queue
tags question: http://stackoverflow.com/q/52046552

http://stackoverflow.com/a/51967465
answers question: http://stackoverflow.com/q/51967102
has comment: http://stackoverflow.com/comment/90912664
score: 0
has body: The code which wants to write needs to access the value of the variable wr somehow. You don't tell us what that code really wants to do, but as a starting point, here is one way to modify your example. import csv def start(): NewCSV = input('Name of csv: ') with open(NewCSV + '.csv', 'w') as myfile: wr = csv.writer(myfile, quoting=csv.QUOTE_ALL) Code_that_writes_in_CSV(wr) def Code_that_writes_in_CSV(handle): handle.writerow(['']) A more common arrangement is to keep all the CSV handling in a single function, and perhaps perform some calculations in a separate function. def write_to_csv(filename): with open(filename, 'w') as myfile: wr = csv.writer(myfile, quoting=csv.QUOTE_ALL) for row in code_that_calculates_a_row_at_a_time(): wr.writerow(row) The code which calculates a row at a time could return a list of rows, or usefully yield a single row at a time.
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/51967102
type: Answer

http://stackoverflow.com/comment/91161136
comment on: http://stackoverflow.com/a/52103383
score: 0
type: Comment
has text: import csv infile = 'C:\\temp\\XXX\\names.csv' outfile = 'C:\\temp\\XXX\\Testcopyx.csv' with open(infile) as rf, open(outfile, 'w+') as wf: newline='' reader = csv.DictReader(rf) writer = csv.DictWriter(wf, [*reader.fieldnames, "Count"]) # Add the new column name writer.writeheader() for count, row in enumerate(reader): row.update({"Count": count}) # update the row to have the new column writer.writerow(row)
type: AnswerComment

http://stackoverflow.com/q/52062831
has comment: http://stackoverflow.com/comment/91076355
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91076785
has body: I understand that I can add a Python docstring to an enum type as I would any other class. But how do I add documentation to an element of that type? As far as I can see there are three possibilities: class MyEnum(Enum): """ This is my enum type. """ """ Variant 1 """ a = 0, b = 1, # variant 2 c = 2, """ variant 3 """ But none of them really work consistently. If I call print(inspect.getdoc(MyEnum.a)) in any of the variants, the docstring of the MyEnum type is returned ('This is my enum type'). Pycharm can show variant 3 in its Quick Documentation preview, but includes the quotes and longer comments that exceed the column wrap will not be shown correctly. Is there a preferred way or convention on how to document Python enum elements?
downvote count: 1
score: 19
has answer: http://stackoverflow.com/a/52063239
accepted answer: http://stackoverflow.com/a/52063239
type: Question
tagged with: enums
upvote count: 20
has comment: http://stackoverflow.com/comment/91076289
answer count: 1
duplicate of: http://stackoverflow.com/q/19330460
tagged with: documentation
favorite count: 0
tagged with: python-3.x
linked to: http://stackoverflow.com/q/19330460
has comment: http://stackoverflow.com/comment/91076436
has comment: http://stackoverflow.com/comment/91076460
tagged with: python
has title: How do I properly document python enum elements?

http://stackoverflow.com/comment/91014296
has text: @atayenel I added them above
comment on: http://stackoverflow.com/q/52031907
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52038390
has comment: http://stackoverflow.com/comment/91027265
tagged with: cortana-skills-kit
has comment: http://stackoverflow.com/comment/91143961
tagged with: cortana
tagged with: python
has comment: http://stackoverflow.com/comment/91037073
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91117716
has comment: http://stackoverflow.com/comment/91117893
tagged with: cortana-intelligence
type: Question
has answer: http://stackoverflow.com/a/52038681
accepted answer: http://stackoverflow.com/a/52038681
answer count: 1
has comment: http://stackoverflow.com/comment/91143878
score: 0
has comment: http://stackoverflow.com/comment/91175344
has title: Link Cortana Alert / Notification and Python
tagged with: python-3.x
has body: I would like Python to read any Cortana Notification / Alert it receives from my mobile. Whenever my mobile receive a Message / WhatsApp, it is displayed into windows using Cortana. Now, I and would like to use this content into python, i.e., link Cortana Alert to Python. Lastly, Python would receive the text/content and run some AI scripts. Tks and have a great day

http://stackoverflow.com/q/52102138
tagged with: pyqt
answer count: 1
has body: I've been giving myself a headache trying to work with Nuke's docked panels. It works with QStackedWidgets as tabs, where the entire program is built out of it and is very dynamic. Just for the record I've been dealing with stuff like this, it works but takes a ton of trial and error to figure out: def x(self): return self.parent().parent().parent().parent().parent().parent().parent().x() def y(self): return self.parent().parent().parent().parent().parent().parent().parent().y() def closeEvent(self, event): is_docked = self.x() == self.y() == 0 num_tabs = widget.parent().parent().parent().parent().parent().parent().parent().parent().count() #Delete the window if not is_docked and num_tabs == 1: self.parent().parent().parent().parent().parent().parent().parent().parent().parent().close() #Delete the tab else: for obj in QtWidgets.QApplication.allWidgets(): if obj.objectName() == 'uk.co.thefoundry.NukeTestWindow': obj.deleteLater() event.accept() I've attempted to get full control so I can deal with callbacks at a later time, which has been a little hard as it never calls closeEvent. I can currently handle automatically closing it, and I'll be using hideEvent to read the window position, as it calls just before it closes. I have got almost all the functionality I need, but I'm still not able to catch when a user manually closes the tab. I've figured out technically how to detect if it's closed, but it only works after the function has finished. If I print out the value of self.parent().parent().parent().parent().parent().parent().parent().parent(), it says it is a widget, but if I print after the code has executed, then it equals None, so that is the level of parents to ideally check. How do I query that in hideEvent but offset the execution until after everything has finished? As far as I'm aware there's no other events being called after, I've considered threading with time.sleep, but it's not very clean and would be prone to issues. Maya had a command called evalDe…
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/52117641
tagged with: python
tagged with: qt
has title: Delay check on if widget exists
type: Question
score: 0

http://stackoverflow.com/comment/90953526
type: QuestionComment
comment on: http://stackoverflow.com/q/52001533
type: Comment
has text: @JPG maximum: Get ideal solution to store values as Decimal with large decimal places without loss in accuracy
score: 0

http://stackoverflow.com/comment/91173178
type: QuestionComment
has text: Who decides when to take the pictures? Is there a schedule, or is it ad-hoc? If the former, than set up NTP sync on the devices and use e.g. cron to have the pictures taken, without any outside interaction. If the latter, then you need some kind of messaging system. For example, the devices could listen for messages on a shared message queue.
score: 0
comment on: http://stackoverflow.com/q/52110930
type: Comment

scikit-learn
tags question: http://stackoverflow.com/q/52112414
tags question: http://stackoverflow.com/q/52003387
tags question: http://stackoverflow.com/q/52070950
tags question: http://stackoverflow.com/q/52000882
tags question: http://stackoverflow.com/q/52066886
tags question: http://stackoverflow.com/q/52093314
tags question: http://stackoverflow.com/q/52098107
tags question: http://stackoverflow.com/q/52005164
tags question: http://stackoverflow.com/q/52056640
tags question: http://stackoverflow.com/q/52004350
tags question: http://stackoverflow.com/q/52013990
tags question: http://stackoverflow.com/q/51991569
tags question: http://stackoverflow.com/q/51959321
tags question: http://stackoverflow.com/q/51959370
tags question: http://stackoverflow.com/q/52096140
tags question: http://stackoverflow.com/q/52045028
tags question: http://stackoverflow.com/q/51986706
tags question: http://stackoverflow.com/q/52069894
tags question: http://stackoverflow.com/q/52028149
tags question: http://stackoverflow.com/q/51977643
tags question: http://stackoverflow.com/q/52069821
tags question: http://stackoverflow.com/q/52078872
tags question: http://stackoverflow.com/q/52032019
tags question: http://stackoverflow.com/q/52075125
tags question: http://stackoverflow.com/q/52093388
tags question: http://stackoverflow.com/q/52096970
tags question: http://stackoverflow.com/q/52040800
tags question: http://stackoverflow.com/q/52102217
tags question: http://stackoverflow.com/q/51963174
tags question: http://stackoverflow.com/q/51968772
tags question: http://stackoverflow.com/q/52024880
tags question: http://stackoverflow.com/q/52103774
tags question: http://stackoverflow.com/q/52049346
tags question: http://stackoverflow.com/q/52002607
tags question: http://stackoverflow.com/q/52016217
tag name: scikit-learn
tags question: http://stackoverflow.com/q/52110428
tags question: http://stackoverflow.com/q/51978308
tags question: http://stackoverflow.com/q/52080028
tags question: http://stackoverflow.com/q/52054067
tags question: http://stackoverflow.com/q/51968669
tags question: http://stackoverflow.com/q/52014258
tags question: http://stackoverflow.com/q/52101779
tags question: http://stackoverflow.com/q/52057836
type: Tag
tags question: http://stackoverflow.com/q/52045877
tags question: http://stackoverflow.com/q/51982990
tags question: http://stackoverflow.com/q/52097392
tags question: http://stackoverflow.com/q/51962502
tags question: http://stackoverflow.com/q/52097663
tags question: http://stackoverflow.com/q/52055072
tags question: http://stackoverflow.com/q/52007396
tags question: http://stackoverflow.com/q/52042843
tags question: http://stackoverflow.com/q/52108019
tags question: http://stackoverflow.com/q/51968769
tags question: http://stackoverflow.com/q/52082139
tags question: http://stackoverflow.com/q/52050057
tags question: http://stackoverflow.com/q/51961033
tags question: http://stackoverflow.com/q/52005058
tags question: http://stackoverflow.com/q/52070293
tags question: http://stackoverflow.com/q/52030945
tags question: http://stackoverflow.com/q/51998226
tags question: http://stackoverflow.com/q/52046064
tags question: http://stackoverflow.com/q/52008298
tags question: http://stackoverflow.com/q/52048631
tags question: http://stackoverflow.com/q/52055722
tags question: http://stackoverflow.com/q/51988768
tags question: http://stackoverflow.com/q/52008548
tags question: http://stackoverflow.com/q/52084545
tags question: http://stackoverflow.com/q/51986414
tags question: http://stackoverflow.com/q/52094229
tags question: http://stackoverflow.com/q/52055658
tags question: http://stackoverflow.com/q/52029408
tags question: http://stackoverflow.com/q/52034043
tags question: http://stackoverflow.com/q/52060288

nested
tags question: http://stackoverflow.com/q/51989294
tag name: nested
type: Tag
tags question: http://stackoverflow.com/q/52100488
tags question: http://stackoverflow.com/q/52060788
tags question: http://stackoverflow.com/q/52081545
tags question: http://stackoverflow.com/q/52071001
tags question: http://stackoverflow.com/q/51992551
tags question: http://stackoverflow.com/q/51963134
tags question: http://stackoverflow.com/q/52095800

http://stackoverflow.com/comment/90979338
score: 0
comment on: http://stackoverflow.com/a/52014282
type: Comment
has text: Oh no wait you have team in your Profile model. It should just be Reports.objects.select_related(‘profile’).filter(team=team) where team is your team object lookup on team Id.
type: AnswerComment

http://stackoverflow.com/a/52067343
has comment: http://stackoverflow.com/comment/91085199
answers question: http://stackoverflow.com/q/52067222
has comment: http://stackoverflow.com/comment/91088445
score: 0
type: Answer
has body: You can zip the list with itself offset by one: b = [5, 6, 7, 8] c = [y-x for x, y in zip(b, b[1:])] # [1, 1, 1] Be aware that this won't recalculate values if b changes. When you change b you should also change c, or recalculate c before using it.

http://stackoverflow.com/comment/91155697
type: Comment
has text: In that case the above won't work. You may have enough memory to use subarrays of say 1000 pixels, instead of working per pixel. Some other strategies are discussed at https://stackoverflow.com/questions/3372006/incremental-median-computation-with-max-memory-efficiency
type: QuestionComment
comment on: http://stackoverflow.com/q/52102181
score: 1

http://stackoverflow.com/comment/90988340
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52019050
has text: Looks like `Widget` defines all the stuff needed to register/support the events... when not inheriting from it you don't get that functionality...

http://stackoverflow.com/a/52081754
upvote count: 4
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/52081588
has comment: http://stackoverflow.com/comment/91114347
has body: Using groupby and ffill and bfill df.groupby('code').value.ffill().bfill() 0 red 1 blue 2 yellow 3 red 4 pink 5 pink 6 blue Name: value, dtype: object
score: 4
has comment: http://stackoverflow.com/comment/91114462

http://stackoverflow.com/q/51987962
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90925543
has comment: http://stackoverflow.com/comment/90925526
tagged with: python
has comment: http://stackoverflow.com/comment/90925614
has comment: http://stackoverflow.com/comment/90925700
has comment: http://stackoverflow.com/comment/90925503
has comment: http://stackoverflow.com/comment/90926687
has title: can't install pandas in windows python 3.7?
has comment: http://stackoverflow.com/comment/90926015
type: Question
has comment: http://stackoverflow.com/comment/90925534
has answer: http://stackoverflow.com/a/51988138
score: 0
has comment: http://stackoverflow.com/comment/90926357
tagged with: pandas
has body: Due to some reasons I need to install pandas manually, I found this link: https://pandapower.readthedocs.io/en/v1.5.1/getting_started/installation_without_pip.html FYI: since I am using python 3.7, I am running command py setup.py install I also tried python setup.py install but got the same result. at the end of the install I am getting following error: Installed c:\python 3.7\lib\site-packages\pandapower-1.5.1-py3.7.egg Processing dependencies for pandapower==1.5.1 Searching for scipy Reading https://pypi.python.org/simple/scipy/ Download error on https://pypi.python.org/simple/scipy/: timed out -- Some packages may not be found! Couldn't find index page for 'scipy' (maybe misspelled?) Scanning index of all packages (this may take a while) Reading https://pypi.python.org/simple/ Download error on https://pypi.python.org/simple/: timed out -- Some packages may not be found! No local packages or working download links found for scipy error: Could not find suitable distribution for Requirement.parse('scipy') Anyhow I tried to compile a project that has import pandas and the output I get is: Traceback (most recent call last): File "Workstation Sampling.py", line 2, in &lt;module&gt; import pandas ModuleNotFoundError: No module named 'pandas' All replies are much appreciated :)
answer count: 1
has comment: http://stackoverflow.com/comment/90925466

http://stackoverflow.com/q/52059772
score: 0
possible better answer: http://stackoverflow.com/a/52059880
upvote count: 1
has answer: http://stackoverflow.com/a/52059880
downvote count: 1
type: Question
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52059840
has answer: http://stackoverflow.com/a/52059883
answer count: 3
has body: Making a simple program which responds to the user's inputs. In the example, the input "I like math", would return the response "That's cool". I want the response to change if the user inputs two items from the list, for example "I like math and biology". I decided to get this done by using the count function, but it always returns the value 0. What would I have to do to get the if response? list = ["math", "physics", "biology", "computer science"] favsub = input("What are your favorite subjects? \n") favsub = favsub.lower() favsub = favsub.split() num = favsub.count(list) if num == 2: print("Both?") else print("That's cool") The code above is a simplified example, if you want to see the actual code, I'll leave it in a google doc here.
favorite count: 0
accepted answer: http://stackoverflow.com/a/52059840
tagged with: python
has title: How to count separate items in list from input

http://stackoverflow.com/comment/91125428
type: Comment
type: QuestionComment
score: 2
has text: We would need to know what is being passed to the function (i.e. the value of `grid`).
comment on: http://stackoverflow.com/q/52087567

http://stackoverflow.com/a/51999536
type: Answer
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/51999427
downvote count: 0
has body: If write NaNs values to file in pandas they are converted to empty strings. So it seems your values are not missing values, but strings. So need parameters keep_default_na=False, na_values=['Naan'] for convert them to NaNs and then: data = data.fillna('') Or replace: data = pd.read_csv('iso_country_continent.csv') data = data.replace({'Naan':''}) But if empty values in csv need parameter keep_default_na=False only, but no values are converted to NaN. Or specify values to converting by keep_default_na=False, na_values=['NaN']
has comment: http://stackoverflow.com/comment/90948404

http://stackoverflow.com/comment/91141198
score: 0
type: Comment
type: QuestionComment
has text: Possible duplicate of [Plotting a line over several graphs](https://stackoverflow.com/questions/6146290/plotting-a-line-over-several-graphs)
comment on: http://stackoverflow.com/q/52095337

http://stackoverflow.com/q/52089869
linked to: http://stackoverflow.com/q/52495824
tagged with: python
has comment: http://stackoverflow.com/comment/92339094
has body: I need to write two programs which will be run as a parent process and its child. The parent process spawns the child and then they communicate via pair of pipes connected to child's stdin and stdout. The communication is peer-to-peer, that's why I need asyncio. A simple read/reply loop won't do. I have written the parent. No problem because asyncio provides everything I needed in create_subprocess_exec(). However I don't know how to create a similar stream reader/writer in the child. I did not expect any problems. because the pipes are already created and file descriptors 0 and 1 are ready to use when the child process starts. No connection is to be open, no process needs to be spawned. This is my not working attempt: import asyncio import sys _DEFAULT_LIMIT = 64 * 1024 async def connect_stdin_stdout(limit=_DEFAULT_LIMIT, loop=None): if loop is None: loop = asyncio.get_event_loop() reader = asyncio.StreamReader(limit=limit, loop=loop) protocol = asyncio.StreamReaderProtocol(reader, loop=loop) r_transport, _ = await loop.connect_read_pipe(lambda: protocol, sys.stdin) w_transport, _ = await loop.connect_write_pipe(lambda: protocol, sys.stdout) writer = asyncio.StreamWriter(w_transport, protocol, reader, loop) return reader, writer The problem is I have two transports where I should have one. The function fails, because it tries to set the protocol's transport twice: await loop.connect_read_pipe(lambda: protocol, sys.stdin) await loop.connect_write_pipe(lambda: protocol, sys.stdout) # !!!! assert self._transport is None, 'Transport already set' I tried to pass a dummy protocol to the first line, but this line is not correct either, because both transports are needed, not just one: writer = asyncio.StreamWriter(w_transport, protocol, reader, loop) I guess I need to combine two unidirectional transports to one bidirectional somehow. Or is my approach entirely wrong? Could you please give me some advice? UPDATE: after some test this seems to work (but does not look good …
has comment: http://stackoverflow.com/comment/92335624
has comment: http://stackoverflow.com/comment/92332147
has comment: http://stackoverflow.com/comment/103371952
has comment: http://stackoverflow.com/comment/92306236
type: Question
linked to: http://stackoverflow.com/q/52219672
has comment: http://stackoverflow.com/comment/91389055
upvote count: 20
has comment: http://stackoverflow.com/comment/99287412
linked to: http://stackoverflow.com/q/31510190
score: 20
has comment: http://stackoverflow.com/comment/92332125
has comment: http://stackoverflow.com/comment/92337494
downvote count: 0
answer count: 1
has answer: http://stackoverflow.com/a/52702646
has comment: http://stackoverflow.com/comment/112618770
favorite count: 0
tagged with: python-asyncio
has title: How to create asyncio stream reader/writer for stdin/stdout?
type: UnansweredQuestion

http://stackoverflow.com/comment/90891977
type: QuestionComment
comment on: http://stackoverflow.com/q/51970529
has text: sorry for being vague.I am using BeautifulSoup and after finding the text, it gave me a paragraph. i want to cut the paragraph starting from a unique string up to the last string in the list.
score: 0
type: Comment

http://stackoverflow.com/comment/91098393
comment on: http://stackoverflow.com/a/52071147
type: AnswerComment
has text: actually, try one of these `pip install configparser` or `pip3 install configparser` if those don't work try `pip install ConfigParser` or `pip3 install ConfigParser`. Also, if you think my answer to be sufficient please select it as the best answer.
type: Comment
score: 0

http://stackoverflow.com/q/52053693
favorite count: 0
has title: Persist an object to either local file system or to S3
type: UnansweredQuestion
has body: I need a method which persists an object (model) to either local file system or to an S3 bucket. The destination is determined by the environment variable MODELS_DIR. I have two versions where the first is a little longer and I am rather confident about its correctness. The second version is shorter, but I am worried that not using the with statement is actually wrong. def persist_model(model, model_name): """ VERSION 1 Persist `model` under the name `model_name` to the environment variable `MODELS_DIR` (having a trailing '/'). """ MODELS_DIR = os.getenv('MODELS_DIR') if MODELS_DIR.startswith('s3://'): s3 = s3fs.S3FileSystem() with s3.open(MODELS_DIR[5:] + model_name, 'wb') as f: joblib.dump(model, f) else: with open(MODELS_DIR + model_name, 'wb') as f: joblib.dump(model, f) and: def persist_model(model, model_name): """VERSION 2 Persist `model` under the name `model_name` to the environment variable `MODELS_DIR` (having a trailing '/'). """ MODELS_DIR = os.getenv('MODELS_DIR') if MODELS_DIR.startswith('s3://'): s3 = s3fs.S3FileSystem() f = s3.open(MODELS_DIR[5:] + model_name, 'wb') else: f = open(MODELS_DIR + model_name, 'wb') joblib.dump(model, f) My question is whether the second version is safe to use?
tagged with: python
score: 2
upvote count: 2
type: Question
tagged with: amazon-s3
has answer: http://stackoverflow.com/a/52096181
answer count: 1
downvote count: 0

http://stackoverflow.com/comment/91036917
type: Comment
has text: Yes, I used it in view file as href link. I will try to follow your suggestion, but I am very surprised that there is no less expensive solution
comment on: http://stackoverflow.com/a/52041675
score: 0
type: AnswerComment

http://stackoverflow.com/a/52062681
has comment: http://stackoverflow.com/comment/92269435
accepted answer of: http://stackoverflow.com/q/52062560
answers question: http://stackoverflow.com/q/52062560
upvote count: 4
has comment: http://stackoverflow.com/comment/91076031
type: AcceptedAnswer
downvote count: 0
has body: You can use advanced indexing: index = np.array([0,1,2]) matrix = np.array([[1,4,7],[2,5,8],[3,6,9]]) res = matrix[np.arange(matrix.shape[0]), index] # array([1, 5, 9]) For your second example, reverse your indices: index = np.array([0,1,1]) matrix = np.array([[1,4,7],[2,5,8],[3,6,9]]) res = matrix[index, np.arange(matrix.shape[1])] # array([1, 5, 8])
has comment: http://stackoverflow.com/comment/92269362
has comment: http://stackoverflow.com/comment/91076088
type: Answer
score: 4

http://stackoverflow.com/q/51968628
has title: Openpyxl comparing values in two sheets to see if a value does not exist
tagged with: excel
type: Question
has answer: http://stackoverflow.com/a/52019085
accepted answer: http://stackoverflow.com/a/52019085
has body: I am making an excel comparing program that takes a certain amount of sheets, compares them and checks to see if the values in one of the sheets do not exist in the other. However, I am receiving a repetitive problem. To clarify, here is my code: import tkinter as tk from tkinter import filedialog import openpyxl, os, csv from openpyxl.utils import get_column_letter, column_index_from_string # Output File outputFile = open('output.csv','w',newline='') outputWriter = csv.writer(outputFile) # Tk initialization for file dialog root = tk.Tk() root.withdraw() # Number of sheets to be compared number = input('Enter number of workbook sheets for comparison: ') number = int(number) # Functions for generating file paths def generate_file_path(): file_path = filedialog.askopenfilename(title="Open Workbook") return file_path # Variables to store file paths, workbooks and worksheets all_ws = [] # Core function for program's logistics def core(): # for loops for generating file paths, workbooks and worsheets for x in range(number): path = generate_file_path() wb = openpyxl.load_workbook(path) ws = wb['CBF'] all_ws.append(ws) # for loop to use for finding diff for row in all_ws[1].iter_cols(): for cellz in row: sheet_cols.append(cellz.value) # loop that checks if the value does not exist for ws_diff in range(number): for row,row2 in zip(all_ws[0].iter_cols(),all_ws[1].iter_cols()): for cell,cell2 in zip(row,row2): if cell.value not in sheet_cols: outputWriter.writerow([str(cell2.value)]) However, when I check my csv file, the "differences" outputted appear to be on both of the files. Does anyone have any suggestions for helping me out? Anything would be great thank you
answer count: 2
possible better answer: http://stackoverflow.com/a/52018332
score: 4
has comment: http://stackoverflow.com/comment/90910646
has answer: http://stackoverflow.com/a/52018332
favorite count: 0
tagged with: python
upvote count: 6
has comment: http://stackoverflow.com/comment/90901630
type: AnsweredQuestion
downvote count: 2
tagged with: openpyxl

http://stackoverflow.com/q/52030127
score: 0
answer count: 1
has comment: http://stackoverflow.com/comment/91010698
has comment: http://stackoverflow.com/comment/91011053
accepted answer: http://stackoverflow.com/a/52030230
tagged with: python-3.x
has body: I thought the following code would work the way I expcted. p1 = [ ({1}, (0,0)), ({2}, (0,0)), ({3},(0,0), ] p2 = [ ({1,2}, (1,0)), ({3}, (0,0)), ] for k in range(len(p1)): m = set() for l in range(len(p2)): if p1[k] != p2[l]: m = m.union( set([min(p1[k][0])])) print(m) What I should be getting is {1,2}, but I get Set([1]) Set([2]) I also get an error message saying: 'set' object does not support indexing and I don't know if I should be using some other command. I am real grateful for any help I can get. I have thought about it for some time and have not been able to fix this.
has comment: http://stackoverflow.com/comment/91010761
tagged with: python
has comment: http://stackoverflow.com/comment/91010711
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91010666
tagged with: set
type: Question
has comment: http://stackoverflow.com/comment/91010902
has answer: http://stackoverflow.com/a/52030230
tagged with: unions
has title: Index over a set, I get two sets and not one
has comment: http://stackoverflow.com/comment/91010920

http://stackoverflow.com/q/52047383
answer count: 0
duplicate of: http://stackoverflow.com/q/15112125
downvote count: 0
type: UnansweredQuestion
score: 1
has title: Tic-Tac-Toe Winnner determiner?
type: Question
has body: Hello I have simple code here to determine if there is a win in a tic-tac-toe game. I am having trouble getting the condition right to determine a win. board = [['7', '8', '9'], ['4', '5', '6'], ['1', '2', '3']] the top row is 7,8,9 the middle 4,5,6 and the bottom 1,2,3 I wrote a if statement to detect when a winner of 'X' or 'O' has been determined. if ('X' == (board[0][0] and board[0][1] and board[0][2])) or ('O' == (board[0][0] and board[0][1] and board[0][2])): return True elif ('X' == (board[1][0] and board[1][1] and board[1][2])) or ('O' == (board[1][0] and board[1][1] and board[1][2])): return True elif ('X' == (board[2][0] and board[2][1] and board[2][2])) or ('O' == (board[2][0] and board[2][1] and board[2][2])): return True elif ('X' == (board[0][0] and board[1][0] and board[2][0])) or ('O' == (board[0][0] and board[1][0] and board[2][0])): return True elif ('X' == (board[0][1] and board[1][1] and board[2][1])) or ('O' == (board[0][1] and board[1][1] and board[2][1])): return True elif ('X' == (board[0][2] and board[1][2] and board[2][2])) or ('O' == (board[0][2] and board[1][2] and board[2][2])): return True elif ('X' == (board[0][0] and board[1][1] and board[2][2])) or ('O' == (board[0][0] and board[1][1] and board[2][2])): return True elif ('X' == (board[0][2] and board[1][1] and board[2][0])) or ('O' == (board[0][2] and board[1][1] and board[2][0])): return True else: return False I would like for the conditions to return True if all three of the Boards are full of either X's or O's. Sorry for the repeat question notice, I have rewrote the if statements again and wish someone could explain what I have done wrong here. At this moment I am having lot's of issues writing these conditionals and any explanation would be much appreciated. -Thanks
upvote count: 1
has comment: http://stackoverflow.com/comment/91045796
has comment: http://stackoverflow.com/comment/91045810
linked to: http://stackoverflow.com/q/15112125
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/91048085
tagged with: python

http://stackoverflow.com/q/52073685
has comment: http://stackoverflow.com/comment/91126527
score: 0
has title: how to speed up the computation of the sparse matrix in python
has body: Recently, i have the problem of speeding up the computation of the sparse matrix in python. Now, the dimension of the W is [17000, 2] and b is [1,2]. And when others use the web service i will compute the xW + b, where the dimension of the x is [1, 17000]. But what confuse me is when i do the pressure test with ab command, if the Concurrency is lower than 100 per second, then it can operate it with 0.002 ms, but if Concurrency pass that limit, the cost time will fly to 4 ms, i want to know what happen in this procedure. P.S. all the relevant matrices are sparse matrices
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/91120978
answer count: 0
tagged with: scipy
type: Question

http://stackoverflow.com/a/52019262
score: 3
answers question: http://stackoverflow.com/q/52019192
downvote count: 0
upvote count: 3
type: AcceptedAnswer
type: Answer
accepted answer of: http://stackoverflow.com/q/52019192
has body: In Python 3, dict.items() (and also .keys() and .values()) returns a special dictionary view object. It behaves like an iterator, but isn't specifically a list. #!/usr/bin/env python3 d = {} d['a'] = 1 d['b'] = 2 # You can pack items() into a list and then it's a "real" list l = list(d.items()) print(repr(l[1])) # Or you can use itertools or otherwise use it as a plain iterator import itertools for p in itertools.islice(d.items(), 1, 2): print(repr(p))

http://stackoverflow.com/a/52020081
accepted answer of: http://stackoverflow.com/q/52019713
has comment: http://stackoverflow.com/comment/90992276
type: AcceptedAnswer
upvote count: 3
type: Answer
has body: Your current code is appending a generator expression to the neighbors list. I'm pretty sure you want to be appending actual nodes, not generators. Further, since the generators are closures (don't worry too much if you don't know what this means), you may be doing your calculation wrong when it comes to deciding which nodes to append. I'd suggest making a second explicit loop, rather than using any generator expressions, and turn all the if clauses you have in the generator expressions into parts of the condition in one if statement. That would look something like this: for node in nodes: for n in nodes: if (n.x == node.x - 1 and n.y == node.y or n.x == node.x + 1 and n.y == node.y or ...): node.neighbours.append(n) I haven't copied over all the conditions, but you can do that, just connecting them with or. You might be able to group some of the conditions, if you wanted to streamline things (e.g. you could test n.x == node.x - 1 and node.y - 1 &lt;= n.y &lt;= node.y + 1 rather than using three different tests for the different y values).
downvote count: 0
has comment: http://stackoverflow.com/comment/90990619
answers question: http://stackoverflow.com/q/52019713
score: 3

http://stackoverflow.com/q/51991048
tagged with: matplotlib
type: Question
has answer: http://stackoverflow.com/a/51991139
answer count: 1
has body: My imports : from pydub import AudioSegment import matplotlib.pyplot as plt import numpy as np import wave import sys why am i getting that error while i'm clearly not importing tkinter and how to fix it
score: 0
has title: ImportError: No module named '_tkinter'?
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/51991139
tagged with: tkinter
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/a/53405720
has comment: http://stackoverflow.com/comment/100728473
has body: I had this exact issue with a Logitech wide angle in windows camera and I was wondering about a driver problem. So I solved it using the DirectShow driver instead of the native driver using this: cv2.VideoCapture(cv2.CAP_DSHOW) If you have more than one camera add the index to that value like this cv2.VideoCapture(cv2.CAP_DSHOW + camera_index) It will accept the desired resolution by applying the right aspect ratio without having the sidebars.
type: Answer
upvote count: 9
downvote count: 0
answers question: http://stackoverflow.com/q/52043671
score: 9
has comment: http://stackoverflow.com/comment/98108592

http://stackoverflow.com/q/52081602
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/91116746
answer count: 0
has body: I need to email a pdf and a generic cover letter from a file directory to a an email address that matches the 5 digit code. the code can be found in the first 5 of the pdf name and then the corresonding dataframe that contains the 5 digit code and email address. Is there an easy way to accomplish this? Thanks # loop through the email list for i in email_list.itertuples(): PDF_name = i.AGCODE + '_2017 Net_Initial.pdf' cover_letter_name = 'CoverLetter.pdf' print(PDF_name) #attach an excel file and PDF file: with open(dir_path + PDF_name, 'rb') as f, open(dir_path + cover_letter_name, 'rb') as g: # Read the binary file contents PDF_content = f.read() cl_content = g.read() PDF_att = FileAttachment(name=PDF_name, content=PDF_content) cl_att = FileAttachment(name=cover_letter_name, content=cl_content) # if you want a copy in the 'Sent' folder m = Message( account=a ,folder=a.sent ,subject=('Award Letter for ' + i.FACILITY_NAME + ' -- Agency Code: ' + i.AGCODE) ,body = body_of_email ,to_recipients=[Mailbox(email_address=i.FAC_EMAIL_ADDR)]) #attach files m.attach(cl_att) m.attach(PDF_att) # send email each time m.send_and_save() #========================
tagged with: loops
type: Question
has comment: http://stackoverflow.com/comment/91140898
has title: Python Email PDF from file Directory
tagged with: if-statement
score: 0
has comment: http://stackoverflow.com/comment/91716474
tagged with: exchangelib

http://stackoverflow.com/comment/91112319
score: 0
type: Comment
type: QuestionComment
has text: I fixed indents.
comment on: http://stackoverflow.com/q/52080892

http://stackoverflow.com/q/51992452
has comment: http://stackoverflow.com/comment/90934666
has comment: http://stackoverflow.com/comment/90934664
has answer: http://stackoverflow.com/a/51993362
type: AnsweredQuestion
has title: How to remove this extra trailing space at the end of each line in python3
accepted answer: http://stackoverflow.com/a/51993362
has comment: http://stackoverflow.com/comment/90934757
type: Question
has comment: http://stackoverflow.com/comment/90934634
answer count: 1
has comment: http://stackoverflow.com/comment/90934988
score: 0
tagged with: python
has body: I am trying to print this pattern using print() function in python3. 0 0 1 0 0 1 2 1 0 0 1 2 3 2 1 0 0 1 2 1 0 0 1 0 0 the following are the two ways I implemented this. numeric approach limit = int(input()) space = ' ' for i in range(0, limit + 1): print(space * (limit - i), end='') for j in range(2 * i + 1): if j &gt; i: print(i - (j - i), end=' ') else: print(j, end=" ") print() for i in range(0, limit)[::-1]: print(space * (limit - i), end='') for j in range(2 * i + 1)[::-1]: if j &gt; i: print(i - (j - i), end=' ') else: print(j, end=" ") print() string and list comprehension approach gap = ' ' y = int(input()) y = y + 1 for n in range(1, y + 1): str1 = ' '.join(str(e) for e in list(range(n))) str2 = ' '.join(str(e) for e in list(range(n - 1))[::-1]) print(gap * (y - n) + str1 + " " + str2.strip()) for n in range(1, y)[::-1]: str1 = ' '.join(str(e) for e in list(range(n))) str2 = ' '.join(str(e) for e in list(range(n - 1))[::-1]) print(gap * (y - n) + str1 + " " + str2.strip()) the pattern is printing right but when I am submitting this to online judge it do not accept. wrong answer 1st lines differ - expected: ' 0', found: ' 0 ' it expects to remove that extra space after the 0. PROBLEM: In both of the code snippet I am unable to remove the last line extra space. I do not know how to achieve this Pattern and also not to have that extra space after the number at the end of each line.
tagged with: python-3.x

http://stackoverflow.com/comment/90904185
comment on: http://stackoverflow.com/a/51976983
has text: Thank you, PixelEinstein. What if crawler keeps visiting and grabbing data in a same website from page1 to page10 step by step, DOWNLOAD_DELAY is still delay or stop 2 seconds for every different page?
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/91006571
has text: Possible duplicate of [Error after upgrading pip: cannot import name 'main'](https://stackoverflow.com/questions/49836676/error-after-upgrading-pip-cannot-import-name-main)
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52002684

django-forms
tags question: http://stackoverflow.com/q/52094771
tags question: http://stackoverflow.com/q/52099275
tags question: http://stackoverflow.com/q/52066617
tags question: http://stackoverflow.com/q/51970096
tags question: http://stackoverflow.com/q/52051802
tags question: http://stackoverflow.com/q/51978965
tags question: http://stackoverflow.com/q/52095333
tags question: http://stackoverflow.com/q/51959369
tags question: http://stackoverflow.com/q/52065182
tags question: http://stackoverflow.com/q/52054246
tags question: http://stackoverflow.com/q/52096043
tags question: http://stackoverflow.com/q/52104746
tags question: http://stackoverflow.com/q/51984225
tag name: django-forms
type: Tag
tags question: http://stackoverflow.com/q/51962003
tags question: http://stackoverflow.com/q/52097001
tags question: http://stackoverflow.com/q/51976534
tags question: http://stackoverflow.com/q/52076330
tags question: http://stackoverflow.com/q/52099529
tags question: http://stackoverflow.com/q/52091908
tags question: http://stackoverflow.com/q/52017598
tags question: http://stackoverflow.com/q/52054446
tags question: http://stackoverflow.com/q/52107256
tags question: http://stackoverflow.com/q/52096073
tags question: http://stackoverflow.com/q/52021136
tags question: http://stackoverflow.com/q/51967671

http://stackoverflow.com/comment/90956062
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52003436
score: 5
has text: What you are looking for are [Uniforms](https://www.opengl.org/sdk/docs/tutorials/ClockworkCoders/uniform.php). You usually don't compile new shader for changing the viewport or the color. Side note: What should `gl_Position[3] += 3` do? Setting the homogeneous coordinate looks very wrong.

http://stackoverflow.com/q/52048071
has comment: http://stackoverflow.com/comment/91047039
has answer: http://stackoverflow.com/a/52048144
favorite count: 0
has answer: http://stackoverflow.com/a/52048161
has title: Does addition not work properly if used on indexes?
has comment: http://stackoverflow.com/comment/91047213
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91047022
has body: I'm new to python, coding generally and while doing a specific project I got stuck here : Guess_1 = input() Number_2 = input() Set_dead_1 = set() def teste_dead_1(): index_1 = 0 while index_1 &lt;= 3: if Guess_1[index_1] == Number_2[index_1]: Set_dead_1.add(Number_2[index_1]) else: pass for i in Set_dead_1: print(i, "is dead.") index_1 += 1 teste_dead_1() For further explanation I am trying to compare each char of each string and if it is a match type that char "is dead." but the problem is when I execute my program and insert the numbers, something like this pops up: &gt;1234 1234 1 is dead 2 is dead 1 is dead 3 is dead 2 is dead 1 is dead 4 is dead 3 is dead 2 is dead 1 is dead But I want it to write : &gt;1 is dead 2 is dead 3 is dead 4 is dead Thanks for your comprehension! PS: the two 1234s are the one I typed
accepted answer: http://stackoverflow.com/a/52048161
downvote count: 1
type: Question
upvote count: 0
score: -1
answer count: 2
has comment: http://stackoverflow.com/comment/91046979
possible better answer: http://stackoverflow.com/a/52048144

http://stackoverflow.com/q/51996247
has comment: http://stackoverflow.com/comment/90942038
has body: When I look at python code I see two styles of handling variables in python. pass all variables. Example #initialize variable1 = 1 variable2 = 1 variable3 = 1 def recursive(variable1, variable2, variable3): do stuff with variables recursive(variable1, variable2, variable3) if a variable doesn't need a separate instance inside the function, just make it global example #initialize variable1 = 1 global variable2 variable2 = 1 global variable3 variable3 = 1 def recursive(variable1): global variable2 global variable3 do stuff variables recursive(variable1) Are there any advantages to either style? Is one more 'pythonic' than the other?
type: Question
has title: Python Recursion: Are there any advantages to passing all variables vs just declaring a global variable and re-declaring in the function?
accepted answer: http://stackoverflow.com/a/51996266
answer count: 1
has comment: http://stackoverflow.com/comment/90942153
has comment: http://stackoverflow.com/comment/90942544
tagged with: python
score: 0
has answer: http://stackoverflow.com/a/51996266
type: AnsweredQuestion

web-deployment
tags question: http://stackoverflow.com/q/52096527
tag name: web-deployment
type: Tag

http://stackoverflow.com/comment/91096606
has text: If you run `print(chnum('kkikkd'))` with your answer code, you will notice that it does not produce the required result.
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52073266

http://stackoverflow.com/q/52096226
tagged with: python
has title: Create image using tensorflow
answer count: 0
type: UnansweredQuestion
tagged with: tensorflow
type: Question
has body: Is there any way to create image through input pixel values by using tensorflow functions? I don't mean to generate images like some people did that by applying generative models. Some functions like "crop_to_bounding_box()" or "extract_image_patches()" which listed in https://www.tensorflow.org/api_docs/python/tf just working on existed images, but I want something helps me create a new image out of overlapping patches with arbitrary size and pixel values.
score: 0
has comment: http://stackoverflow.com/comment/91143226
has comment: http://stackoverflow.com/comment/91146068

http://stackoverflow.com/comment/90932040
has text: Add minimal sample data and expected output?
type: QuestionComment
comment on: http://stackoverflow.com/q/51991001
score: 0
type: Comment

http://stackoverflow.com/a/54953251
score: 1
upvote count: 1
has body: Replace python \n with &lt;br&gt; for HTML
accepted answer of: http://stackoverflow.com/q/52087954
type: AcceptedAnswer
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/52087954

http://stackoverflow.com/comment/90875122
has text: No I was wrong, answer to follow!
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51962229

http://stackoverflow.com/a/52023473
answers question: http://stackoverflow.com/q/52023384
has body: When you do for k in (i-m,i): you don't iterate in a range, but k only takes 2 values: i-1 and m. Same for the line for i in (0,n,m):. You also get uncorrect results because you never check in the last block. Indeed even by doing for i in range(0, n, m): you will stop when i + m >= n, so you have to check in the last part to be sure that the element is not there. def jumpsearch(array, x): n=len(array) m=int(math.sqrt(n)) if array[0] &gt; x: return -1 for i in range(0, n, m): if array[i] == x: return i elif x &lt; array[i]: for k in range(i-m, i): if array[k]==x: return k else: return -1 for j in range(i+1,n): if array[j] == x: return j else: return -1
has comment: http://stackoverflow.com/comment/91010144
score: 0
type: Answer

http://stackoverflow.com/a/52049473
upvote count: 2
accepted answer of: http://stackoverflow.com/q/52049335
type: Answer
answers question: http://stackoverflow.com/q/52049335
score: 2
has body: You can get it a bit easier by using some .stacks and .unstacks to regroup things: n [96]: df = df.unstack().unstack(1) In [97]: df Out[97]: False Negative False Positive True Positive company1 April- 2012 112.0 0.0 0.0 April- 2013 370.0 544.0 140.0 April- 2014 499.0 50.0 24.0 August- 2012 431.0 0.0 0.0 August- 2013 496.0 0.0 0.0 August- 2014 221.0 426.0 77.0 company2 April- 2012 112.0 0.0 0.0 April- 2013 370.0 544.0 140.0 April- 2014 499.0 50.0 24.0 August- 2012 431.0 0.0 0.0 August- 2013 496.0 0.0 0.0 August- 2014 221.0 426.0 77.0 In [98]: df['SUM'] = df.sum(axis=1) In [99]: df['FSUM'] = df['False Negative'] + df['False Positive'] In [100]: df = df.stack().unstack([0,2]) In [101]: df Out[101]: company1 \ False Negative False Positive True Positive SUM FSUM April- 2012 112.0 0.0 0.0 112.0 112.0 April- 2013 370.0 544.0 140.0 1054.0 914.0 April- 2014 499.0 50.0 24.0 573.0 549.0 August- 2012 431.0 0.0 0.0 431.0 431.0 August- 2013 496.0 0.0 0.0 496.0 496.0 August- 2014 221.0 426.0 77.0 724.0 647.0 company2 False Negative False Positive True Positive SUM FSUM April- 2012 112.0 0.0 0.0 112.0 112.0 April- 2013 370.0 544.0 140.0 1054.0 914.0 April- 2014 499.0 50.0 24.0 573.0 549.0 August- 2012 431.0 0.0 0.0 431.0 431.0 August- 2013 496.0 0.0 0.0 496.0 496.0 August- 2014 221.0 426.0 77.0 724.0 647.0
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/52096582
answer count: 3
linked to: http://stackoverflow.com/q/1155008
favorite count: 0
has comment: http://stackoverflow.com/comment/91143561
has comment: http://stackoverflow.com/comment/91143312
tagged with: python-3.x
possible better answer: http://stackoverflow.com/a/52096647
tagged with: python
has comment: http://stackoverflow.com/comment/91143703
has answer: http://stackoverflow.com/a/52096647
has comment: http://stackoverflow.com/comment/91143420
has comment: http://stackoverflow.com/comment/91143505
has answer: http://stackoverflow.com/a/52181584
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/52181584
tagged with: memory
downvote count: 1
tagged with: unit-testing
upvote count: 17
type: Question
has body: tl;dr Does Python reuse ids? How likely it is that two objects with non overlapping lifetime will get the same id? Background: I've been working on a complex project, written purely in Python 3. I've been seeing some issues in testing and spent a lot of time searching for a root cause. After some analysis, my suspicion was that when the testing is being run as a whole (it's orchestrated and being run by a dedicated dispatcher) it's reusing some mocked methods instead of instatiating new objects with their original methods. To check if the interpreter is reusing I used id(). Problem: id() usually works and shows the object identifier and lets me tell when my call is creating a new instance and not reusing. But what happens when ids if two objects are the same? The documentation says: Return the “identity” of an object. This is an integer which is guaranteed to be unique and constant for this object during its lifetime. Two objects with non-overlapping lifetimes may have the same id() value. The questions: When can the interpreter reuse id() values? Is it just when it randomly selects the same memory area? If it's just random, it seems extremely unlikely but it's still not guaranteed. Is there any other method to check what object I am actually referencing? I encountered a situation where I had the object, it had a mocked method. The object was no longer used, garbage collector destroyed it. After that I create a new object of the same class, it got a new id() but the method got the same id as when it was mocked and it actually was just a mock. Is there a way to force Python to destroy the given object instance? From the reading I did it appears that no and that it is up to a garbage collector when it sees no references to the object but I thought it's worth asking anyway.
has answer: http://stackoverflow.com/a/52096694
has comment: http://stackoverflow.com/comment/91143440
has comment: http://stackoverflow.com/comment/91143304
score: 16
has title: How unique is Python's id()?

http://stackoverflow.com/q/52065249
tagged with: tkinter
type: AnsweredQuestion
tagged with: python-imaging-library
has answer: http://stackoverflow.com/a/52065375
type: Question
score: 0
has comment: http://stackoverflow.com/comment/91081239
has body: Lets say I would like to open a new completely white image in tkinter in Python without already having saved the image to my drive. How would I go about doing this?
has title: How to create open a new image in tkinter without previously saving image to drive?
answer count: 1
accepted answer: http://stackoverflow.com/a/52065375
tagged with: python

http://stackoverflow.com/a/52061742
type: Answer
answers question: http://stackoverflow.com/q/52061293
has body: Result of a list call return an iterable, so first you would have to consume this iterable as a list. Then, each object will contain a serialize method that will put back the object into its JSON form. In practical terms: client = CompteManagementClient(credentials, subscription_id) vmSizesList = [vm_size.serialize() for vm_size in client.virtual_machine_sizes.list()] json.dumps(vmSizesList)
upvote count: 4
downvote count: 0
score: 4

http://stackoverflow.com/a/52013757
has body: The operator module provides the various comparators as functions, so you could map from string form to a function to perform the comparison: import operator class Condition: cmp_to_op = {'==': operator.eq, '!=': operator.ne, '&lt;': `operator.lt, '&lt;=': `operator.le, '&gt;': `operator.gt, '&gt;=': `operator.ge} def __init__(self, value1, operator, value2): self.value1 = value1 self.operator = self.cmp_to_op(operator) self.value2 = value2 def test(self): # No need for if return True else return False; comparison already returns # True or False for normal objects return self.operator(self.value1, self.value2)
type: Answer
upvote count: 1
answers question: http://stackoverflow.com/q/52013706
downvote count: 0
score: 1

pca
tag name: pca
type: Tag
tags question: http://stackoverflow.com/q/52101779

http://stackoverflow.com/comment/91156474
comment on: http://stackoverflow.com/q/52102744
score: 0
type: QuestionComment
type: Comment
has text: Hi Shan, welcome to SO! A few suggestions so that you get better response. 1) "I've searched everywhere" - if you could include a few of your results from that search ("what you've tried"), then that helps us a lot. 2) Thank you for providing your code! A big improvement, IMO, would be to make it "minimal", and to tell us what it does and what you want it to do. That's a *very* big code dump for something simple like alphabetizing. 3) Have you tried the built-in "sorted" function?

http://stackoverflow.com/comment/90950320
type: Comment
has text: I believe the selector is not correct because it says it can't find the location
comment on: http://stackoverflow.com/a/51985365
type: AnswerComment
score: 0

http://stackoverflow.com/comment/91215260
type: QuestionComment
type: Comment
has text: Added colums_rule too in the question. Please do let me know of your suggestions that I can perform on my data and share the results with you. Thanks for your interest in my question.
score: 0
comment on: http://stackoverflow.com/q/52092284

http://stackoverflow.com/a/52032833
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/52032714
upvote count: 1
has comment: http://stackoverflow.com/comment/91017272
has body: Shorter alternative: [{baz['id']: {quux['takenid']: quux['lib']}} for foo in d for k, v in foo.items() for bar in v for kk, vv in bar.items() for baz in vv if 'library' in baz and baz['library'] for quux in baz['library'] ] # =&gt; [{'1': {'2': 'man'}}, {'3': {'0': 'woman'}}, {'3': {'1': 'ghost'}}, {'3': {'4': 'monster'}}] Here, if 'library' in baz and baz['library'] will check that the library key exists and is not empty.
type: Answer

http://stackoverflow.com/q/51960468
favorite count: 0
score: 0
upvote count: 1
downvote count: 1
tagged with: python-3.x
tagged with: telegram
type: UnansweredQuestion
tagged with: python
has body: I have the following API call point: iostCall = "https://min-api.cryptocompare.com/data/price?fsym=IOST&amp;tsyms=USD,JPY,EUR" I want to concatenate an input from my telegram user at (IOST). this is what I have currently wrote but i have to hard code each call to the api. def test (bot, update, args): params = { 'fsym' : fsym } testCall = "https://min-api.cryptocompare.com/data/price" testJson = requests.get(testCall, params=params) testOut = testJson update.message.reply_text(testOut) and this is what sends the command to the telegram api. basically, my script waits till a user calls /test (inputs a coin name)... for example: /test btc dp.add_handler(CommandHandler("test", test, pass_args=True)) sends it to my user.
tagged with: bots
type: Question
has answer: http://stackoverflow.com/a/51960531
answer count: 1
has title: how to change api call destination based on user input?(python)
has comment: http://stackoverflow.com/comment/90871251

http://stackoverflow.com/a/52061407
has comment: http://stackoverflow.com/comment/91073255
has comment: http://stackoverflow.com/comment/91073689
has body: It is easiest to traverse the structure recursively with a generator: def flatten_forest(forest, write=True): def flatten(d, seen = None): for a, b in d.items(): if seen is None: yield ('ROOT', a) else: yield (seen, a) if b: yield from flatten(b, a) if write: with open('full_flattened_tree.txt', 'a') as f: f.write(' '.join(map(str, flatten(forest)))+'\n') data = {'a': {'b': {'c': {'x': {}}, 'd': {'p': {}}}, 'g': {}, 'f': {}}, 't': {'r': {'o': {}}, 'y': {}}} for i in data.values(): flatten_forest(i) File output: ('ROOT', 'b') ('b', 'c') ('c', 'x') ('b', 'd') ('d', 'p') ('ROOT', 'g') ('ROOT', 'f') ('ROOT', 'r') ('r', 'o') ('ROOT', 'y') This will work on large dictionaries: import random, string, time def create_structure(_len, _depth = 5, _count = 0): return {string.ascii_lowercase[i]:{} if _depth == _count else create_structure(random.randint(1, 26), _count = _count + 1) for i in range(_len)} d = create_structure(26) c = time.time() flatten_forest(d, write=True) print(time.time()-c) Output: 11.871491193771362
has comment: http://stackoverflow.com/comment/91073115
has comment: http://stackoverflow.com/comment/91073311
score: 0
has comment: http://stackoverflow.com/comment/91073426
has comment: http://stackoverflow.com/comment/91073112
has comment: http://stackoverflow.com/comment/91073476
answers question: http://stackoverflow.com/q/52060788
type: Answer
has comment: http://stackoverflow.com/comment/91073355

http://stackoverflow.com/a/51997684
answers question: http://stackoverflow.com/q/51996701
upvote count: 1
score: 1
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51996701
type: Answer
has body: I realized the problem is with permission. I found a way around it that can solve the problem. I fixed it by changing the permission for in site-packages directory as follows: sudo chmod -R o+r scipy sudo chmod -R o+r numpy If there is a sophisticated solution for this problem, please feel free to post it.

http://stackoverflow.com/comment/90969539
comment on: http://stackoverflow.com/a/51996147
has text: @curious_cosmo For the first question: `f'{spam} and {eggs}'` is a shorthand way of writing `'{spam} and {eggs}'.format(spam=spam, eggs=eggs)` added in Python 3.6. See [the PEP on f-string literals](https://www.python.org/dev/peps/pep-0498/) for details. `{ex!r}` is normal [format string syntax](https://docs.python.org/3/library/string.html#formatstrings) that goes all the way back to 2.6/3.0; the `!r` means to print the `repr` instead of the `str` (which is often more useful for debugging purposes, and especially so when printing exceptions).
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/90891266
score: 0
type: Comment
type: QuestionComment
has text: ...in general, though, the thing you're relying on (shell variables being set and expanded) relies on *having a shell*, so in the UNIX world, best practice would be to rework what you're doing entirely, to where it doesn't depend on shell variables at all.
comment on: http://stackoverflow.com/q/51969420

http://stackoverflow.com/comment/91072029
comment on: http://stackoverflow.com/q/52060867
has text: If you want to install to your 2.7, use pip...if you wang for python 3, use pip3.
type: Comment
type: QuestionComment
score: 2

http://stackoverflow.com/comment/91139981
type: QuestionComment
has text: @Tushortz I corrected it but the issue is still there
type: Comment
comment on: http://stackoverflow.com/q/52094797
score: 0

http://stackoverflow.com/comment/92560692
type: Comment
score: 0
comment on: http://stackoverflow.com/a/52117885
has text: I tried but I don't know where I have to use this. Can you edit my script and show me ?
type: AnswerComment

http://stackoverflow.com/a/51991090
has body: This is happening because your @function_debug decorator is returning a function, not a group. Rewrite the decorator to return a coroutine and switch the order of the decorators. @bot.group(pass_context = True) @function_debug
answers question: http://stackoverflow.com/q/51988684
score: 0
accepted answer of: http://stackoverflow.com/q/51988684
type: AcceptedAnswer
type: Answer

http://stackoverflow.com/a/52009079
has comment: http://stackoverflow.com/comment/91043653
type: Answer
answers question: http://stackoverflow.com/q/52007716
has body: If you wanted to copy every key and value from one dictionary to a new one, I would use this: oldDict = {} oldDict['offset'] = 'some_value' newDict = {} for key, value in oldDict.items(): newDict[key] = value If you wanted to copy only a specific set of keys with their value, you could use something like this: oldDict = {} oldDict['offset'] = 'some_value' oldDict['other'] = 'other_value' newDict = {} for key, value in oldDict.items(): if key == 'offset': newDict[key] = value This would only add the key and value if it was 'offset'
has comment: http://stackoverflow.com/comment/91042217
has comment: http://stackoverflow.com/comment/91043706
has comment: http://stackoverflow.com/comment/90972383
has comment: http://stackoverflow.com/comment/90972140
score: 0

http://stackoverflow.com/q/52013320
upvote count: 3
type: Question
score: 3
has title: How can I add raw HTML/JavaScript to a Dash application?
has answer: http://stackoverflow.com/a/52132699
has body: I'd like to have a tacky Matrix-style background in my Dash application. How can I add code for that, for example, what you'd find here?
tagged with: plotly-dash
answer count: 1
downvote count: 0
favorite count: 0
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/html
tagged with: python
tagged with: css

http://stackoverflow.com/q/52035673
tagged with: conda
has answer: http://stackoverflow.com/a/59057990
score: 37
has answer: http://stackoverflow.com/a/52035787
has answer: http://stackoverflow.com/a/78282594
downvote count: 0
has comment: http://stackoverflow.com/comment/91021416
favorite count: 0
has title: How can I update to the latest Python version using conda?
has body: I am new to Python. I was asked to update to the latest Python version using conda. So far, I have installed Anaconda on my Mac. So I am mainly using the Terminal. Thank you in advance.
tagged with: python
answer count: 4
has answer: http://stackoverflow.com/a/52036230
type: UnansweredQuestion
type: Question
upvote count: 37

http://stackoverflow.com/comment/91128939
score: 0
type: AnswerComment
type: Comment
has text: @agra94 , you should not just define `driver`, but use it in following lines (note that I used `driver.execute_script()`, not `webdriver.execute_script()`)
comment on: http://stackoverflow.com/a/52084638

http://stackoverflow.com/q/51989415
tagged with: django-orm
upvote count: 3
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51989815
tagged with: django
downvote count: 1
has body: I have and object and QuerySet which contains this object. I need to get next and previous object of this QuerySet. How can I do that? I could get next this way: next = False for o in QuerySet: if next: return o if o==object: next = True but I think it's very slow and unefficient approach on huge QuerySets. Do you know a better solution?
score: 2
has comment: http://stackoverflow.com/comment/90936186
has answer: http://stackoverflow.com/a/51989705
type: Question
tagged with: django-queryset
has comment: http://stackoverflow.com/comment/90937555
tagged with: django-2.1
has title: Get next and previous object from QuerySet by object
favorite count: 0
has answer: http://stackoverflow.com/a/65381058
tagged with: python
has answer: http://stackoverflow.com/a/51989533
answer count: 4
has comment: http://stackoverflow.com/comment/91022921

http://stackoverflow.com/q/52051810
has body: I do manual calculations from a json file and import the data. I want to automate the process using python. I am looking to pick few values based on the json file do the calculation. Below is the sample Json file so in order to calculate a SayDo formula, i have to take the sum(completed story points)/sum(committed story points) based on director. In this case director "Rajesh." Could you please point me to the right source Sample Data Set {"saydo": [{"teamName": "EPAM Backend 1", "sprintName": "MF-S94", "director": "Rajesh", "location": "Ukraine", "vendors": "EPAM,FTE", "sayDo": 77, "saydoStatusMeassure": "Yellow", "saydoStatusMeassureNumber": 0, "commitedSayDo": 68, "commitedSaydoStatusMeassure": "Yellow", "commitedSaydoStatusMeassureNumber": 0, "commitedStories": 17, "completedStories": 16, "completedStoryPoints": 56, "commitedStoryPoints": 73, "completedSoryPointsWithoutAddedAfterSprintStart": 50, "incompletedStories": 5, "addedAfterSprintStartStories": 5, "removedStories": 1, "bugsPerDev": 0.75, "bugsStatusMeassureNumber": 0, "bugsStatusMeassure": "Yellow", "openBeforeSprintEndsBugs": 6, "membersCount": 12, "completedBugsCount": 9, "p3BugsStatusMeassureNumber": 1, "p3BugsStatusMeassure": "Green", "p3BugsCount": 1, "addedIssuesAfterSprintCount": 6, "completedInSprintCount": 9, "techDebtIsuuesCount": 3, "foundAndFixedBugsValue": 100, "foundAndFixedBugsStatusMeassureNumber": 1, "foundAndFixedBugsStatusMeassure": "Green", "afterProdStatusMeassureNumber": 1, "afterProdStatusMeassure": "Green", "bugsAfterProdCount": 0}]} My code so far is import json def test3(): with open('C:/Users/erpsaam/Desktop/say-do-statistics-MF-S82-MF-S94-2018-07-09--10-30.json') as f: d = json.load(f) print (d['saydo'][1]['director']) test3()
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91095690
tagged with: python
upvote count: 0
tagged with: http://stackoverflow.com/tag/json
has comment: http://stackoverflow.com/comment/91053991
score: -1
downvote count: 1
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/91053801
tagged with: arrays
has title: Using Python to calculate aggregate values from a Json file
has answer: http://stackoverflow.com/a/52051910
has answer: http://stackoverflow.com/a/52056356
favorite count: 0

http://stackoverflow.com/a/52042449
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/91036958
accepted answer of: http://stackoverflow.com/q/52042298
score: 0
has comment: http://stackoverflow.com/comment/91036908
type: Answer
has comment: http://stackoverflow.com/comment/91037557
has comment: http://stackoverflow.com/comment/91037466
has comment: http://stackoverflow.com/comment/91038054
has body: You need to wrap orgdata in brackets and ensure that it's length is equal to the number of columns that you have, like so: df = pd.DataFrame([orgdata], columns=cols) When you are creating your MultiIndex, you are passing orgdata as a list of 25 values (i.e. Shape of passed values is (1, 25)). You then define your list colnames (I'm assuming) as a list of strings, with length 9. Then you create your MultiIndex using from_product() with another list of 3 values, therefore giving you indices imply (27, 25). The 25 here stems from the fact that you are passing orgdata to your dataframe constructor as a single list, so it will attempt to parse each individual value as it's own row. You need to wrap this in brackets to ensure that each value will be assigned to a column (since each list in the constructor is interpreted as a single row). Finally, you either need to ensure you have 25 columns to match your passed orgdata, or pass 27 values inside of orgdata. Using your sample data, here is a minimal example: import pandas as pd data = ['15EC41', 'LIC', '40', '60', 'P'] orgdata = ['somestring', data[0], data[1], data[2], data[3], data[4]] colnames = ['USN', data[2]] cols = pd.MultiIndex.from_product([colnames, ['IA', 'EX', 'Total']]) df = pd.DataFrame([orgdata], columns=cols) Yields: USN 40 IA EX Total IA EX Total 0 somestring 15EC41 LIC 40 60 P A bit more complex example to set index: import pandas as pd data1 = ['15EC41', 'LIC', '40', '60', 'P'] data2 = ['62F793', 'DUH', '52', '85', 'O'] data3 = ['9734HJ', 'IAS', '34', '94', 'D'] orgdata = [['somestring', i[0], i[1], i[2], i[3], i[4]] for i in [data1, data2, data3]] colnames = [data1[0], data1[2]] cols = pd.MultiIndex.from_product([colnames, ['IA', 'EX', 'Total']]) df = pd.DataFrame(orgdata, columns=cols) USN = [0, 1, 2] df.index = USN; df.index.name = 'USN' Yields: 15EC41 40 IA EX Total IA EX Total USN 0 somestring 15EC41 LIC 40 60 P 1 somestring 62F793 DUH 52 85 O 2 somestring 9734HJ IAS 34 94 D
answers question: http://stackoverflow.com/q/52042298
has comment: http://stackoverflow.com/comment/91037276
has comment: http://stackoverflow.com/comment/91038337

http://stackoverflow.com/a/52108343
type: Answer
has body: I see an issue with your code. The problem is at this point: for filename in os.listdir(cwd): print(filename) if filename != post.filename: url = post.file_url wget.download(url) time.sleep(1.03) You are looping through each file in the directory. That means if you have a single file in the directory that is not named the same as the post's filename, it's going to download. So let's say your code is trying to download file3 and your directory contains file1, file2, and file3. With those files in the directory your if statement is going to make these 3 checks. if 'file1' != 'file3': url = post.file_url wget.download(url) time.sleep(1.03) if 'file2' != 'file3': url = post.file_url wget.download(url) time.sleep(1.03) if 'file3' != 'file3': url = post.file_url wget.download(url) time.sleep(1.03) What you might want to try instead is checking if the filename is in the list that os.listdir() returns. Here is my solution: if 'ylyl' in subject or 'YLYL' in subject: for post in thread.all_posts: if post.has_file: print(post.filename) if post.filename not in os.listdir(cwd): url = post.file_url wget.download(url) time.sleep(1.03)
accepted answer of: http://stackoverflow.com/q/52108009
answers question: http://stackoverflow.com/q/52108009
type: AcceptedAnswer
score: 0

http://stackoverflow.com/a/52096445
type: Answer
downvote count: 1
score: -1
upvote count: 0
answers question: http://stackoverflow.com/q/52096071
has body: Try the following xpath tree.xpath('//ca1//text()')[0].strip()

http://stackoverflow.com/a/51977122
upvote count: 2
accepted answer of: http://stackoverflow.com/q/51976146
answers question: http://stackoverflow.com/q/51976146
has body: You forgot to commit your changes. Add connection.commit() to the end of your code.
score: 2
type: AcceptedAnswer
downvote count: 0
type: Answer

http://stackoverflow.com/a/51969382
has comment: http://stackoverflow.com/comment/90985631
upvote count: 3
has comment: http://stackoverflow.com/comment/90985240
has comment: http://stackoverflow.com/comment/90892090
score: 3
has body: Just as you used np.histogram1 to check uniformity in 1D, you can use np.histogram2d to do the same thing in 2D, and np.histogramdd in 3D+. To see an example, let's first fix your loops by making them go away: kx = np.random.random(nk1 * nk2 * nk3) ky = np.random.random(nk1 * nk2 * nk3) kz = np.tile(np.arange(nk3) / nk3, n1 * n2) hist2d, *_ = np.histogram2d(kx, ky, range=[[0, 1], [0, 1]]) The range parameter ensures that you are binning over [0, 1) in each direction, not over the actual min and max if your data, no matter how close it may be. Now it's entirely up to you how to visualize the 100 data points in hist2d. One simple way would be to just ravel it and do a bar chart like you did for the 1D case: plt.bar(np.arange(hist2d.size), hist2d.ravel()) plt.plot([0, hist2d.size], [nk1 * nk2 * nk3 / hist2d.size] * 2) Another simple way would be to do a heat map: plt.imshow(hist2d, interpolation='nearest', cmap='hot') This is actually not as useful as the bar chart, and doesn't generalize to higher dimensions as well. Your best bet is probably just checking the standard deviation of the raw data. 1 Or rather plt.hist did for you under the hood.
has comment: http://stackoverflow.com/comment/90892564
answers question: http://stackoverflow.com/q/51969307
downvote count: 0
has comment: http://stackoverflow.com/comment/90892636
has comment: http://stackoverflow.com/comment/90892731
type: Answer

http://stackoverflow.com/comment/90938935
type: Comment
comment on: http://stackoverflow.com/q/51994368
score: 0
type: QuestionComment
has text: This snippet removed all of the symbols other than numerals, then pushed all of the numerals into column 1 squished together: new_line = re.sub('\\D+','',str(line))

http://stackoverflow.com/q/52020748
has comment: http://stackoverflow.com/comment/91213013
tagged with: keras
favorite count: 0
has comment: http://stackoverflow.com/comment/91262994
has comment: http://stackoverflow.com/comment/91212652
has comment: http://stackoverflow.com/comment/91212967
score: 32
tagged with: python
upvote count: 33
has body: I have been developing feedforward neural networks (FNNs) and recurrent neural networks (RNNs) in Keras with structured data of the shape [instances, time, features], and the performance of FNNs and RNNs has been the same (except that RNNs require more computation time). I have also simulated tabular data (code below) where I expected a RNN to outperform a FNN because the next value in the series is dependent on the previous value in the series; however, both architectures predict correctly. With NLP data, I have seen RNNs outperform FNNs, but not with tabular data. Generally, when would one expect a RNN to outperform a FNN with tabular data? Specifically, could someone post simulation code with tabular data demonstrating a RNN outperforming a FNN? Thank you! If my simulation code is not ideal for my question, please adapt it or share a more ideal one! from keras import models from keras import layers from keras.layers import Dense, LSTM import numpy as np import matplotlib.pyplot as plt Two features were simulated over 10 time steps, where the value of the second feature is dependent on the value of both features in the prior time step. ## Simulate data. np.random.seed(20180825) X = np.random.randint(50, 70, size = (11000, 1)) / 100 X = np.concatenate((X, X), axis = 1) for i in range(10): X_next = np.random.randint(50, 70, size = (11000, 1)) / 100 X = np.concatenate((X, X_next, (0.50 * X[:, -1].reshape(len(X), 1)) + (0.50 * X[:, -2].reshape(len(X), 1))), axis = 1) print(X.shape) ## Training and validation data. split = 10000 Y_train = X[:split, -1:].reshape(split, 1) Y_valid = X[split:, -1:].reshape(len(X) - split, 1) X_train = X[:split, :-2] X_valid = X[split:, :-2] print(X_train.shape) print(Y_train.shape) print(X_valid.shape) print(Y_valid.shape) FNN: ## FNN model. # Define model. network_fnn = models.Sequential() network_fnn.add(layers.Dense(64, activation = 'relu', input_shape = (X_train.shape[1],))) network_fnn.add(Dense(1, activation = None)) # Compile model…
has title: Why Bother With Recurrent Neural Networks For Structured Data?
has answer: http://stackoverflow.com/a/52215330
tagged with: prediction
accepted answer: http://stackoverflow.com/a/52215330
downvote count: 1
has comment: http://stackoverflow.com/comment/91212791
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91212537
has comment: http://stackoverflow.com/comment/91206094
has comment: http://stackoverflow.com/comment/91201041
has comment: http://stackoverflow.com/comment/91211487
tagged with: recurrent-neural-network
type: Question
has comment: http://stackoverflow.com/comment/91262906
answer count: 1

http://stackoverflow.com/a/52055363
score: 1
has body: You can use merge with how='left' and indicator=True and then filter rows present in df1. In [277]: df1.merge(df2, indicator=True, how='left' ).query('_merge == "left_only"' ).drop('_merge', 1) Out[277]: emp_no no_children status 2 23 5 5 Details In [278]: df1.merge(df2, indicator=True, how='left') Out[278]: emp_no no_children status _merge 0 1 3 3 both 1 2 2 2 both 2 23 5 5 left_only In [279]: df1.merge(df2, indicator=True, how='left').query('_merge == "left_only"') Out[279]: emp_no no_children status _merge 2 23 5 5 left_only
downvote count: 0
answers question: http://stackoverflow.com/q/52055318
type: Answer
upvote count: 1

http://stackoverflow.com/q/52029026
tagged with: telegram
tagged with: events
tagged with: python
score: 2
upvote count: 2
type: UnansweredQuestion
has body: i am developing a python script for my telegram right now. The problem is: How do I know when my bot is added to a group? Is there an Event or something else for that? I want the Bot to send a message to the group he´s beeing added to which says hi and the functions he can. I dont know if any kind of handler is able deal with this.
has answer: http://stackoverflow.com/a/52093608
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/62833920
has comment: http://stackoverflow.com/comment/91008408
has title: Telegram Python Bot | Event when Bot is added to a group
downvote count: 0
favorite count: 0
tagged with: telegram-bot
tagged with: python-telegram-bot

http://stackoverflow.com/comment/90989620
has text: Can you give some other example inputs and outputs?
comment on: http://stackoverflow.com/q/52019578
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51979432
type: AnsweredQuestion
downvote count: 0
has answer: http://stackoverflow.com/a/51980402
score: 1
has comment: http://stackoverflow.com/comment/90908951
type: Question
has comment: http://stackoverflow.com/comment/90908569
answer count: 1
has title: Filter out 'None' from Python list, 'str' object is not callable
tagged with: typeerror
has comment: http://stackoverflow.com/comment/90908676
tagged with: exception
upvote count: 1
has comment: http://stackoverflow.com/comment/90909460
has body: My script does an LDAP search: import ldap ...&lt;initializations&gt; res = conn.search_s(base, scope_level, filter, attrs) _logger.debug("LDAP query result: %s", res) # Filter out the 'None' entries for referrals filter(lambda x: (isinstance(x,tuple) and x[0] is not None), res) This filter here errors out with TypeError: 'str' object is not callable I added try...except around it to log _logger.debug("Result was:%s, Result type: %s", res, type(res)) and it is indeed a list # Example: Result was:[('CN=Domain Admins,CN=Users,DC=hiccups,DC=com', {'sAMAccountName': ['domain admins']}), (None, ['ldap://sirius.hiccups.com/DC=sirius,DC=hiccups,DC=com']), (None, ['ldap://ForestDnsZones.hiccups.com/DC=ForestDnsZones,DC=hiccups,DC=com']), (None, ['ldap://DomainDnsZones.hiccups.com/DC=DomainDnsZones,DC=hiccups,DC=com']), (None, ['ldap://hiccups.com/CN=Configuration,DC=hiccups,DC=com'])], Result type: &lt;type 'list'&gt; If I copy the list in a separate script and run the same filter, it works as expected. A for construct replacing filter also works fine: result = [] for each in res: if (isinstance(each, tuple) and each[0] is not None): result.append(each) But I want to debug why filter is failing
favorite count: 0
accepted answer: http://stackoverflow.com/a/51980402
has comment: http://stackoverflow.com/comment/90909153
tagged with: python

http://stackoverflow.com/a/52123761
accepted answer of: http://stackoverflow.com/q/52040392
type: Answer
answers question: http://stackoverflow.com/q/52040392
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/91203793
has body: Try using eager execution and tf.contrib.eager.defun to build your graphs (search for usages of defun in the tensorflow codebase to see examples of this). Eager execution lets you persistent tensors on-device without fetching them and without the need to worry about sessions.
upvote count: 1
type: AcceptedAnswer

http://stackoverflow.com/q/52111663
tagged with: python
score: 2
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/48763072
has body: I need to edit 2 RTP header fields in a PACP file. I want to edit the RTP timestamp field and the SSRC field. This is so that I can manipulate some capture for replay using tcpreplay for testing end device for a couple of reasons. Using the Python REPL i am able to load the file: from scapy.all import rdpcap pkts_list = rdpcap("foo.pcap") the I get the length of the file len(pkts_list) then I can inspect a packet pkts_list[xxx].show() How / Can I decode / see RTP header information? Sorry scapy docs are a bit think for me on this one. Thanks in advance Neil
linked to: http://stackoverflow.com/q/44724186
possible better answer: http://stackoverflow.com/a/59478307
tagged with: rtp
tagged with: scapy
has comment: http://stackoverflow.com/comment/91196222
type: Question
upvote count: 2
answer count: 2
downvote count: 0
has title: Python Scapy RTP header manipulation - how can I decode RTP in scapy?
has answer: http://stackoverflow.com/a/52122559
accepted answer: http://stackoverflow.com/a/52122559
has answer: http://stackoverflow.com/a/59478307
has comment: http://stackoverflow.com/comment/91174091
favorite count: 0

http://stackoverflow.com/comment/91025863
score: 0
comment on: http://stackoverflow.com/q/52036914
has text: @AlexK.thanks Alex i will try it too!
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91041118
type: Comment
comment on: http://stackoverflow.com/a/52044846
score: 0
type: AnswerComment
has text: @fuglede I think the version different may cause the out put slightly different .

http://stackoverflow.com/comment/91165116
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52106515
has text: provide a [mcve]

http://stackoverflow.com/comment/90962444
comment on: http://stackoverflow.com/a/52005482
type: AnswerComment
score: 0
has text: @HaiVu Yes, you could, but this will break if the allowed difference is larger than 1.
type: Comment

http://stackoverflow.com/q/52031995
type: Question
upvote count: 1
favorite count: 0
linked to: http://stackoverflow.com/q/9626535
answer count: 1
tagged with: python
has body: For a general POST request in Python like: &gt;&gt;&gt; import requests &gt;&gt;&gt; r = requests.post(url=url, data=data, headers = headers, cookies = cookies) &gt;&gt;&gt; type(r) &lt;class 'requests.models.Response'&gt; Is it possible to obtain the ip address that was used at the time the post request was made? I have tried to look through its contents using dir(r) and got: dir(r) ['attrs', 'bool', 'class', 'delattr', 'dict', 'dir', 'doc', 'enter', 'eq', 'exit', 'format', 'ge', 'getattribute', 'getstate', 'gt', 'hash', 'init', 'init_subclass', 'iter', 'le', 'lt', 'module', 'ne', 'new', 'nonzero', 'reduce', 'reduce_ex', 'repr', 'setattr', 'setstate', 'sizeof', 'str', 'subclasshook', 'weakref', '_content', '_content_consumed', '_next', 'apparent_encoding', 'close', 'connection', 'content', 'cookies', 'elapsed', 'encoding', 'headers', 'history', 'is_permanent_redirect', 'is_redirect', 'iter_content', 'iter_lines', 'json', 'links', 'next', 'ok', 'raise_for_status', 'raw', 'reason', 'request', 'status_code', 'text', 'url'] Is there something in here that might contain it? thanks.
linked to: http://stackoverflow.com/q/11618118
tagged with: python-3.x
has title: In Python, for a POST request, is it possible to obtain the ip address used for the request from the POST request object?
has answer: http://stackoverflow.com/a/52032062
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/52032062
downvote count: 0
score: 1
tagged with: post

http://stackoverflow.com/a/52079840
has body: you could try: if B in (A or []): so if A is None it tests against empty list and yields False if A is an empty list, it will also test against the rightmost operand of or but the result will be the same. Larger scope: if you have default values as None in your function: def foo(A=None,B=None): leave them as None, and change them in the function code so the default argument isn't mutable ("Least Astonishment" and the Mutable Default Argument). if A is None: A = []
score: 1
answers question: http://stackoverflow.com/q/52079704
upvote count: 1
downvote count: 0
type: Answer

http://stackoverflow.com/comment/90991165
type: Comment
score: 1
comment on: http://stackoverflow.com/a/52020165
has text: I was doing the ''.join() because using with open gives me a list of strings which I can't feed to beautifulsoup. I tried using "html.parser" instead and it worked. Thank you for the help!
type: AnswerComment

http://stackoverflow.com/comment/102772363
type: Comment
type: QuestionComment
has text: I get this behavior without wanting it in 2.1.1...
comment on: http://stackoverflow.com/q/52095337
score: 0

http://stackoverflow.com/q/52101429
has answer: http://stackoverflow.com/a/52101472
answer count: 1
favorite count: 0
has title: Is it possible to replace a python file while its running
has comment: http://stackoverflow.com/comment/91153705
tagged with: python
has body: I have a single python file that takes about an hour to run. Can I replace the whole file while its running without issues? I am aware if this question it does not address the concern of the python file being totally replaced with a new one.
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/5296977
downvote count: 0
score: 1
duplicate of: http://stackoverflow.com/q/5296977
type: Question
upvote count: 1

http://stackoverflow.com/q/52046551
tagged with: python-3.x
has answer: http://stackoverflow.com/a/52047122
tagged with: python
tagged with: pyqt5
upvote count: 1
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/52047122
score: 1
type: Question
tagged with: pyqt
answer count: 1
downvote count: 0
has body: I am wanting to use a "Radialbar" widget for an aesthetic purposes in a GUI I am creating. Currently, I am trying to use a port found at the following location: http://pyjuice.com/porting-radialbar-cqt-pyqt/ My question is, how do I actually go about using this in the GUI I have already built? I currently use Qt Designer to create the ui file that I use for the GUI, and then import to PtQt5 using: uic.loadUi("name.ui") Is there a way to include this widget into my existing GUI? I am pretty new at this, and do not understand how I should go about using the port from the link above.
favorite count: 0
has title: Using Radialbar QML Port with PyQt5

http://stackoverflow.com/comment/91047450
comment on: http://stackoverflow.com/q/52048331
score: 0
type: QuestionComment
has text: Are the existing tuples unique, or might you have, say 3 copies of `(100, 700)`?
type: Comment

http://stackoverflow.com/q/51968897
has comment: http://stackoverflow.com/comment/90888815
type: Question
has body: Is there a way to repeat whole tkinter program after pressing a button? Ways to do it without pressing a button will be cool too.Something like repeating whole mainloop
has comment: http://stackoverflow.com/comment/90888727
downvote count: 5
has answer: http://stackoverflow.com/a/51969402
has comment: http://stackoverflow.com/comment/90888273
upvote count: 0
answer count: 1
has title: Repeat whole tkinter program
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/90888990
accepted answer: http://stackoverflow.com/a/51969402
tagged with: python
type: AnsweredQuestion
score: -5
tagged with: tkinter

http://stackoverflow.com/a/52112591
type: Answer
has body: You've mixed up the displayWidth and displayHeight variables and that means the gy variable is 640 (below the screen). Just swap them (also, there's no need for parentheses here): gx = displayWidth * 0.45 gy = displayHeight * 0.8
upvote count: 1
score: 1
accepted answer of: http://stackoverflow.com/q/52105116
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/52105116

http://stackoverflow.com/a/79412185
answers question: http://stackoverflow.com/q/51973105
score: 0
type: Answer
has body: You're on the right track, but dictionaries in Python exist in memory while the program is running. You need to store the data persistently, so it remains available after termination. For small-scale data, use JSON or persidict. For larger datasets with frequent queries, use SQLite. persidict behaves like a normal Python dictionary but automatically saves changes to a file. pip install persidict from persidict import PersiDict # Load (or create) a persistent dictionary stored in "users.json" users = PersiDict("users.json") # Ensure 'John' exists in the dictionary if "John" not in users: users["John"] = {'Favourite Colour': 'Blue', 'Age': '10'} # Modify John's data and save it users["John"]["Food"] = "Chicken" users.commit() # Save changes permanently # Print updated dictionary print(users["John"])

http://stackoverflow.com/q/52015435
score: 1
has title: Add administrative level
tagged with: python-3.x
type: UnansweredQuestion
upvote count: 1
has body: I just discovered osmnx and I'm still exploring all its features. All I can say for now is that it's an amazing package ! I looked at your code places = ox.gdf_from_places(['Botswana', 'Zambia', 'Zimbabwe']) places = ox.project_gdf(places) ox.save_gdf_shapefile(places) ox.plot_shape(ox.project_gdf(places)) Is there a way to have the admisitrative level 2 for example? Thanks, Jaber
type: Question
tagged with: openstreetmap
downvote count: 0
answer count: 1
has answer: http://stackoverflow.com/a/52410947
tagged with: osmnx
favorite count: 0
tagged with: python

http://stackoverflow.com/a/51960531
has comment: http://stackoverflow.com/comment/90871712
has comment: http://stackoverflow.com/comment/90874938
has comment: http://stackoverflow.com/comment/90872049
answers question: http://stackoverflow.com/q/51960468
score: 0
has comment: http://stackoverflow.com/comment/90874556
has comment: http://stackoverflow.com/comment/90872409
type: Answer
has comment: http://stackoverflow.com/comment/90871674
has comment: http://stackoverflow.com/comment/90874662
has comment: http://stackoverflow.com/comment/90874757
has comment: http://stackoverflow.com/comment/90875239
has body: What you can do is, pass a new parameter which will have the value. This way you can change the parameter every time, rather than hard coding. For example: def iost(bot, update, fsym, tsym): params = { 'fsym' : fsym, 'tsyms' : tsym } iostCall = "https://min-api.cryptocompare.com/data/price" iostCallJson = requests.get(iostCall, params=params).json() iostOut = iostCallJson update.message.reply_text(iostOut) iost(bot= bot, update= update, fsym='IOST', tsyms='USD,JPY,EUR')
has comment: http://stackoverflow.com/comment/90875324

http://stackoverflow.com/a/51975039
upvote count: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/90901437
type: Answer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51974020
score: 1
answers question: http://stackoverflow.com/q/51974020
has body: @SagarJhamb your code have two faults 1.repo_dicts is not initialised 2. defining my_style= LS("333366", base_style=LCS) the value should start with #333366 for learning more about custom style with pygal you can check out[pygal documentation][1][1]: http://www.pygal.org/en/stable/documentation/parametric_styles.html import requests import pygal from pygal.style import LightColorizedStyle as LCS, LightenStyle as LS url = "https://api.github.com/search/repositories?q=language:python&amp;sort=stars" r = requests.get(url) response_dict = r.json() # initialise response dict repo_dict=response_dict['items'] names,stars = [],[] for repo in repo_dict: names.append(repo["name"]) stars.append(repo["stargazers_count"]) # #333366 remove your error of NoneType object has no attribute startswith #It is rightformat of using custom style with pygal #It should starts with # my_style = LS("#333366", base_style=LCS) chart = pygal.Bar( style=my_style, x_label_rotation=45, show_legend=False) chart.title = "Most starred Python projects on GitHub" chart.x_labels = names chart.add("stars", stars) chart.render_to_file("repo_visual.svg")

http://stackoverflow.com/q/52106752
upvote count: 2
tagged with: tensorflow-estimator
answer count: 1
favorite count: 0
type: UnansweredQuestion
tagged with: python
score: 2
downvote count: 0
has title: Validation and Testing in Tensforflow Estimator vs. Keras
has body: I've read answers here and trying to understand how training, validation and testing map to Tensorflow Estimator API and Keras API. A: Tensorflow tf.estimator.train_and_evaluate function takes a train_spec and a eval_spec. Here, does evaluate mean validation or testing in above terminology? If it's testing, where do I specify a validation set? B: Keras In Keras, this seems to be clearer, model.fit takes validation_data argument, which is for validation set. There is a separate function model.evaluate, to which we provide the test set. Is this correct?
has answer: http://stackoverflow.com/a/52107283
tagged with: tensorflow
type: Question
tagged with: keras

http://stackoverflow.com/q/52037050
has comment: http://stackoverflow.com/comment/91086912
type: Question
has comment: http://stackoverflow.com/comment/91050199
has title: About Custom Device Actions
has comment: http://stackoverflow.com/comment/91049649
has body: I follow the instruction (https://developers.google.com/assistant/sdk/guides/library/python/extend/custom-actions) to set a "blinklight" Custom Device Actions, but it's not working. I went to "deviceregistration" page, but i can't see the "blinklight" traits. in the list. I ran the example code, and get the log below: "device_model_id: pegagooleassistnatcplusplus-pegagoogleassistantcplusplus-v5mnh8 device_id: 075C580BE09EBB9D304FEBA605EEFA59 ON_MUTED_CHANGED: {"is_muted": false} ON_MEDIA_STATE_IDLE ON_START_FINISHED ON_CONVERSATION_TURN_STARTED ON_END_OF_UTTERANCE ON_RECOGNIZING_SPEECH_FINISHED: {"text": "blinking 5 times"} ON_RESPONDING_STARTED: {"is_error_response": false} ON_RESPONDING_FINISHED ON_CONVERSATION_TURN_FINISHED: {"with_follow_on_turn": false}
tagged with: google-assistant-sdk
has comment: http://stackoverflow.com/comment/91033964
has comment: http://stackoverflow.com/comment/91075720
answer count: 0
type: UnansweredQuestion
score: 0
tagged with: python

http://stackoverflow.com/a/52065942
accepted answer of: http://stackoverflow.com/q/52065842
downvote count: 0
score: 40
has body: Most containers start with LANG=C set. That can be really annoying if you're dealing with UTF-8. Just to make sure your container starts with the right locale add -e LANG=C.UTF-8 when calling docker.
has comment: http://stackoverflow.com/comment/105296276
type: AcceptedAnswer
upvote count: 40
answers question: http://stackoverflow.com/q/52065842
type: Answer

http://stackoverflow.com/comment/91142185
score: 2
type: AnswerComment
comment on: http://stackoverflow.com/a/52094827
type: Comment
has text: @Vamshi can you provide an example of your data, i.e. one or two rows from data frame, and a definition of your metric (code)?

http://stackoverflow.com/comment/91089893
comment on: http://stackoverflow.com/a/52069725
score: 0
type: Comment
has text: what if i only want the value of only one key and not the whole dictionary. for example, when you type in white 3, i only want to output 3 'white':3 not the whole dictionary.
type: AnswerComment

http://stackoverflow.com/a/75690198
upvote count: 1
answers question: http://stackoverflow.com/q/52068066
has comment: http://stackoverflow.com/comment/133529594
downvote count: 0
type: Answer
has body: resp = dynamodb.execute_statement(Statement="SELECT gateway FROM Table_Name") data = resp['Items'] #print(resp['NextToken']) while 'NextToken' in resp: resp = dynamodb.execute_statement(Statement="SELECT gateway FROM Table_Name", NextToken =resp['NextToken']) data.extend(resp['Items'])
has comment: http://stackoverflow.com/comment/133567750
score: 1

http://stackoverflow.com/comment/91304662
comment on: http://stackoverflow.com/q/52094242
has text: @PearlySpencer is there any other lib or source which can be helpfull to extract text with autonumbering
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/a/52036589
type: Answer
has body: As per the code pasted above Person is the Superclass and Birthday is the Subclass. So, It's the Subclass which inherits from Superclass and not the other way round. Also, Inheritance is an is-a relationship. Have/Has-A relationship corresponds to composition. You can read more here.
answers question: http://stackoverflow.com/q/52036357
score: 0

http://stackoverflow.com/comment/91046175
type: Comment
score: 0
has text: Your column name ;} change for `sequence_list`, I guess thats what youre using
type: AnswerComment
comment on: http://stackoverflow.com/a/52047585

http://stackoverflow.com/comment/91157158
type: AnswerComment
score: 0
type: Comment
has text: No the indentation was correct,my question is arent variable names declared in any functions local to that function only So str was decalred in main but in nextpal() the interpreter should consider it as a function right?
comment on: http://stackoverflow.com/a/52102810

http://stackoverflow.com/comment/91011684
has text: I got `AttributeError at /api/player/42: 'Player' object has no attribute 'last_stat_list'`
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52029787

http://stackoverflow.com/q/51967221
has comment: http://stackoverflow.com/comment/90884696
has comment: http://stackoverflow.com/comment/90884650
tagged with: process-monitoring
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90884448
has comment: http://stackoverflow.com/comment/90885075
has title: Fetch memory usage of system without using psutil
has comment: http://stackoverflow.com/comment/90885809
answer count: 0
type: Question
has comment: http://stackoverflow.com/comment/90885562
tagged with: python
linked to: http://stackoverflow.com/q/17718449
linked to: http://stackoverflow.com/q/276052
has comment: http://stackoverflow.com/comment/90885353
has comment: http://stackoverflow.com/comment/90884577
has body: I am developing a server monitoring application. I need to get the memory usage of the system with out using the "psutil" package. Is there a way to do it in python?
score: 0
tagged with: memory

http://stackoverflow.com/q/51971050
tagged with: tensorflow-estimator
answer count: 3
has answer: http://stackoverflow.com/a/75808761
downvote count: 0
favorite count: 0
score: 33
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/78749192
has title: Graph optimizations on a tensorflow serveable created using tf.Estimator
has body: Context: I have a simple classifier based on tf.estimator.DNNClassifier that takes text and output probabilities over an intent tags. I am able to train an export the model to a serveable as well as serve the serveable using tensorflow serving. The problem is this servable is too big (around 1GB) and so I wanted to try some tensorflow graph transforms to try to reduce the size of the files being served. Problem: I understand how to take the saved_model.pb and use freeze_model.py to create a new .pb file that can be used to call transforms on. The result of these transforms (a .pb file as well) is not a servable and cannot be used with tensorflow serving. How can a developer go from: saved model -&gt; graph transforms -&gt; back to a servable There's documentation that suggests that this is certainly possible, but its not at all intuitive from the docs as to how to do this. What I've Tried: import tensorflow as tf from tensorflow.saved_model import simple_save from tensorflow.saved_model import signature_constants from tensorflow.saved_model import tag_constants from tensorflow.tools.graph_transforms import TransformGraph with tf.Session(graph=tf.Graph()) as sess_meta: meta_graph_def = tf.saved_model.loader.load( sess_meta, [tag_constants.SERVING], "/model/path") graph_def = meta_graph_def.graph_def other_graph_def = TransformGraph( graph_def, ["Placeholder"], ["dnn/head/predictions/probabilities"], ["quantize_weights"]) with tf.Graph().as_default(): graph = tf.get_default_graph() tf.import_graph_def(other_graph_def) in_tensor = graph.get_tensor_by_name( "import/Placeholder:0") out_tensor = graph.get_tensor_by_name( "import/dnn/head/predictions/probabilities:0") inputs = {"inputs": in_tensor} outputs = {"outputs": out_tensor} simple_save(sess_meta, "./new", inputs, outputs) My idea was to load the servable, extract the graph_def from the meta_graph_def, transform the graph_def and then try to recreate the servable. This seems to be the incorrect approach. Is there a …
has comment: http://stackoverflow.com/comment/91158447
tagged with: tensorflow-serving
tagged with: tensorflow
type: Question
upvote count: 33
has answer: http://stackoverflow.com/a/79216047

http://stackoverflow.com/comment/91081962
has text: It does print the data frame with the score column, yes
comment on: http://stackoverflow.com/a/52065587
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/51974324
upvote count: 1
answer count: 1
downvote count: 1
has body: I'm looking at creating a pipeline between an FTP server and an AWS S3 bucket. With the capability of monitoring the FTP server for new files. I would like to program most to all of it with Python. Where do I begin?
has title: Where do I begin when trying to develope a data pipeline from an FTP server to an AWS S3 bucket?
tagged with: amazon-s3
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90899299
has answer: http://stackoverflow.com/a/51974789
has comment: http://stackoverflow.com/comment/90899360
tagged with: amazon-web-services
tagged with: data-science
favorite count: 0
has comment: http://stackoverflow.com/comment/90900931
type: Question
linked to: http://stackoverflow.com/q/23939179
tagged with: python
score: 0

http://stackoverflow.com/comment/90950456
comment on: http://stackoverflow.com/q/52000052
type: QuestionComment
type: Comment
has text: I really advice to first gain some experience with a database (does not have to be MySQL per se), and read the Django tutorial, I have the impression that there is some knowledge lacking here, making it virtually impossible to help you with this particular issue.
score: 0

http://stackoverflow.com/comment/91160781
type: Comment
has text: OP needs the two columns to match in the same row; your logic assumes that matching in different rows is okay.
comment on: http://stackoverflow.com/a/52104526
score: 0
type: AnswerComment

http://stackoverflow.com/a/52010724
has comment: http://stackoverflow.com/comment/90972498
type: AcceptedAnswer
has body: you can tell splitlines to keep the end of lines when splitting (by passing True as optional argument). Then, on each line, don't go to the next line if there is no newline (you have to strip line when displaying. for line in string.splitlines(True): global x_cursor, y_cursor # pixel location of cursor in image x_size_of_text = draw_one_line_of_text(line.rstrip()) old_x_cursor = x_cursor if line.endswith("\n"): x_cursor = 0 y_cursor += 20 # lines are 20 pixels high That avoids the final test, but introduces a lot of extra testing &amp; complexity, just to handle the last case. I see no problem sticking to your solution (it's ugly but fast - better ask for forgiveness than for permission). One objection, instead of: if string[-1] != '\n': # if string is empty: Index out of range exception I'd do: if string and not string.endswith("\n"): If the string is empty your test would crash your program. Besides, there would be nothing to correct so test for empty string first.
accepted answer of: http://stackoverflow.com/q/52010637
type: Answer
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/52010637
downvote count: 0

http://stackoverflow.com/comment/91024484
type: QuestionComment
has text: Now I do not see any errors when running your code. But there is no way you get two figures if you only create one. You do not need to re-open the question.
comment on: http://stackoverflow.com/q/52036709
score: 0
type: Comment

http://stackoverflow.com/a/52075069
type: Answer
has body: You are simply overwriting the same output CSV file for all the pages, you can call .to_csv() in the "append" mode to have the new data added to the end of the existing file: df.to_csv('example31.csv', mode='a', encoding="utf-8", header=False) Or, even better would be to collect the titles into a list of titles and then dump into a CSV once: #start looping through all pages titles = [] for item in webpages: headers = {'User-Agent': 'Mozilla/5.0'} data = r.get(item, headers=headers) page_soup = soup(data.text, 'html.parser') #find targeted info and put them into a list to be exported to a csv file via pandas title_list = [title.text for title in page_soup.find_all('div', {'class':'field field-name-node-title'})] titles += [el.replace('\n', '') for el in title_list] # export to csv file via pandas dataset = [{'Title': title} for title in titles] df = pandas.DataFrame(dataset) df.index.name = 'ArticleID' df.to_csv('example31.csv', encoding="utf-8")
score: 2
has comment: http://stackoverflow.com/comment/91099997
accepted answer of: http://stackoverflow.com/q/52074916
answers question: http://stackoverflow.com/q/52074916
type: AcceptedAnswer
downvote count: 0
upvote count: 2

windows
tags question: http://stackoverflow.com/q/51975519
tags question: http://stackoverflow.com/q/51983774
tags question: http://stackoverflow.com/q/51969420
tags question: http://stackoverflow.com/q/51977190
tags question: http://stackoverflow.com/q/52096669
tags question: http://stackoverflow.com/q/52030008
tags question: http://stackoverflow.com/q/51996262
tags question: http://stackoverflow.com/q/52059663
tags question: http://stackoverflow.com/q/52049163
tags question: http://stackoverflow.com/q/52063996
tags question: http://stackoverflow.com/q/51973372
tags question: http://stackoverflow.com/q/52093116
tags question: http://stackoverflow.com/q/52096844
tags question: http://stackoverflow.com/q/52077195
tags question: http://stackoverflow.com/q/52084983
type: Tag
tags question: http://stackoverflow.com/q/52073396
tags question: http://stackoverflow.com/q/52104043
tags question: http://stackoverflow.com/q/52013769
tags question: http://stackoverflow.com/q/52074590
tags question: http://stackoverflow.com/q/51987502
tags question: http://stackoverflow.com/q/52108369
tag name: windows
tags question: http://stackoverflow.com/q/51988578
tags question: http://stackoverflow.com/q/51987408

http://stackoverflow.com/comment/91128143
comment on: http://stackoverflow.com/q/52088986
score: 1
type: Comment
type: QuestionComment
has text: i am using pandas in `load_data`, this is a minimal example

http://stackoverflow.com/comment/90974809
type: QuestionComment
type: Comment
has text: Also, `sys` is special in that it's usually either built-in or frozen-in to the interpreter itself, while `math` is usually found in the standard library. So, maybe you just can't find your standard library. Do any other stdlib modules not work? Can you print out `sys.path` and `sys.metapath` and show us what they say?
comment on: http://stackoverflow.com/q/52011847
score: 0

http://stackoverflow.com/q/52052003
score: 3
has answer: http://stackoverflow.com/a/52052051
tagged with: python
has body: I have a dict- a = {'b': [1,2,3], 'c':[4,5,6]} I want to use list comprehension only to achieve this output- [['c', 4], ['c', 5], ['c', 6], ['b', 1], ['b', 2], ['b', 3]] A simple for loop gets it done with - x = [] for k, v in a.iteritems(): for i in v: x.append([k, i]) Tried to convert it to list comprehension, I did this- [[k,i] for i in v for k, v in a.items()] But weirdly for me, I got an output [['c', 1], ['b', 1], ['c', 2], ['b', 2], ['c', 3], ['b', 3]] What should be the right list comprehension and why is my list comprehension not working?
favorite count: 0
has answer: http://stackoverflow.com/a/52052085
has answer: http://stackoverflow.com/a/52052062
possible better answer: http://stackoverflow.com/a/52052051
has title: List comprehension from dict of lists
upvote count: 3
has answer: http://stackoverflow.com/a/52052252
tagged with: list-comprehension
answer count: 4
linked to: http://stackoverflow.com/q/1198777
downvote count: 0
accepted answer: http://stackoverflow.com/a/52052252
type: Question
type: AnsweredQuestion

http://stackoverflow.com/a/52109857
has body: Use pandas library for this. import pandas as pd df = pd.DataFrame(found, columns=['dropbearid', 'distance']) df = df.drop(0) # drop the header row df.to_csv('Found.csv', index=False)
answers question: http://stackoverflow.com/q/52108730
score: 0
type: Answer

http://stackoverflow.com/q/52064821
has comment: http://stackoverflow.com/comment/91133498
has comment: http://stackoverflow.com/comment/91085801
has title: Django OSError [Errno 13] Permission denied: '/home/django/media_cdn/1.png' solution
score: 0
has comment: http://stackoverflow.com/comment/91080532
has comment: http://stackoverflow.com/comment/91204727
has comment: http://stackoverflow.com/comment/91204618
has comment: http://stackoverflow.com/comment/91109240
type: UnansweredQuestion
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/91110314
has body: setting.py STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static"), #'/var/www/static/', ] STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), "static_cdn") MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR), "media_cdn") MEDIA_URL = '/media/' models.py image = models.ImageField(null=True, blank=True, height_field="height_field", width_field ="width_field") The error text is written in the title. It is telling me it doesn't have permission.Please help...
answer count: 0
has comment: http://stackoverflow.com/comment/91094718
has comment: http://stackoverflow.com/comment/91115842
has comment: http://stackoverflow.com/comment/91204730
type: Question

http://stackoverflow.com/q/52019218
has comment: http://stackoverflow.com/comment/90988756
tagged with: python
has body: I am testing the code below for serialization of a Logistic Regression model using JSON. It seems to write the JSON file OK, but I am unable to read the JSON file successfully. I got the following error message for lr.predict(X). "AttributeError: 'list' object has no attribute 'shape'" Any input would be highly appreciated. from sklearn.linear_model import LogisticRegression from sklearn.datasets import load_iris import os import json import codecs import numpy as np iris = load_iris() X, y = iris.data, iris.target lr = LogisticRegression() lr.fit(X, y) attr = lr.__dict__ New_attr = attr keys = New_attr.keys() # -------------------- # Converting array to list # -------------------- New_attr['coef_'] = attr['coef_'].tolist() New_attr['classes_'] = attr['classes_'].tolist() New_attr['n_iter_'] = attr['n_iter_'].tolist() New_attr['intercept_'] = attr['intercept_'].tolist() # -------------------- # Writing the JSON file... # -------------------- json_file = "file.json" json.dump(New_attr, codecs.open(json_file, 'w', encoding='utf-8'), sort_keys=True, indent=4) # -------------------- # Reading the JSON file... # -------------------- obj_text = codecs.open(json_file, 'r', encoding='utf-8').read() b_new = json.loads(obj_text) lr = LogisticRegression() print(b_new) lr.__dict__ = dict(b_new) lr.predict(X)
has answer: http://stackoverflow.com/a/52020021
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/48328012
has comment: http://stackoverflow.com/comment/90988841
tagged with: logistic-regression
type: Question
tagged with: http://stackoverflow.com/tag/json
score: 0
answer count: 1
duplicate of: http://stackoverflow.com/q/48328012
has comment: http://stackoverflow.com/comment/90990516
has title: Python: Serialization of Logistic Regression to JSON and loading JSON
accepted answer: http://stackoverflow.com/a/52020021

http://stackoverflow.com/q/52014482
tagged with: regex
has title: Chunking sentences using the word 'but' with RegEx
favorite count: 0
tagged with: chunking
tagged with: python
type: AnsweredQuestion
score: 3
upvote count: 3
possible better answer: http://stackoverflow.com/a/53496641
has body: I am attempting to chunk sentences using RegEx at the word 'but' (or any other coordinating conjunction words). It's not working... sentence = nltk.pos_tag(word_tokenize("There are no large collections present but there is spinal canal stenosis.")) result = nltk.RegexpParser(grammar).parse(sentence) DigDug = nltk.RegexpParser(r'CHUNK: {.*&lt;CC&gt;.*}') for subtree in DigDug.parse(sentence).subtrees(): if subtree.label() == 'CHUNK': print(subtree.node()) I need to split the sentence "There are no large collections present but there is spinal canal stenosis." into two: 1. "There are no large collections present" 2. "there is spinal canal stenosis." I also wish to use the same code to split sentences at 'and' and other coordinating conjunction (CC) words. But my code isn't working. Please help.
type: Question
tagged with: nltk
downvote count: 0
answer count: 2
has answer: http://stackoverflow.com/a/52018630
accepted answer: http://stackoverflow.com/a/52018630
has answer: http://stackoverflow.com/a/53496641

http://stackoverflow.com/q/52083522
has comment: http://stackoverflow.com/comment/91121022
tagged with: download
answer count: 0
type: UnansweredQuestion
tagged with: selenium
has comment: http://stackoverflow.com/comment/91145385
upvote count: 1
tagged with: python
has title: Selecting saveas button when downloading file from browser
has body: I've written a code with selenium and pyautogui to click around on a website and be able to click the save button with pyautogui after the download button has been clicked with selenium. I wanted to know if it was possible to click the saveas button instead and change the file name with python. the code I have: driver.find_by_element_by_xpath("//a[@id='Ribbon.Library.Action.ExportToSpreadsheet-Medium']").click() saveButton = pyautogui.locateCenterOnScreen("C:\\User\\Documents\\savebutton.jpg") pyautogui.click(position[0], position[1]) so what this does is click the download button and then compares the picture of the button and clicks the save option. But theres an arrow on the button to click saveas and that's what I need to click so I can choose the destination to save it and change the name of the file. Was wondering if there is a way to do this. the button looks like this also I am downloading from Edge, I'm not looking to use chrome or any other browser.
tagged with: save-as
score: 1
has comment: http://stackoverflow.com/comment/91119116
tagged with: microsoft-edge
type: Question
has comment: http://stackoverflow.com/comment/91124962
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/91120826

http://stackoverflow.com/q/52101712
tagged with: python
answer count: 0
type: UnansweredQuestion
type: Question
has comment: http://stackoverflow.com/comment/91154460
tagged with: numpy
score: 0
tagged with: pandas
has title: Create unique list from column in multiple dataframes, create excel workbooks based off that, and put rows from dataframes on different worksheets?
has comment: http://stackoverflow.com/comment/91154256
has body: So here, I have 2 data frames, each has Name1 and Name2. I am trying to create an excel sheet named BOB + SAM, have that data frames name as the sheet name and the one record that is it. Ryan Connor is in both data frames, so I want to create an excel file named Ryan + Connor, have data frame 1 record on sheet 1 (named something) and data frames 2 records on sheet 2 In my actual use case, I will have many more than 2 dataframes. The below code works properly for 1 data frame however not for more than 1 names=df['A'].unique().tolist() from pandas import ExcelWriter import os path="/name" os.chdir(path) for i in names: writer = ExcelWriter(str(i)+'.xlsx') i=pd.DataFrame(df.loc[df['A']==i]) i.to_excel(writer)
has comment: http://stackoverflow.com/comment/91154377

http://stackoverflow.com/comment/91036358
type: AnswerComment
type: Comment
score: 1
comment on: http://stackoverflow.com/a/52042744
has text: Nice contribution. Double check that you are comparing apples to apples. What I presented was an assignment to the dataframe and @Wen presented a Series. What I'm suggesting is that the assignment of the series to the dataframe has some overhead that may not be accounted for in your test.

http://stackoverflow.com/comment/91040026
comment on: http://stackoverflow.com/q/52044389
score: 0
type: Comment
type: QuestionComment
has text: Multiprocessing Actually works in this case. If you wanna find centroid and other patterns on that large image data simply you can run the script to the certain batch size and put the program to **sleep** for few seconds. It will take a very long time as you think but it will help you to stop killing the script.

upsert
tags question: http://stackoverflow.com/q/52007418
type: Tag
tag name: upsert

http://stackoverflow.com/comment/91143153
comment on: http://stackoverflow.com/a/52096436
type: AnswerComment
has text: Isn't this identical to my one ;). Except you split by `;` twice for some reason. And feed a generator expression to `str.join` which is inefficient vs list comprehension.
type: Comment
score: 1

http://stackoverflow.com/a/54457536
answers question: http://stackoverflow.com/q/51960655
type: Answer
has body: see content of one level up (https://download.opensuse.org/repositories/devel:/languages:/python/) : openSUSE_Leap_42.3 has been dropped in favor of openSUSE_Leap_15.0
score: 0

http://stackoverflow.com/a/52038830
score: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/52035117
type: Answer
answers question: http://stackoverflow.com/q/52035117
has body: I would use Spark Window to solve such a problem. Assuming there's only one row per day where type is not null: from pyspark.sql import functions as F from pyspark.sql import Window df = sqlContext.createDataFrame([ [(1),('2018-03-21 12:25:01'), ('a')], [(1),('2018-03-21 12:25:02'), (None)], [(1),('2018-03-22 12:25:03'), ('b')], [(1),('2018-03-22 12:25:04'), (None)], [(2),('2018-03-21 12:25:01'), ('c')], [(2),('2018-03-21 12:25:02'), (None)], [(2),('2018-03-21 12:25:03'), (None)], ], ['id', 'date', 'type']) df2 = df.select('*', F.to_date('date', 'yyyy-MM-dd HH:mm:ss').alias('date2')) windowSpec = Window.partitionBy('id', 'date2') typee = F.max('type').over(windowSpec) df3 = df2.select('id', 'date', typee.alias('type')) df3.show() &gt;&gt;&gt; +---+-------------------+----+ | id| date|type| +---+-------------------+----+ | 2|2018-03-21 12:25:01| c| | 2|2018-03-21 12:25:02| c| | 2|2018-03-21 12:25:03| c| | 1|2018-03-22 12:25:03| b| | 1|2018-03-22 12:25:04| b| | 1|2018-03-21 12:25:01| a| | 1|2018-03-21 12:25:02| a| +---+-------------------+----+

http://stackoverflow.com/comment/91163419
score: 0
comment on: http://stackoverflow.com/a/52106179
type: AnswerComment
type: Comment
has text: Sorry, I think I was not quite clear in my question. I don't want the string to be the return value, I simply want some behavior, for example the `print` statement, to run each time the generator yields. However, the values returned by `next()` should not be modified by the decorator.

http://stackoverflow.com/q/51963174
tagged with: dictionary
answer count: 0
has comment: http://stackoverflow.com/comment/90884797
type: Question
has comment: http://stackoverflow.com/comment/90876833
has comment: http://stackoverflow.com/comment/90917182
has comment: http://stackoverflow.com/comment/90876920
has comment: http://stackoverflow.com/comment/90877663
tagged with: hyperparameters
has comment: http://stackoverflow.com/comment/90916571
score: 0
tagged with: scikit-learn
has comment: http://stackoverflow.com/comment/90876876
has title: Can I reference on a variable within a python dictionary? How do I programm a gridsearch for hyperparameters depending on each other?
has comment: http://stackoverflow.com/comment/90884815
has body: I want to optimize Hyperparmeters for my customised sklearn model using randomizedsearchCV. Unfortunately there are two parameters depending on each other. Meaning: the size of n_unit is dependent on k. Example: when k is 2, then n_units should be a list of size 2. When k is 3 then n_units has to be of size 3. So I basically need something like: dict(K=scipy.stats.randint(1,50), n_units=[np.random.randint(1,60,K)]) However, this does not work. Is there any way to search for hyperparameters depending on each other?
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/q/51995611
has answer: http://stackoverflow.com/a/51995714
accepted answer: http://stackoverflow.com/a/51995714
upvote count: 1
has title: Datetime 12 Hour Format Pandas Python
type: Question
has comment: http://stackoverflow.com/comment/90940758
has comment: http://stackoverflow.com/comment/90940737
score: 1
answer count: 1
downvote count: 0
favorite count: 0
tagged with: pandas
tagged with: datetime
tagged with: python
has body: I'm trying to convert this time format to datetime: Date Hour 05/12/17 2:15 p 05/12/17 2:20 p 05/12/17 2:25 p Using: pd.to_datetime(df['Hour'], format="%I:%M %p") Getting this error: ValueError: time data '05/12/17 2:15 p' does not match format '%d/%m/%y %I:%M %p' (match)
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90940666

instantiation
type: Tag
tags question: http://stackoverflow.com/q/52022790
tag name: instantiation

http://stackoverflow.com/a/51968680
score: 15
has comment: http://stackoverflow.com/comment/133531217
upvote count: 15
has comment: http://stackoverflow.com/comment/137228492
type: Answer
has comment: http://stackoverflow.com/comment/137946864
answers question: http://stackoverflow.com/q/51959646
downvote count: 0
has body: Figured it out, the method actually required base64 encoded binary data, which wasn't really specified in the docs, the doc just said base64-encoded bytes. self.rekog_client = boto3.client('rekognition', 'us-east-1') with open('cat_pic600.jpg', "rb") as cf: base64_image=base64.b64encode(cf.read()) base_64_binary = base64.decodebytes(base64_image) resp = self.rekog_client.detect_labels(Image={'Bytes': base_64_binary})

http://stackoverflow.com/a/51977078
has body: I'm the dill author. You should use pickle if all the objects you want to pickle can be pickled by pickle.dump. If one or more of the objects are unpicklable with pickle, then use dill. See the pickle docs for what can be pickled with pickle. dill can pickle most python objects, with some exceptions. If you want to consider alternatives to dill, there's cloudpickle, which has a similar functionality to dill (and is very similar to dill when using dill.settings['recurse'] = True). There are other serialization libraries, like json, but they actually serialize less objects than pickle does, so you'd not choose them to serialize a user-built class.
type: Answer
accepted answer of: http://stackoverflow.com/q/51971579
answers question: http://stackoverflow.com/q/51971579
downvote count: 0
score: 1
upvote count: 1
type: AcceptedAnswer

http://stackoverflow.com/comment/91125153
has text: `if` is not `elif`.
comment on: http://stackoverflow.com/q/52087398
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/91040296
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52039621
has text: @DanielGale Yes.

http://stackoverflow.com/comment/91066892
has text: You are passing in the wrong class to `super()`. Pass in the **current** class, `Grandchild`.
comment on: http://stackoverflow.com/q/52058400
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/q/51984042
tagged with: python
tagged with: indexing
type: AnsweredQuestion
downvote count: 0
score: 1
tagged with: slice
type: Question
has comment: http://stackoverflow.com/comment/90955982
accepted answer: http://stackoverflow.com/a/52008194
tagged with: numpy-ndarray
has answer: http://stackoverflow.com/a/52008194
upvote count: 1
has title: Tuple of colons in ndarray slicing
answer count: 1
favorite count: 0
has body: In NumPy documentation we see a Note in the beginning: In Python, x[(exp1, exp2, ..., expN)] is equivalent to x[exp1, exp2, ..., expN]; the latter is just syntactic sugar for the former. Why doesn't x[(:,:)] work instead of x[:,:] then? For example if the concatenation of slices is needed, one must use a[(0,) + (slice(None),)] instead of a[(0,) + (:,)]
has comment: http://stackoverflow.com/comment/90917507

http://stackoverflow.com/q/51971180
tagged with: regression
has comment: http://stackoverflow.com/comment/90893247
has comment: http://stackoverflow.com/comment/90893484
type: Question
possible better answer: http://stackoverflow.com/a/52085844
has title: Keras GRU model predicts only [-0., -0., -0., -0., -0.]
tagged with: neural-network
has comment: http://stackoverflow.com/comment/90893322
upvote count: 2
has comment: http://stackoverflow.com/comment/90893267
answer count: 3
has comment: http://stackoverflow.com/comment/90893530
has comment: http://stackoverflow.com/comment/90892893
tagged with: keras
has comment: http://stackoverflow.com/comment/90893233
has answer: http://stackoverflow.com/a/62309380
favorite count: 0
has answer: http://stackoverflow.com/a/52085844
tagged with: gated-recurrent-unit
has answer: http://stackoverflow.com/a/52102658
accepted answer: http://stackoverflow.com/a/52102658
tagged with: python
has comment: http://stackoverflow.com/comment/90893138
has body: I'm trying to predict 5 periodic prices of cryptocurrency based on previous 50 inputs. &gt;&gt;&gt; X_train.shape, X_test.shape, Y_train.shape, Y_test.shape ((291314, 50, 8), (72829, 50, 8), (291314, 5), (72829, 5)) Here I have 50 previous samples x 8 features as input sample and prices for 5 next periods as outputs I've build model with this code: from tensorflow.keras.layers import GRU from tensorflow.keras.models import Sequential from tensorflow.keras.layers import Dense, Dropout, Activation model = Sequential() model.add(GRU(units=50, input_shape=X_train.shape[1:], return_sequences=False)) model.add(Activation('tanh')) model.add(Dropout(0.2)) model.add(Dense(NFS)) model.add(Activation('relu')) model.compile(loss='mse', optimizer='adam') model.fit(X_train, Y_train, batch_size=50, validation_data=(X_test, Y_test), epochs=2) That gave me output: Train on 291314 samples, validate on 72829 samples Epoch 1/2 291314/291314 [==============================] - 487s 2ms/step - loss: 0.0107 - val_loss: 0.2502 Epoch 2/2 291314/291314 [==============================] - 463 2ms/step - loss: 0.0103 - val_loss: 0.2502 After this step I've tried to predict outputs for X_test but instead of prediction I've got matrix with correct shape but full of zeros instead of any predictions: &gt;&gt;&gt; model.predict(X_test) array([[-0., -0., -0., -0., -0.], [-0., -0., -0., -0., -0.], [-0., -0., -0., -0., -0.], ..., [-0., -0., -0., -0., -0.], [-0., -0., -0., -0., -0.], [-0., -0., -0., -0., -0.]], dtype=float32) Why I'm getting this bad? And do I use correct way to do what I want? UPD: Here is the full notebook.
score: 2
has comment: http://stackoverflow.com/comment/90892872
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90894921
downvote count: 0

http://stackoverflow.com/comment/91162751
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52105834
score: 1
has text: What is sh? Does it have a Helm attribute? Add why are you setting a module as an instance variable anyway?

http://stackoverflow.com/comment/91003735
has text: star-unpacking inside comprehensions was explicitly considered and rejected: see [PEP 448](https://www.python.org/dev/peps/pep-0448/) for details. The invalid syntax in the `return` surprises me, though; it's possible that this is simply an oversight.
comment on: http://stackoverflow.com/q/52026406
type: Comment
type: QuestionComment
score: 2

http://stackoverflow.com/comment/91127485
type: Comment
comment on: http://stackoverflow.com/a/52087224
has text: Thank you! I updated the question with your suggestions and still getting an error (please, see at the top)
type: AnswerComment
score: 0

http://stackoverflow.com/comment/90965478
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52007341
has text: Will `apply_async` take advantage of the pool of `n` processes? Using multiple process is the objective.

http://stackoverflow.com/comment/91137644
comment on: http://stackoverflow.com/q/52093838
score: 2
type: Comment
type: QuestionComment
has text: You need square brackets to index an array in Python `Sn[z]=1`

http://stackoverflow.com/comment/91210512
has text: But can you show me how to reproduce the parameters? (I'm a total noob at python)
type: AnswerComment
type: Comment
score: 1
comment on: http://stackoverflow.com/a/52081156

http://stackoverflow.com/comment/90927136
has text: @LunchBox did you add any ? `ddf4[~df4.applymap(lambda x : str.startswith(x,'--')).any(1)]`
type: Comment
score: 0
comment on: http://stackoverflow.com/a/51987693
type: AnswerComment

http://stackoverflow.com/q/52063320
tagged with: python-3.x
has answer: http://stackoverflow.com/a/52063368
tagged with: python
accepted answer: http://stackoverflow.com/a/52063368
type: AnsweredQuestion
type: Question
has title: Convert multiple columns into a MultiIndex
answer count: 1
score: 0
tagged with: pandas
has body: A library I use returns a DataFrame for analysis. This DataFrame is a simple time series with multiple columns. I would like to join a couple of these columns to a MultiIndex and export the result as a JSON file. Example: In[2]: df.loc[:, ['open', 'high', 'low', 'close']].tail() Out[2]: open high low close period_close 2018-08-20 23:56:00+00:00 0.001837 0.001837 0.001837 0.001837 2018-08-20 23:57:00+00:00 0.001837 0.001837 0.001837 0.001837 2018-08-20 23:58:00+00:00 0.001837 0.001841 0.001830 0.001841 2018-08-20 23:59:00+00:00 0.001827 0.001840 0.001814 0.001832 2018-08-21 00:00:00+00:00 0.001824 0.001831 0.001824 0.001831 I would like to transform this table into the following format: candle period_close 2018-08-20 23:56:00+00:00 [0.001837, 0.001837, 0.001837, 0.001837] 2018-08-20 23:57:00+00:00 [0.001837, 0.001837, 0.001837, 0.001837] 2018-08-20 23:58:00+00:00 [0.001837, 0.001841, 0.001830, 0.001841] 2018-08-20 23:59:00+00:00 [0.001827, 0.001840, 0.001814, 0.001832] 2018-08-21 00:00:00+00:00 [0.001824, 0.001831, 0.001824, 0.001831]

http://stackoverflow.com/a/51995951
upvote count: 1
downvote count: 0
has body: Comments are not placeholders for if statements so use pass. ... if selection == 1: #Connect pass ...
answers question: http://stackoverflow.com/q/51995928
type: Answer
score: 1

http://stackoverflow.com/comment/91040326
comment on: http://stackoverflow.com/q/52044711
score: 0
type: QuestionComment
has text: For it to be transparent it needs to be the right color format, do you know what color format your png is?
type: Comment

http://stackoverflow.com/q/52062579
has title: Write a python program to create a list and converting the data type of the first element into integer
favorite count: 0
has comment: http://stackoverflow.com/comment/91075547
has comment: http://stackoverflow.com/comment/91075623
downvote count: 8
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/91075537
upvote count: 1
has comment: http://stackoverflow.com/comment/91075508
type: Question
has answer: http://stackoverflow.com/a/52062625
answer count: 1
has comment: http://stackoverflow.com/comment/91075642
score: -7
has body: list=["ABART 20","CDXEF 50","BKWRK 25"] g=int(list[0]) g Output: " invalid literal for int() with base 10:'ABART 20'. Can anyone explain me ??

http://stackoverflow.com/q/52006325
has answer: http://stackoverflow.com/a/52006437
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/90962531
accepted answer: http://stackoverflow.com/a/52006437
favorite count: 0
linked to: http://stackoverflow.com/q/46103044
tagged with: python
type: AnsweredQuestion
score: 2
upvote count: 2
has title: Choose indices in numpy arrays on particular dimensions
type: Question
tagged with: numpy
has body: It is hard to find a clear title but an example will put it clearly. For example, my inputs are: c = np.full((4, 3, 2), 5) c[:,:,1] *= 2 ix = np.random.randint(0, 2, (4, 3)) if ix is: array([[1, 0, 1], [0, 0, 1], [0, 0, 1], [1, 1, 0]]) if want as a result: array([[10, 5, 10], [ 5, 5, 10], [ 5, 5, 10], [10, 10, 5]]) My c array can be of arbitrary dimensions, as well a the dimension I want to sample in. It sounds like interpolation, but I'm reluctant to construct a be array of indices each time I want to apply this. Is there a way of doing this using some kind of indexing on numpy arrays ? Or do I have to use some interpolation methods... Speed and memory are a concern here because I have to do this many times, and the arrays can be really large. Thanks for any insight !
tagged with: indexing
duplicate of: http://stackoverflow.com/q/46103044
tagged with: arrays
has comment: http://stackoverflow.com/comment/90962594

http://stackoverflow.com/comment/90938458
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51994367
has text: yes well when i put it on the same indentation level it wont run until i unindent it

http://stackoverflow.com/a/52077334
upvote count: 1
score: 1
type: AcceptedAnswer
downvote count: 0
has body: The workaround according to https://www.reddit.com/r/Telegram/comments/6fta1h/getting_is_not_on_telegram_yet_would_you_like_to/ is to add 5000 contacts, wait a while (could be a long while), then add up to 5000 more. More than 10000 total may not be possible.
accepted answer of: http://stackoverflow.com/q/52077292
type: Answer
answers question: http://stackoverflow.com/q/52077292

http://stackoverflow.com/q/51964177
answer count: 1
has body: def strategy(board): import random #t_1 =, t_2 and t_3 are ranges from 0 to a object named board t_1 = [board[0] - i for i in range (0,(board[0] + 1))] t_2 = [board[1] - i for i in range (0,(board[1] + 1))] t_3 = [board[2] - i for i in range (0,(board[2] + 1))] #randomly chooses a single number from each range x = random.choice (t_1) y = random.choice (t_2) z = random.choice (t_3) #randomly chooses one of those 3 randomly chosen numbers q = random.choice (x,y,z) As you can see the code randomly chooses a number from 3 different ranges and assigns each of them to a different variable. Once that is done, it randomly chooses one out of the 3 numbers chosen previously and assigns that a new variable. I keep getting the error mentioned in the title. I cant figure out whats wrong. Thanks for the help p.s. I am using python 3 with PyCharm
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/90878362
score: 0
has title: error: choice() takes 2 positional arguments but 4 were given
type: Question
has answer: http://stackoverflow.com/a/51964195
tagged with: random

http://stackoverflow.com/q/52029343
has body: I want to make a very simple network graph for some links between documents that I've extracted, and display it in an existing Django application. I've looked at a bunch of Bokeh/Django integrations and things along those lines but nothing seems appropriate. Therefore I've decided to go ahead and try D3. I don't know any Javascript. I copied the template provided here: http://bl.ocks.org/mbostock/2706022 and this is fine for my purposes. All I need to do is to provide my own data. I can build up a list of dictionaries in the view and pass these as a context. I can access that context in the template with {{ data }}. However, what I don't know how to do is to then feed that to the javascript. This is the relevant part that I'll need to change: var links = [ {source: "Microsoft", target: "Amazon", type: "licensing"}, {source: "Microsoft", target: "HTC", type: "licensing"}, {source: "Samsung", target: "Apple", type: "suit"}, {source: "Motorola", target: "Apple", type: "suit"}, {source: "Nokia", target: "Apple", type: "resolved"}, ... {source: "Nokia", target: "Qualcomm", type: "suit"} ]; This looks like a list of dictionaries. But I don't know, there's some bare words in there so I'm not sure how Javascript sees this thing and how to cast the python context into whatever this is. I imagine something along the lines of var links = &lt;cast&gt;({{data}}) How do I implement this so that I can pass this D3 code my own data?
answer count: 1
tagged with: templates
tagged with: django
tagged with: python
type: AnsweredQuestion
has title: Django send data to Javascript in template
accepted answer: http://stackoverflow.com/a/52029443
type: Question
tagged with: javascript
has answer: http://stackoverflow.com/a/52029443
score: 0

http://stackoverflow.com/comment/90944428
score: 0
type: Comment
has text: Yes, but you are not alone. Many people don't understand. True-True vectorization takes advantage of algorithms that lower the time complexity of the problem. However, we all too often call doing stuff with vectors "vectorization". It is very fast from a raw computational perspective, but it can also be problematic as you've seen. My approach is O(n^2) in computation and memory. My next approach will still be O(n^2) but it will be much better on memory... and probably quicker.
comment on: http://stackoverflow.com/a/51997389
type: AnswerComment

http://stackoverflow.com/comment/90901217
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/51975343
score: 0
has text: This is a duplicate question https://stackoverflow.com/questions/37287938/sort-pandas-dataframe-by-value

http://stackoverflow.com/q/51987556
tagged with: dataframe
has comment: http://stackoverflow.com/comment/90925284
type: Question
has answer: http://stackoverflow.com/a/51987922
linked to: http://stackoverflow.com/q/21608228
has comment: http://stackoverflow.com/comment/90924964
has comment: http://stackoverflow.com/comment/90924703
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/90925073
tagged with: pandas
tagged with: python
accepted answer: http://stackoverflow.com/a/51987922
favorite count: 0
has body: I have the following dataframe called df containing a variable called Category. I would like to create new_variable with the below mentioned values in Python. How do I do? df = pd.DataFrame({ 'Category': [ 'Foreign Stocks', 'Stocks China', 'Stocks', 'Bonds', 'Bonds USA', 'Bonds India' ], 'New_Variable': [ 'Stocks', 'Stocks', 'Stocks', 'Bonds', 'Bonds', 'Bonds' ] }) df Category New_Variable 0 Foreign Stocks Stocks 1 Stocks China Stocks 2 Stocks Stocks 3 Bonds Bonds 4 Bonds USA Bonds 5 Bonds India Bonds Maybe it is me who cannot translate other similar answers to a solution for me, but I have not been able to find the same question elsewhere. /Jonas
upvote count: 2
has title: Change variable based on other variable in Python
type: AnsweredQuestion
score: 2
has comment: http://stackoverflow.com/comment/90925071
tagged with: conditional-statements
tagged with: if-statement
has comment: http://stackoverflow.com/comment/90926024

http://stackoverflow.com/q/52059966
has comment: http://stackoverflow.com/comment/91070546
has title: Finding unique indices between arrays returned by numpy.where
tagged with: python
has body: I have two numpy arrays returned by the function numpy.where, like so: A = numpy.where(img == 255) B = numpy.where(img2 != 0) I need to find number of unique coordinates in A and B. I initially contemplated using numpy.intersect1d to get the number of common indices, and subtract this from the total number of elements from both arrays. But these arrays are not 1-dimensional, so I'm not sure how to go about it. Any suggestions how I can accomplish this? Thanks
accepted answer: http://stackoverflow.com/a/52060313
type: Question
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52060313
has comment: http://stackoverflow.com/comment/91070631
tagged with: numpy
answer count: 1
has comment: http://stackoverflow.com/comment/91070626
has comment: http://stackoverflow.com/comment/91070462
score: 0

http://stackoverflow.com/comment/91121099
comment on: http://stackoverflow.com/q/52072085
has text: Possible duplicate of [Proper way to declare custom exceptions in modern Python?](https://stackoverflow.com/questions/1319615/proper-way-to-declare-custom-exceptions-in-modern-python)
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52064106
favorite count: 0
downvote count: 3
has comment: http://stackoverflow.com/comment/91078826
tagged with: python
tagged with: string-decoding
tagged with: python-3.x
has title: Decode ASCII string in Python 3
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91078815
has body: Got a string in ASCII (with only ASCII value ranges for A-Z, a-z, and " "), want to decode it. ex. "781059910132" cooresponds to "Nice " Is there an easy way to do this in Python 3?
has comment: http://stackoverflow.com/comment/91078869
type: Question
has answer: http://stackoverflow.com/a/52064254
score: -1
tagged with: ascii
upvote count: 2
has comment: http://stackoverflow.com/comment/91078688
tagged with: encoding
answer count: 1

http://stackoverflow.com/q/52109777
upvote count: 4
tagged with: selenium-webdriver
downvote count: 0
tagged with: selenium
tagged with: webdriver
type: Question
score: 4
answer count: 3
has answer: http://stackoverflow.com/a/52110529
favorite count: 0
has answer: http://stackoverflow.com/a/52110631
tagged with: python-3.x
has title: How to wait for a button to be clicked by user in Selenium web-driver using python?
type: UnansweredQuestion
has body: I've a Login form like below. Textbox for username, password, captcha and SIGN-IN button are clickable and visible from beginning. Using Selenium I can provide input for username & password. Then, I've to wait for entering the CAPTCHA by users, and then click on SIGN IN button by user again. After clicking the SIGN-IN button webdriver should take the control for next. So, webdriver should wait until the SIGN-IN button is clicked (for user1, it may take 2 seconds to enter CAPTCHA, but for user2 it may take 5 seconds to enter the CAPTCHA). This is the HTML for SIGN IN button. SIGN IN I tried with below, But, it's not working. from selenium import webdriver from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC driver = webdriver.Chrome() driver.get("url") btnSignIn = driver.find_element_by_xpath("//form/button[@type='submit' and @class='search_btn']") WebDriverWait(driver, timeout=600).until(EC.staleness_of(btnSignIn)) How can I do that ? Thanks in advance.
has answer: http://stackoverflow.com/a/70141882
tagged with: python

http://stackoverflow.com/a/51992699
upvote count: 4
answers question: http://stackoverflow.com/q/51989635
type: AcceptedAnswer
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/51989635
has comment: http://stackoverflow.com/comment/90936598
has body: Set source='cuisinetypes_set' while serializeing the queryset as, class FoodCuisineSerializer(serializers.ModelSerializer): cuisine_type = CuisineTypesSerializer(many=True, read_only=True, source='cuisinetypes_set') class Meta: model = FoodCuisine fields = ('cuisine', 'cuisine_type') Reference 1. reverse relationship 2. source in DRF-Serializer UPDATE 1 Since FoodCuisine.objects.all() is a QuerySet (list type object), you should pass many=True in serializer, as y = FoodCuisineSerializer(FoodCuisine.objects.all(), many=True)
score: 4

http://stackoverflow.com/comment/91066213
type: QuestionComment
score: 2
has text: https://dev.mysql.com/doc/connector-python/en/connector-python-api-mysqlcursor-executemany.html
type: Comment
comment on: http://stackoverflow.com/q/52058007

http://stackoverflow.com/comment/91010134
type: Comment
has text: PS, you can _always_ do it with pure comprehensions, it just isn't always a good idea… To cram an assignment into an comprehension (without assignment expressions), just throw a 1-element loop in outside the other loops: `[[next(list2_iterator) for _ in sublist] for list2_iterator in [iter(list2)] for sublist in list1]`. Obviously nowhere near as readable as what you have now.
type: AnswerComment
score: 2
comment on: http://stackoverflow.com/a/52029765

http://stackoverflow.com/q/52058611
tagged with: android
tagged with: python
tagged with: kivy
linked to: http://stackoverflow.com/q/23952484
answer count: 0
score: 1
has title: App crash with kivy and bs4
upvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/91071347
downvote count: 0
has comment: http://stackoverflow.com/comment/91070763
has comment: http://stackoverflow.com/comment/92834888
tagged with: buildozer
favorite count: 0
tagged with: beautifulsoup
has body: I build the apk in the kivy VM and after building, when I open the app on android, crashed I get first this error: ImportError: cannot import name _htmlparser I search on the internet i and I found this solution: Buildozer compiles apk, but it crashes on android But after do this, crash again but with another error, this: bs4.FeatureNotFound: Couldn't find a tree builder with the features you requested: html.parser. Do you need to install a parser library? And now I don't know how can I do...I tried to replace soup = BeautifulSoup(RESPONSE.content, "html.parser") with soup = BeautifulSoup(RESPONSE.content, "lxml") But I get the same error In the buildozer.spec file i have this: https://hastebin.com/ayepobufon.shell And all the libraries are updated, I use python2 and Kivy VM to build apk with command buildozer android debug
type: UnansweredQuestion

http://stackoverflow.com/q/51985203
answer count: 1
has body: I'm trying to install stitch2d with following command pip install stitch2d but i'm getting following error while trying to install it. writing top-level names to pip-egg-info/stitch2d.egg-info/top_level.txt writing pip-egg-info/stitch2d.egg-info/PKG-INFO Traceback (most recent call last): File "&lt;string&gt;", line 1, in &lt;module&gt; File "/tmp/pip-install-7fo41qxe/stitch2d/setup.py", line 35, in &lt;module&gt; zip_safe=False) File "/home/gulve/anaconda3/lib/python3.5/site-packages/setuptools/__init__.py", line 140, in setup return distutils.core.setup(**attrs) File "/home/gulve/anaconda3/lib/python3.5/distutils/core.py", line 148, in setup dist.run_commands() File "/home/gulve/anaconda3/lib/python3.5/distutils/dist.py", line 955, in run_commands self.run_command(cmd) File "/home/gulve/anaconda3/lib/python3.5/distutils/dist.py", line 974, in run_command cmd_obj.run() File "/home/gulve/anaconda3/lib/python3.5/site-packages/setuptools/command/egg_info.py", line 288, in run writer(self, ep.name, os.path.join(self.egg_info, ep.name)) File "/home/gulve/anaconda3/lib/python3.5/site-packages/setuptools/command/egg_info.py", line 613, in write_pkg_info metadata.write_pkg_info(cmd.egg_info) File "/home/gulve/anaconda3/lib/python3.5/distutils/dist.py", line 1107, in write_pkg_info self.write_pkg_file(pkg_info) File "/home/gulve/anaconda3/lib/python3.5/site-packages/setuptools/dist.py", line 91, in write_pkg_file long_desc = rfc822_escape(self.get_long_description()) File "/home/gulve/anaconda3/lib/python3.5/distutils/util.py", line 471, in rfc822_escape lines = header.split('\n') TypeError: a bytes-like object is required, not 'str' ---------------------------------------- Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-install-7fo41qxe/stitch2d/ i have updated supertool but it still no luck
accepted answer: http://stackoverflow.com/a/51986554
type: AnsweredQuestion
has title: Issue in installing stitch2d
has answer: http://stackoverflow.com/a/51986554
type: Question
tagged with: python
tagged with: installation
tagged with: package
score: 0
tagged with: pip

http://stackoverflow.com/comment/90901706
type: QuestionComment
comment on: http://stackoverflow.com/q/51975411
score: 0
has text: http://docs.sqlalchemy.org/en/latest/orm/join_conditions.html#specifying-alternate-join-conditions
type: Comment

http://stackoverflow.com/comment/90926433
type: AnswerComment
comment on: http://stackoverflow.com/a/51976132
type: Comment
has text: @user1459519: it depends on what you mean by "only the basic tkinter widgets". I don't see how ttk is any less "basic". Also, you can use either `grid` or `pack` (or even `place`) to get the same effect. I just used `pack` for the example because it requires fewer lines of code, and is arguably the right choice when stacking things top-to-bottom.
score: 0

http://stackoverflow.com/q/52005192
tagged with: for-loop
possible better answer: http://stackoverflow.com/a/52005294
upvote count: 0
score: -2
has comment: http://stackoverflow.com/comment/90959964
has body: I guess I could be able to handle the rest of the project but not on how to start the program. My problem scenario is, I will ask the user to input a random number. for example, he input 3. I should create then a program that iterates 3 times, while at the same time in between, asking the user some input. the idea is shown below: Number 1: Enter your number: Enter your age: Number 2: Enter your number: Enter your age: Number 3: Enter your number: Enter your age: In the end of my program I will need to do calculation, for example, which number item is the oldest? is it number1, number2, or number3...I think I could be able to handle that, My problem is how can store each Number item in one variable, with all the iterations going on....Im super confused. your help is much appreciated. thank you
has title: Listing items and inputting information in those items
answer count: 2
tagged with: while-loop
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/52005294
has comment: http://stackoverflow.com/comment/90977368
tagged with: python
linked to: http://stackoverflow.com/q/4730949
has comment: http://stackoverflow.com/comment/90959911
has answer: http://stackoverflow.com/a/52005518
accepted answer: http://stackoverflow.com/a/52005518
type: AnsweredQuestion
downvote count: 2
type: Question

http://stackoverflow.com/q/52047625
tagged with: word-embedding
tagged with: word2vec
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/52067799
has body: Background I am trying to train a Skip-gram word2vec model using negative sampling. from what I understand I need to generate couples (target, context) and a label where 0 = not in context and 1 = in context. What I am unsure about: Should we make skipgram couples sentence by sentence? or should we flatten the sentences in to one large sentence and generate skipgrams from that? In other words, should the generated couples span sentences? The only difference between the two code snippets below is one of them generates couples that span the two sentences like so: data = ['this is some stuff.', 'I have a cookie.'] results: ...SNIP... [some, have] [stuff, this] [stuff, is] [stuff, some] [stuff, i] [stuff, have] [stuff, a] [i, is] [i, some] [i, stuff] [i, have] [i, a] [i, cookie] [have, some] [have, stuff] ...SNIP... We can see that there are couples that stretch across sentences Or we can have couples that don't span sentences: ...SNIP... [some, stuff] [stuff, this] [stuff, is] [stuff, some] [i, have] [i, a] [i, cookie] [have, i] [have, a] [have, cookie] ...SNIP... What I have done so far. Get data from sklearn.datasets import fetch_20newsgroups newsgroups_train = fetch_20newsgroups(subset='train', remove=('headers', 'footers', 'quotes')) Initialize some variables vocabulary_size = 8 window_size = 3 neg_samples = 0.0 Flatten the sentences into one large sequence sents = newsgroups_train.data tokenizer = Tokenizer(num_words= vocabulary_size, lower=True, filters=filters) tokenizer.fit_on_texts(sents) word_index_inv = {v: k for k, v in tokenizer.word_index.items()} sequences = tokenizer.texts_to_sequences(sents) couples, labels = skipgrams(list(itertools.chain.from_iterable(sequences)), vocabulary_size=vocabulary_size, window_size=window_size, shuffle=False, negative_samples=neg_samples) word_target, word_context = zip(*couples) word_target = np.array(word_target, dtype="int32") word_context = np.array(word_context, dtype="int32") OR: Split dataset into sentences and gener…
type: Question
score: 0
answer count: 1
has answer: http://stackoverflow.com/a/52067799
tagged with: keras
has title: Word2Vec Skipgrams - Should couples span sentences?

http://stackoverflow.com/a/52065129
score: 0
answers question: http://stackoverflow.com/q/52048473
has body: Would creating the text output you want in python work? For example, gather the produced LaTeX up and add \table{} and \caption: #+begin_src python :exports results :session :results latex import pandas as pd df = pd.DataFrame({'a': [1, 2, 3, 4, 5], 'b': [9, 8, 7, 6, 5]}) var_dict = {} for var in df.columns: var_dict[var] = df[var].value_counts().to_latex() res = '\n'.join(['\\begin{table}\n\\caption{Variable: %s} \n\n %s\n\end{table}' % (key, value) for (key, value) in var_dict.items()]) res #+end_src #+results: #+BEGIN_EXPORT latex \begin{table} \caption{Variable: a} \begin{tabular}{lr} \toprule {} &amp; a \\ \midrule 5 &amp; 1 \\ 4 &amp; 1 \\ 3 &amp; 1 \\ 2 &amp; 1 \\ 1 &amp; 1 \\ \bottomrule \end{tabular} \end{table} \begin{table} \caption{Variable: b} \begin{tabular}{lr} \toprule {} &amp; b \\ \midrule 7 &amp; 1 \\ 6 &amp; 1 \\ 5 &amp; 1 \\ 9 &amp; 1 \\ 8 &amp; 1 \\ \bottomrule \end{tabular} \end{table} #+END_EXPORT
type: Answer
has comment: http://stackoverflow.com/comment/91085096

http://stackoverflow.com/a/51974883
has comment: http://stackoverflow.com/comment/90900358
has body: The error in your code is trying to apply count on a file handle, not on a list. Anyway, you don't need to count the elements, you just need to see if the element already has been seen in the file. I'd suggest a marker set to note down which elements already occured. seen = set() result = set() with open ("Duplicate.txt", "r") as datafile: for i in datafile: # you may turn i to a number here with: i = int(i) if i in seen: result.add(i) # data is already in seen: duplicate else: seen.add(i) # next time it occurs, we'll detect it print(list(result)) # convert to list (maybe not needed, set is ok to print)
answers question: http://stackoverflow.com/q/51974727
has comment: http://stackoverflow.com/comment/90900404
type: Answer
upvote count: 1
has comment: http://stackoverflow.com/comment/90900492
score: 1
has comment: http://stackoverflow.com/comment/90900519
downvote count: 0

http://stackoverflow.com/q/52059256
downvote count: 0
favorite count: 0
type: UnansweredQuestion
tagged with: python
answer count: 0
upvote count: 1
type: Question
score: 1
tagged with: bokeh
has body: I have a dynamically updated CheckboxGroup, whose container re-sizes well as long as I don't put the widget into a more complex settings of rows or columns. Once the layout becomes more complex, the widgets overlap when dynamically adding entries to the CheckboxGroup (size stays on the original height). Here's some code for testing: import sys, os from collections import OrderedDict from bokeh.io import curdoc from bokeh.layouts import row, column from bokeh.models.widgets import CheckboxGroup, Div, Button def guiBuildLayout(guiElements): layout = column(guiElements.values()) return layout def update_checkbox(): checkbox.labels += checkbox.labels guiElements = OrderedDict() divHTML = ' TEST. ' guiElements.update({'test': row(Div(text=divHTML, height=30))}) checkbox = CheckboxGroup(labels=['aa','bb','cc','dd','ee','ff']) guiElements.update({'chbx': row(children=[checkbox])}) button = Button(label='Grow!') button.on_click(update_checkbox) guiElements.update({'but': button}) divHTML2 = ' TEST2. ' guiElements.update({'test2': row(Div(text=divHTML2, height=30))}) mainLayout = guiBuildLayout(guiElements) curdoc().add_root(mainLayout) curdoc().title = "Check Checkboxgroup" If the checkbox group is not put into a row in the first place (before adding to the column of widgets), re-sizing works just fine. Do you know of any way to avoid this?
has title: Bokeh CheckboxGroup with changing content - container size

http://stackoverflow.com/comment/90910680
comment on: http://stackoverflow.com/q/51979312
has text: The error is not in the code you have posted, but in the migration.
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/52045585
tagged with: python
has comment: http://stackoverflow.com/comment/91080020
answer count: 0
upvote count: 2
type: UnansweredQuestion
tagged with: machine-learning
has title: How to solve or identify problems in Neural Networks which can be seen on Tensorboard Graphs
tagged with: tensorflow
score: 2
has comment: http://stackoverflow.com/comment/91072428
has body: I my own data set created by me with 5000 data points. Using those data I built up a network to train with one 1 hidden layers. input layer contains 3 input neurons Hidden layer has 100 neurons output layer has 3 neurons I used tangent-sigmoid(tanh) activation function for hidden neurons and liner activation function for output layer. I used tensor board to visualize the result for accuracy and loss. Problem is my graphs (look at the figure) is very fuzzy and meaning less. And i wont get a accuracy more than 40%. And the network doesn't seem like leaning. my assumption is, there is a problem in my data input method. Please help me out. import random import math import csv import numpy as np from matplotlib import pyplot as plt from sklearn import preprocessing import tensorflow as tf from tensorflow import keras from tensorflow.keras.callbacks import TensorBoard linkLength = 2 def Xe (a,b,c): return linkLength*math.cos(a)+linkLength*math.cos(a+b)+linkLength*math.cos(a+b+c) def Ye (e,f,g): return linkLength*math.sin(e) + linkLength*math.sin(e + f) + linkLength*math.sin(e + f + g) def tita (h,i,j): return math.degrees(h)+math.degrees(i)+math.degrees(j) Q1 = [] Q2 = [] Q3 = [] posX = [] posY = [] titaEnd = [] # data set creation for i in range (0,5000): q1= round(random.uniform(0,math.pi),2) q2= round(random.uniform(-math.pi,0),2) q3= round(random.uniform(-math.pi/2, math.pi/2), 2) Q1.append(q1) Q2.append(q2) Q3.append(q3) posX.append(Xe(q1,q2,q3)) posY.append(Ye(q1,q2,q3)) titaEnd.append(tita(q1,q2,q3)) for i in range(0,len(posX)): plt.plot([posX[i],posX[i]+0.2*math.cos(math.radians(titaEnd[i]))],[posY[i],posY[i]+0.2*math.sin(math.radians(titaEnd[i]))],'k-') plt.scatter(posX,posY) plt.xlabel("X Axis") plt.ylabel("Y Axis") plt.title("data set of 1000 possible endeffector positions and orientations") plt.show() dataMat =np.c_[Q1,Q2,Q3,posX,posY,titaEnd] #removing duplicated end effeector positions for i in range (0,4999): check1 = dataMat[i,3] check2 = dataMat[i,4] chec…
has comment: http://stackoverflow.com/comment/91055898
type: Question
tagged with: neural-network
downvote count: 0
has comment: http://stackoverflow.com/comment/91070780
tagged with: keras
favorite count: 0
has comment: http://stackoverflow.com/comment/91080037

http://stackoverflow.com/a/52054209
has comment: http://stackoverflow.com/comment/91058900
score: 0
type: Answer
has comment: http://stackoverflow.com/comment/91059047
has comment: http://stackoverflow.com/comment/91060283
has body: Somehow instead of response you use selector variable which is not defined, but you should get an error when run that code. UPDATE: You have an error in second xpath "//*[@id='mw-content-text']/span/span[1]/span[2]/span[3])" and should remove the last bracket in the expression (after span[3])
accepted answer of: http://stackoverflow.com/q/52053039
has comment: http://stackoverflow.com/comment/91059831
answers question: http://stackoverflow.com/q/52053039
has comment: http://stackoverflow.com/comment/91059376
has comment: http://stackoverflow.com/comment/91060014
type: AcceptedAnswer

http://stackoverflow.com/comment/90951617
has text: @jezrael, It was working for me too.. But suddenly getting this..
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52001241

http://stackoverflow.com/q/52067930
type: UnansweredQuestion
type: Question
tagged with: automator
has title: Receiving variables from Automator as a String
has comment: http://stackoverflow.com/comment/91087634
score: 0
has comment: http://stackoverflow.com/comment/91086718
has body: I have an Automator script that gets the comments from the current song. I need to pass those comments to Python for further processing, however, when I print the results in python, my results are not the actual comments from the song. I have verified that my Automator variable has the correct comments, but it does not make it to python. when I print the variable in python, i get the following: '-c','\n' Am i missing something to properly receive the variable in python? UPDATE:
tagged with: python
answer count: 0
has comment: http://stackoverflow.com/comment/91087133

http://stackoverflow.com/q/52110869
answer count: 3
has comment: http://stackoverflow.com/comment/91177191
favorite count: 0
score: 28
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/91175731
has comment: http://stackoverflow.com/comment/91172217
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/52784541
tagged with: python
has body: I would like not to use the non-tuple sequence for multidimensional indexing so that the script will support future release of Python when this changes. Below is the code that i am using for plotting the graph: data = np.genfromtxt(Example.csv,delimiter=',', dtype=None, names=True, converters={0: str2date}) p1, = host.plot(data["column_1"], data["column_2"], "b-", label="column_2") p2, = par1.plot(data["column_1"], data['column_3'], "r-", label="column_3") p3, = par2.plot(data["column_1"], data["column_4"], "g-", label="column_4") host.set_xlim([data["column_1"][0], data["column_1"][-1]]) host.set_ylim(data["column_2"].min(), data["column_2"].max()) par1.set_ylim(data["column_3"].min(), data["column_3"].max()) par2.set_ylim(data["column_4"].min(), data["column_4"].max())
has comment: http://stackoverflow.com/comment/91177322
downvote count: 0
linked to: http://stackoverflow.com/q/5644836
linked to: http://stackoverflow.com/q/52594235
has answer: http://stackoverflow.com/a/52120113
has comment: http://stackoverflow.com/comment/91193753
upvote count: 28
type: Question
tagged with: numpy
tagged with: arrays
tagged with: matplotlib
has title: FutureWarning: Using a non-tuple sequence for multidimensional indexing is deprecated use `arr[tuple(seq)]` instead of `arr[seq]`
has comment: http://stackoverflow.com/comment/91172410
has answer: http://stackoverflow.com/a/54732522

http://stackoverflow.com/q/52106515
tagged with: python
score: 1
has comment: http://stackoverflow.com/comment/91165116
type: Question
tagged with: pyqt
has title: PyQt5: bring child windows to front, if main window is brought in front
downvote count: 0
has body: I have written this code for the behaviour of my parent window and its children (which belong to self.windowList). I wanted all child windows to minimise if the parent is minimised: def changeEvent(self, event): if event.type() == QEvent.WindowStateChange: if self.windowState() &amp; Qt.WindowMinimized: for i in range(len(self.windowList)): self.windowList[i].showMinimized() else: for i in range(len(self.windowList)): self.windowList[i].showNormal() now I want to achieve the same behaviour for this instance: if all my application windows are brought to foreground and then I click on something else (e.g. Safari, whatever else), so the windows are all behind safari, but then if I click on my parent window, all child windows should also come back to the front. Is there equivalent of the code I wrote above for such behaviour? I do not know and couldn't find what window state would mean that the window has been brought to foreground. I've tried several possibilities, including activateWindow for children when parent is active, but what that does is also restores them from being minimised, which is not the behaviour I want.
favorite count: 0
answer count: 0
type: UnansweredQuestion
tagged with: pyqt5
upvote count: 1

http://stackoverflow.com/comment/90933312
score: 0
comment on: http://stackoverflow.com/q/51970081
type: Comment
has text: I followed the link you specified, I could see all my process opening in background instead of foreground
type: QuestionComment

http://stackoverflow.com/q/52087684
linked to: http://stackoverflow.com/q/52084458
type: Question
has answer: http://stackoverflow.com/a/52089539
tagged with: twitter
answer count: 1
downvote count: 0
score: 1
favorite count: 0
accepted answer: http://stackoverflow.com/a/52089539
tagged with: python
type: AnsweredQuestion
has body: I have been trying to grab tweets off of twitter using selenium. I have been successful at getting the html that I want and printing it, but I am having trouble with getting into a form that is appropriate to use for a dataframe. Here is my code: import time import pandas as pd import numpy as np from selenium import webdriver from selenium.webdriver.common.keys import Keys from selenium.webdriver.common.by import By browser = webdriver.Chrome() url = 'https://twitter.com/search?f=tweets&amp;q=cuomosmta%20since%3A2016-08-22%20until%3A2018-08-22' browser.get(url) time.sleep(1) tweet_dict = {} tweets = browser.find_elements_by_class_name('tweet-text') for tweet in tweets: print(tweet.text) tweet_dict['tweet'] = tweet.text If you run the code, you will see that it prints each individual tweet. I did this to ensure that the code was working. But for some reason, when I check my dictionary, my output from: tweet_dic['tweet'] is: 'Ugh, Cuomo and #CuomosMTA are terrible, just terrible.' The output above is also the last tweet on the page that I am tyring to scrape. I have tried this method multiple ways and even tried BeautifulSoup, but for some reason I keep getting the same result. I don't understand why I am able to print all of the tweets but not append them to dictionary. I am a beginner and am probably missing something very obvious so any help would be appreciated. Please, if possible, I am trying to keep only using selenium since it is easier to use to grab the exact timestamp than it is in beautifulsoup. Thank you!
has title: Grabbing data using selenium and adding it to a dictionary for use in a dataframe
tagged with: selenium
upvote count: 1

http://stackoverflow.com/q/52046301
answer count: 2
has comment: http://stackoverflow.com/comment/91050284
has title: Achieving Numba's performance with Cython
has body: Usually I'm able to match Numba's performance when using Cython. However, in this example I have failed to do so - Numba is about 4 times faster than my Cython's version. Here the Cython-version: %%cython -c=-march=native -c=-O3 cimport numpy as np import numpy as np cimport cython @cython.boundscheck(False) @cython.wraparound(False) def cy_where(double[::1] df): cdef int i cdef int n = len(df) cdef np.ndarray[dtype=double] output = np.empty(n, dtype=np.float64) for i in range(n): if df[i]&gt;0.5: output[i] = 2.0*df[i] else: output[i] = df[i] return output And here is the Numba-version: import numba as nb @nb.njit def nb_where(df): n = len(df) output = np.empty(n, dtype=np.float64) for i in range(n): if df[i]&gt;0.5: output[i] = 2.0*df[i] else: output[i] = df[i] return output When tested, the Cython version is on par with numpy's where, but is clearly inferior to Numba: #Python3.6 + Cython 0.28.3 + gcc-7.2 import numpy np.random.seed(0) n = 10000000 data = np.random.random(n) assert (cy_where(data)==nb_where(data)).all() assert (np.where(data&gt;0.5,2*data, data)==nb_where(data)).all() %timeit cy_where(data) # 179ms %timeit nb_where(data) # 49ms (!!) %timeit np.where(data&gt;0.5,2*data, data) # 278 ms What is the reason for Numba's performance and how can it be matched when using Cython? As suggested by @max9111, eliminating stride by using continuous memory-view, which doesn't improve the performance much: @cython.boundscheck(False) @cython.wraparound(False) def cy_where_cont(double[::1] df): cdef int i cdef int n = len(df) cdef np.ndarray[dtype=double] output = np.empty(n, dtype=np.float64) cdef double[::1] view = output # view as continuous! for i in range(n): if df[i]&gt;0.5: view[i] = 2.0*df[i] else: view[i] = df[i] return output %timeit cy_where_cont(data) # 165 ms
has comment: http://stackoverflow.com/comment/91046106
has answer: http://stackoverflow.com/a/52137710
favorite count: 0
accepted answer: http://stackoverflow.com/a/52137710
has answer: http://stackoverflow.com/a/53029372
upvote count: 5
has comment: http://stackoverflow.com/comment/91071061
tagged with: numba
tagged with: python
type: AnsweredQuestion
tagged with: performance
downvote count: 0
tagged with: cython
type: Question
score: 5
possible better answer: http://stackoverflow.com/a/53029372
tagged with: x86

http://stackoverflow.com/q/51988307
has body: I need to keep information about filtering and searching in Django admin change page. So when user filters by "?away_team__id__exact=267821", I need to append this query to change page url. Let's say we filtered objects by query above. This is the url of change list: http://127.0.0.1:8000/matches/match/?away_team__id__exact=267821 I want to make change field which redirects user to change page of the current object and appends query to the url so instead: http://127.0.0.1:8000/matches/match/2009/change/ The url will be: http://127.0.0.1:8000/matches/match/2009/change/?away_team__id__exact=267821 The problem is that I couldn't access request in the custom field method. I tried to do it using template language but without success, I get: http://127.0.0.1:8000/matches/match/1996/change/?{{%20request.GET.urlencode%20}} This is the method: def change(self,obj): return mark_safe(f"""Zmeniť") Do you know how to do that? EDIT This is because I need to create a NEXT and PREVIOUS buttons in change object page so user can step directly to the next object.
favorite count: 0
tagged with: python-3.x
tagged with: django-request
has answer: http://stackoverflow.com/a/51988958
has answer: http://stackoverflow.com/a/77151984
tagged with: django
tagged with: python
has answer: http://stackoverflow.com/a/72821904
has comment: http://stackoverflow.com/comment/90926455
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90926792
possible better answer: http://stackoverflow.com/a/72821904
has comment: http://stackoverflow.com/comment/90926620
type: Question
accepted answer: http://stackoverflow.com/a/51988958
tagged with: django-admin
score: 4
has title: How to use `request` in the custom fields of `list_display` in Django Admin?
upvote count: 4
answer count: 3
downvote count: 0

http://stackoverflow.com/comment/90908333
score: 1
comment on: http://stackoverflow.com/q/51979302
type: Comment
type: QuestionComment
has text: It may help if you tell why you need this.

http://stackoverflow.com/comment/91081924
comment on: http://stackoverflow.com/a/52065587
type: AnswerComment
type: Comment
score: 0
has text: does it print anything?

http://stackoverflow.com/a/51993211
has body: Edited for the minimal example compatibility You can define a function which calculates a person's age: from datetime import date def calc_age(row): bm = row['bornMonth'] bd = row['bornDay'] by = row['bornYear'] dm = row['diedMonth'] dd = row['diedDay'] dy = row['diedYear'] birth_date = date(*[int(i) for i in (by, bm, bd)]) # suppose that all the parameters is not None try: end_date = date(*[int(i) for i in (dy, dm, dd)]) except (TypeError, ValueError): # if death date is None end_date = date.today() # is birth date after death date or today; if True == 1, else == 0 is_next_year = ((end_date.month, end_date.day) &lt; (birth_date.month, birth_date.day)) age = end_date.year - birth_date.year - is_next_year return age Apply this function to your data frame along the rows: df.apply(calc_age, axis=1) and it returns pd.Series with age for all the persons in years if there's no missed data. You can concatenate it to your dataframe: df['personsAge'] = df.apply(calc_age, axis=1) Then add another column with a status and print results: def is_dead(row): dm = row['diedMonth'] dd = row['diedDay'] dy = row['diedYear'] try: died = date(*[int(i) for i in (dy, dm, dd)]) return True except ValueError: return False df['is_dead'] = df.apply(is_dead, axis=1) def print_status(row): bm = row['bornMonth'] bd = row['bornDay'] by = row['bornYear'] dm = row['diedMonth'] dd = row['diedDay'] dy = row['diedYear'] age = row['personsAge'] print("DOB: "+str(bm)+"/"+str(bd)+"/"+str(by)+" ("+str(age)+" years old)") if row['is_dead']: print("*DECEASED: "+str(dm)+"/"+str(dd)+"/"+str(dy)) df.apply(print_status, axis=1) stdout: DOB: 8/17/1932 (47 years old) *DECEASED: 3/22/1980 DOB: 4/12/1950 (68 years old) If you don't like copy-paste dates selection, replace it by datetime approach from Andrey Portnoy's solution.
answers question: http://stackoverflow.com/q/51992641
score: 0
type: Answer

http://stackoverflow.com/a/52104959
type: Answer
accepted answer of: http://stackoverflow.com/q/52102805
upvote count: 1
answers question: http://stackoverflow.com/q/52102805
type: AcceptedAnswer
downvote count: 0
score: 1
has body: You may directly use the pandas wrapper to plot grouped bar plots. Set the ax to the respective subplot you want the plot to appear in. fig, axes = plt.subplots(3,2,figsize=(13,10)) for ax, df in zip(axes.flat, [districts_2018, districts_2017, ....]) df'DEM', 'REP'.plot.bar(ax=ax)

http://stackoverflow.com/q/52043238
has title: Fourier filtering, going back to an image
downvote count: 0
type: Question
score: 5
tagged with: filtering
accepted answer: http://stackoverflow.com/a/52043767
answer count: 1
has answer: http://stackoverflow.com/a/52043767
favorite count: 0
tagged with: fft
upvote count: 5
has body: I have a repeating fringe pattern on my data and I am trying to get it out by Fourier transforming it and deleting the pattern. However I can't seem to find the correct way back to image space. red_cube_array = (cube_array - np.median(cube_array)) * taper im_fft = (fftpack.fft2(red_cube_array)) im_po = fftpack.fftshift((np.conjugate(im_fft) * im_fft).real) mask = np.empty_like(im_po[0])*0 + 1 mask[417:430, 410:421] = 0 mask[430:443, 438:450] = 0 im_po_mask = im_po * mask im_ifft = fftpack.ifft2(fftpack.ifftshift(im_po_mask)) taper is just an array that smooths the edges to get rid of the edge effects while doing an FFT. Then I FFT the array and filter out the gunk very roughly. However going back does not seem to work. Am I tripping up somewhere?
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/q/52002271
answer count: 2
duplicate of: http://stackoverflow.com/q/21287624
tagged with: pandas
downvote count: 0
favorite count: 0
has body: I used the following code to read csv, by specifying the types for each col: clean_pdf_type=pd.read_csv('table_updated.csv',usecols=col_names,dtype =col_types) But it has the error: ValueError: Integer column has NA values in column 298 Not sure how to skip the NA?
has comment: http://stackoverflow.com/comment/90953695
tagged with: http://stackoverflow.com/tag/csv
has answer: http://stackoverflow.com/a/52002507
tagged with: python
score: 11
linked to: http://stackoverflow.com/q/11548005
upvote count: 11
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90953742
type: Question
has comment: http://stackoverflow.com/comment/90954058
possible better answer: http://stackoverflow.com/a/52002491
accepted answer: http://stackoverflow.com/a/52002507
has answer: http://stackoverflow.com/a/52002491
linked to: http://stackoverflow.com/q/21287624
tagged with: dataframe
has title: read_csv using dtypes but there is na value in columns

http://stackoverflow.com/comment/90946859
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51998834
has text: HOw do you want to convert `5.6`. Should it be `5` or rounded to `6`?
score: 0

http://stackoverflow.com/comment/90893997
type: Comment
type: QuestionComment
has text: Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/178555/discussion-between-user3-1415927-and-charles-duffy).
score: 0
comment on: http://stackoverflow.com/q/51971477

http://stackoverflow.com/comment/105141312
has text: This was fixed YEARS ago https://github.com/secdev/scapy/blob/master/scapy/layers/rtp.py
score: 0
type: Comment
comment on: http://stackoverflow.com/a/59478307
type: AnswerComment

http://stackoverflow.com/comment/132240881
type: Comment
comment on: http://stackoverflow.com/a/52098307
type: AnswerComment
score: 0
has text: They're asking for something similar to what's possible in rsync where you can chain excludes and includes. This is useful for scenarios like needing all the files of specific subdirectories while omitting extensions like '*.bak'. It's still possible to copy the same files with only ignore or include, but it'll take several more "flat" calls rather than using fewer calls with more complex recursion.

http://stackoverflow.com/q/52047567
linked to: http://stackoverflow.com/q/11977270
has comment: http://stackoverflow.com/comment/91046272
has title: How to reload a module (from within the class) if it's an old version
score: 0
has comment: http://stackoverflow.com/comment/91046257
has comment: http://stackoverflow.com/comment/91046169
has body: I am trying to reload a class (from within the class) if the version of the class is out of date with what the version should be. Would the following make sense and work? If not, could you please suggest the correct way to accomplish the above? class MoviesEC2Prices(GenericScript): def __init__(self): super(MoviesEC2Prices, self).__init__() self.exporter = BaseExporter() self.ingester = self.exporter.ingester self.VERSION = 2 self.ingester.cursor.execute("SELECT version_id FROM movies_version") if self.ingester.cursor.fetchone()[0] != self.VERSION: subprocess.call(shlex.split('git pull origin master')) reload(ingest) reload(ingest.movies_ec2) import ingest from ingest.movies_ec2 import MoviesEC2Prices self = MoviesEC2Prices() What would be the best way to accomplish the above -- that is, if there is a version mis-match, download the code from git and "re-run" the script.
has comment: http://stackoverflow.com/comment/91046085
answer count: 0
has comment: http://stackoverflow.com/comment/91046324
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/91046373
has comment: http://stackoverflow.com/comment/91046119
has comment: http://stackoverflow.com/comment/91046525
has comment: http://stackoverflow.com/comment/91046457
type: Question
has comment: http://stackoverflow.com/comment/91046160
has comment: http://stackoverflow.com/comment/91046353

http://stackoverflow.com/q/52093315
has title: Check string presence in multiple cols and give output to separate cols in pandas
has comment: http://stackoverflow.com/comment/91136816
tagged with: multiple-columns
favorite count: 0
accepted answer: http://stackoverflow.com/a/52093468
has comment: http://stackoverflow.com/comment/91136557
tagged with: python
has comment: http://stackoverflow.com/comment/91136695
type: AnsweredQuestion
score: 4
has comment: http://stackoverflow.com/comment/91136651
type: Question
tagged with: split
has answer: http://stackoverflow.com/a/52093468
possible better answer: http://stackoverflow.com/a/52093593
has body: I have dataframe as like follows: col1 col2 col3 col4 0 a-I - - 12.4 1 - a-I - 2.6 2 a-I - a-I 23 3 - a-I a-I 4 4 - - a-I 5 5 a-I a-I - 6.245 6 - a a 7.23 7 a a - 8 What I want is to check for I in each column if it is present than make res column with splitting string with -. Can anybody have any idea how to do this? Expected Result would be like this: col1 col2 col3 col4 res 0 a-I - - 12.4 I 1 - a-I - 2.6 I 2 a-I - a-I 23 I 3 - a-I a-I 4 I 4 - - a-I 5 I 5 a-I a-I - 6.245 I 6 - a a 7.23 - 7 a a - 8 -
has answer: http://stackoverflow.com/a/52093593
upvote count: 4
answer count: 2
tagged with: pandas
downvote count: 0

http://stackoverflow.com/comment/91076424
type: Comment
has text: Good morning @gregory... I just realized that all of my code looks pretty sloppy... I apologize for that. I am just learning and will do my best to improve. Do you recommend that I edit the code to look more clean? I am not sure if I am supposed to leave it as is or show the updated version. Thanks again sir! Enjoy your day!
type: AnswerComment
comment on: http://stackoverflow.com/a/52049491
score: 0

http://stackoverflow.com/q/52086900
tagged with: class
has title: Changing attributes from a method call
linked to: http://stackoverflow.com/q/50090868
type: Question
has body: I'm trying to make a chopsticks game. Here's a wikipedia link to the game https://en.wikipedia.org/wiki/Chopsticks_(hand_game). So far I just added a couple methods so that one hand can attack another hand using the 'attack' method. I feel like the code I wrote is very verbose, ugly and maybe even wrong though. How can I write this more elegantly? class game: def __init__(self): self.x_left = 1 self.x_right = 1 self.o_left = 1 self.o_right = 1 def set_x_left(self, num): self.x_left = num def set_x_right(self, num): self.x_right = num def set_o_left(self, num): self.o_left = num def set_o_right(self, num): self.o_right = num def dict_func(self, hand): self.func= {'x_left': self.set_x_left, 'x_right': self.set_x_right, 'o_left': self.set_o_left, 'o_right': self.set_o_right} return self.func[hand] def dict_hand(self, hand): self.hands = {'x_left': self.x_left, 'x_right': self.x_right, 'o_left': self.o_left, 'o_right': self.o_right} return self.hands[hand] def attack(self, from_hand, to_hand): self.dict_func(to_hand)(self.dict_hand(from_hand) + self.dict_hand(to_hand))
tagged with: python
answer count: 1
score: 0
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/52086934

http://stackoverflow.com/comment/90916090
comment on: http://stackoverflow.com/a/51966101
type: Comment
has text: Wow, It is of great use for me! I gained a lots from it.
score: 0
type: AnswerComment

http://stackoverflow.com/a/52064774
upvote count: 2
type: Answer
score: 2
has body: The thing you are looking for is called _missing_ and is available in the stdlib as of Python3.6, and in aenum1 as of 2.0. class MyEnum(Enum): BOB = "bob" RALPH = "ralph" ETC = "etc" @classmethod def _missing_(cls, value): for member in cls: if member.value == value.lower(): return member If _missing_ fails to return a MyEnum member then EnumMeta will raise an exception (so _missing_ doesn't have to worry about that part)2. 1 Disclosure: I am the author of the Python stdlib Enum, the enum34 backport, and the Advanced Enumeration (aenum) library. 2 Thanks, Aran-Fey, for bringing that up.
has comment: http://stackoverflow.com/comment/91080227
answers question: http://stackoverflow.com/q/52063986
has comment: http://stackoverflow.com/comment/91080763
downvote count: 0
has comment: http://stackoverflow.com/comment/91080318
has comment: http://stackoverflow.com/comment/91080482
has comment: http://stackoverflow.com/comment/91080353

http://stackoverflow.com/q/52038466
has body: Reverse geocoding with Nominatim seems to return either "town" or "city" depending on the size of the location. import geojson from geopy.geocoders import Nominatim location = "48.84837905, 2.28229522311902" geolocator = Nominatim(user_agent="my-application",timeout=3) location = geolocator.reverse(location) print(location.raw) #Sometimes "town", sometimes "city" ##print(location.raw['address']['town']) ##print(location.raw['address']['city']) What is a good way to handle both cases? Thank you.
answer count: 1
has title: How to support "town" and "city" when querying Nominatim?
favorite count: 0
has answer: http://stackoverflow.com/a/52038535
accepted answer: http://stackoverflow.com/a/52038535
upvote count: 2
tagged with: python
tagged with: dictionary
downvote count: 1
type: AnsweredQuestion
score: 1
tagged with: geojson
type: Question

http://stackoverflow.com/q/52046697
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/91044663
has comment: http://stackoverflow.com/comment/91064029
has comment: http://stackoverflow.com/comment/91054595
has comment: http://stackoverflow.com/comment/91076356
score: 0
has title: Creating a csv file in the new thread using Python
has comment: http://stackoverflow.com/comment/91045232
has comment: http://stackoverflow.com/comment/91045335
has body: I would like to create a csv file using a new thread. Below is the code that I wrote: import GPS_lib as GPS import time from threading import Thread import csv def GPSThread(): try: GPS.gps=GPS.InitConnection() last_print_gps=time.time() with open(GPS.PATH,"w") as csvfile: fieldnames=['Time','Latitude','Longitude','Speed','CoG'] writer=csv.DictWriter(csvfile,fieldnames=fieldnames) writer.writeheader() while True: GPS.gps.update() current_gps=time.time() print(GPS.LATITUDE) if current_gps-last_print_gps&gt;=1: last_print_gps=current_gps GPS.GetGPSValues() writer.writerow({ 'Time':GPS.TIME, 'Latitude':GPS.LATITUDE, 'Longitude': GPS.LONGITUDE, 'Speed': GPS.SPEED, 'CoG': GPS.CoG}) except: print("Error") GPS_thread=Thread(target=GPSThread,args=()) GPS_thread.start() GPS_thread.join() If I use this code without new thread, everything works. With new thread I have only empty file. Why? Can someone help me?
has comment: http://stackoverflow.com/comment/91044805
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion
tagged with: python
answer count: 0
tagged with: multithreading
has comment: http://stackoverflow.com/comment/91232960
upvote count: 1

http://stackoverflow.com/comment/91159732
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52104310
score: 1
has text: Your dictionary names don't make a lot of sense. A dictionary is a set of key: value pairs. So you've named one key "key" and the other key "value".

http://stackoverflow.com/comment/91164293
comment on: http://stackoverflow.com/q/52106557
has text: @user10287754 You have to put `self` first, and any additional parameters after that.
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/a/52084638
score: 1
has comment: http://stackoverflow.com/comment/91122126
has comment: http://stackoverflow.com/comment/91122119
type: Answer
upvote count: 1
has comment: http://stackoverflow.com/comment/91128939
answers question: http://stackoverflow.com/q/52084458
downvote count: 0
has body: To make it work you have to create an instance of webdriver, e.g.: from selenium import webdriver driver = webdriver.Chrome() # webdriver.Ie(), webdriver.Firefox()... last_height = driver.execute_script("return document.body.scrollHeight") You can download Chromedriver from here You also need to add path to Chromedriver to your environment variable PATH or just put downloaded file into the same folder as your Python executable...

http://stackoverflow.com/comment/90926416
type: QuestionComment
comment on: http://stackoverflow.com/q/51988218
has text: @SachinKukreja: using a many-to-may relation *can* be an option, it can however require *extra* logic to enforce that every child has a mother and father (and not zero parents, one parent, two fathers, two mothers, three mothers and two fathers, etc.).
score: 0
type: Comment

http://stackoverflow.com/a/52102067
has body: Using the **encrypt** method imported from **django_cryptography.fields**, define a password attribute for the model LdapProfile (model related to User to store the user profile on ldap) and then, use this password attribute in ldap.authenticate(username, password). password = encrypt(models.CharField( max_length=255, null=True, blank=True ))
accepted answer of: http://stackoverflow.com/q/52100914
answers question: http://stackoverflow.com/q/52100914
type: AcceptedAnswer
score: 0
type: Answer

http://stackoverflow.com/comment/91075961
comment on: http://stackoverflow.com/a/52062651
has text: I should make question more clear. That one is just one example. I need more general thing like get i,j,k element from three columns respectively
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/90885624
has text: also those numbers are floats not necessarily integers
comment on: http://stackoverflow.com/a/51967402
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/a/52046137
has comment: http://stackoverflow.com/comment/91051851
answers question: http://stackoverflow.com/q/52045842
has comment: http://stackoverflow.com/comment/91048009
has comment: http://stackoverflow.com/comment/91048193
upvote count: 1
type: AcceptedAnswer
has body: You can make vector a subclass of list and overload the __lt__ and __gt__ methods so that the last item is checked before the default behavior. Also overload the __le__ and __ge__ methods for completeness: class vector(list): def __lt__(self, other): lt = super().__lt__(other) if lt and self[-1] &gt; other[-1]: return False return lt def __gt__(self, other): gt = super().__gt__(other) if gt and self[-1] &lt; other[-1]: return False return gt def __le__(self, other): if self == other: return True return self &lt; other def __ge__(self, other): if self == other: return True return self &gt; other so that: a=vector([1,2,[1]]) b=vector([1,2,[2]]) c=vector([1,3,[1]]) print(a&lt;b) print(a&lt;c) print(b&lt;c) print(c&lt;b) print(b&gt;c) print(c&gt;b) print(b&lt;=c) print(c&lt;=b) will output: True True False False False False False False EDIT: In light of the comments made below, I would also like to point out that this is case where functools.total_ordering doesn't work because of the atypical logic required by the OP, where one object can be not less than, not greater than and not equal to the other at the same time. So if we define only the __lt__ method for the vector class and apply the total_ordering decorator: from functools import total_ordering @total_ordering class vector(list): def __lt__(self, other): lt = super().__lt__(other) if lt and self[-1] &gt; other[-1]: return False return lt The test code above would produce the following incorrect output instead: True True False False False True True False
type: Answer
has comment: http://stackoverflow.com/comment/91044651
has comment: http://stackoverflow.com/comment/91079245
has comment: http://stackoverflow.com/comment/91090519
has comment: http://stackoverflow.com/comment/91090453
downvote count: 0
score: 1
accepted answer of: http://stackoverflow.com/q/52045842
has comment: http://stackoverflow.com/comment/91047516

http://stackoverflow.com/comment/90935326
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51992679
type: AnswerComment
has text: Thank you for clearing that up. Function2 actually needs to accept each item of the list and run each item through another loop. That is why I put the loop in function2 to test this. Function1 creates a list through webcrawling. Function2 loops through each item of that list and does stuff to it. The code above is me trying to use multiprocessing on function2

http://stackoverflow.com/q/52094432
tagged with: python
accepted answer: http://stackoverflow.com/a/52098000
tagged with: multiprocessing
tagged with: parallel-processing
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/75954208
has answer: http://stackoverflow.com/a/52098000
tagged with: queue
type: Question
upvote count: 4
tagged with: python-multiprocessing
answer count: 2
has title: Best way to wait for queue population python multiprocessing
has body: It is first time I play with parallel computing seriously. I am using multiprocessing module in python and I am running into this problem: A queue consumer run in a different process then queue producer, the former should wait the latter to finish its job, before stop iterating over the queue. Sometimes the consumer is faster then producer and the queue stays empty. If I don't put any condition the program won't stop. In the sample code I use the wildcard PRODUCER_IS_OVER to example what I need. following code sketch the problem: def save_data(save_que, file_): ### Coroutine instantiation PRODUCER_IS_OVER = False empty = False ### Queue consumer while not(empty and PRODUCER_IS_OVER): try: data = save_que.get() print("saving data",data) except: empty = save_que.empty() print(empty) pass #PRODUCER_IS_OVER = get_condition() print ("All data saved") return def get_condition(): ###NameError: global name 'PRODUCER_IS_OVER' is not defined if PRODUCER_IS_OVER: return True else: return False def produce_data(save_que): for _ in range(5): time.sleep(random.randint(1,5)) data = random.randint(1,10) print("sending data", data) save_que.put(data) ### Main function here import random import time from multiprocessing import Queue, Manager, Process manager = Manager() save_que = manager.Queue() file_ = "file" save_p = Process(target= save_data, args=(save_que, file_)) save_p.start() PRODUCER_IS_OVER = False produce_data(save_que) PRODUCER_IS_OVER = True save_p.join() produce_data takes variable time and I want the save_p process to start BEFORE populate the queue, in order to consume the queue while is filled. I think there are workaround to communicate when to stop iteration, but I want to know whether exist a proper way to do it. I tried both multiprocessing.Pipe and .Lock, but I don't know how implement correctly and efficiently. SOLVED: is it the best way? following code implement STOPMESSAGE in the Q, works fine, I can refine it with a class, QMsg, in case the language support…
downvote count: 0
score: 4
favorite count: 0
possible better answer: http://stackoverflow.com/a/75954208

http://stackoverflow.com/q/52084899
type: Question
has answer: http://stackoverflow.com/a/52085000
score: 0
answer count: 2
has comment: http://stackoverflow.com/comment/91120080
has body: I try to make a dict in python to assign each letter (from A to Z) with an other (or himself) randomly. For exemple A:S B:C C:B D:D ... S:A ... Y:Z Z:Y. My code is: import random tblconex = {} alphabet = {1: "A", 2: "B", 3: "C", 4: "D", 5: "E", 6: "F", 7: "G", 8: "H", 9: "I", 10: "J", 11: "K", 12: "L", 13: "M", 14: "N", 15: "O", 16: "P", 17: "Q", 18: "R", 19: "S", 20: "T", 21: "U", 22: "V", 23: "W", 24: "X", 25: "Y", 26: "Z"} while n &lt; 27: var = alphabet[random.randint(1, 26)] #We randomly choose a letter if var in tblconex or alphabet[n] in tblconex: #We test if she is not already assign to an other n += 1 else: tblconex.update({alphabet[n]: var}) #We assign it tblconex.update({var: alphabet[n]}) n += 1 z=1 while z&lt;len(tblconex)+1: #We print our letters print(" ", alphabet[z], " : ", tblconex[alphabet[z]]) z += 1 But when I launch it he stop after few letter with a Key error because he don't assign all letters and I don't understand why. Sorry for my bad english i'm French ;) Thanks!
favorite count: 0
has title: How to check if a value is already assigned to a key and vice versa in a dict in Python
tagged with: python
tagged with: dictionary
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/52085000
has comment: http://stackoverflow.com/comment/91120044
upvote count: 1
has answer: http://stackoverflow.com/a/52085069
accepted answer: http://stackoverflow.com/a/52085069
has comment: http://stackoverflow.com/comment/91120219
downvote count: 1
has comment: http://stackoverflow.com/comment/91120152

http://stackoverflow.com/q/51974524
has comment: http://stackoverflow.com/comment/90900141
downvote count: 0
has answer: http://stackoverflow.com/a/51975716
score: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/90899719
has comment: http://stackoverflow.com/comment/90899799
has title: Product operator of n matrices without a loop
possible better answer: http://stackoverflow.com/a/51974896
has answer: http://stackoverflow.com/a/51974896
tagged with: python
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/48801371
linked to: http://stackoverflow.com/q/45852228
accepted answer: http://stackoverflow.com/a/51975716
has comment: http://stackoverflow.com/comment/90899843
upvote count: 1
has body: I got a matrix of dimention (nx2x2) so suposing the matrix M of (3x2x2): [[[ 1. 5.] [ 2. 4.]] [[ 5. 25.] [10. 20.]] [[ 5. 25.] [10. 20.]]] I would like to do a product operator (dot product) of each 2x2 matrix. In other words I want to do the folowing: where Mj is the same as M[j,:,:] in python. The easiest way to do this is with a for loop like this: prod=np.identity(2) for temp in M: prod=np.dot(prod,temp) but I don't know if there is a vectorized way of doing this (I am sure that this is probably a repeated question but I can't figure out the right question to google)
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/90900039
answer count: 2
linked to: http://stackoverflow.com/q/42808259

http://stackoverflow.com/comment/91166411
type: Comment
comment on: http://stackoverflow.com/a/52107724
has text: The docs say: `Return a random integer N such that a <= N <= b` which is `[a,b]` and not `(a,b]` or `(a,b)`
score: 1
type: AnswerComment

http://stackoverflow.com/comment/91128132
comment on: http://stackoverflow.com/q/52088986
has text: Use pandas as you are using csv files
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51981068
linked to: http://stackoverflow.com/q/12282232
answer count: 2
downvote count: 2
has comment: http://stackoverflow.com/comment/90911875
has comment: http://stackoverflow.com/comment/90911934
has title: How to make a counting function that returns the number of elements in a list
has comment: http://stackoverflow.com/comment/90912173
has comment: http://stackoverflow.com/comment/90911953
favorite count: 0
upvote count: 3
has comment: http://stackoverflow.com/comment/90911999
tagged with: python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90911896
type: Question
has answer: http://stackoverflow.com/a/51981282
has comment: http://stackoverflow.com/comment/90912729
score: 1
has answer: http://stackoverflow.com/a/51981270
has body: I am trying to make a function that counts elements in a list and I am using Python for that. The program should accept a list like [a, a, a, b, b, c, c, c, c] and returns a value [3, 2, 4] but I am having trouble. What should I do?
linked to: http://stackoverflow.com/q/2600191

http://stackoverflow.com/q/52085930
has body: I am using datetime in Arcpy to convert a "Sample Date" field in a feature class to the day of the year. The date in the field is in a month/day/year format and it doesn't include any leading zeros (ex. 7/8/2018 instead of 07/08/2018). Whenever I try running the following line of code, dtm = datetime.datetime.strptime(row, '%Y/%m/%d %H:%M') I get the following error: ValueError: time data '[datetime.datetime(2003, 6, 3, 0, 0)]' does not match format '%Y/%m/%d %H:%M' The sample date field that I am using does not include any time data which I believe is where the two zeros at the end of the error message are coming from. I just assumed that they were hours and minutes but I am not sure. Does anyone know what the zeros are so that I can change my code to fit the correct format or how I can avoid the zeros altogether? I tried datetime.date instead of datetime.datetime as well and still had complications. I can post the long version of the code if needed but the code that I provided is the cause of the error message. I have included the link of the datetime reference I used. The website is for strftime not strptime but I believe that it works the same. Trying strftime throws an error as well. Link: http://strftime.org/
tagged with: arcmap
has title: Getting datetime data into the correct format arcpy python arcmap
has answer: http://stackoverflow.com/a/52100502
tagged with: strptime
answer count: 1
favorite count: 0
type: UnansweredQuestion
downvote count: 2
tagged with: datetime
tagged with: python
has comment: http://stackoverflow.com/comment/91122392
upvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/91122213
tagged with: arcpy
score: -1

http://stackoverflow.com/q/52083840
answer count: 1
tagged with: pyalgotrade
tagged with: algorithmic-trading
score: 0
tagged with: python
has answer: http://stackoverflow.com/a/52130991
tagged with: python-3.x
type: UnansweredQuestion
tagged with: back-testing
has body: i need average fill price for shares when using pyalgotrade on each bar... i am unable to figure out a way to get the same using callout for getAvgFillPrice function. this would help me to decide to enter next trade or not. any help will be appreciated. i have tried the following code: from pyalgotrade.broker import backtesting from pyalgotrade import broker from pyalgotrade import plotter from pyalgotrade.broker import Order class Str1(strategy.BacktestingStrategy): def __init__(self, feed, instrument, qty): strategy.BacktestingStrategy.__init__(self,feed,1000000) self.__qty = qty self.__instrument = instrument self.__priceDS = feed[instrument].getPriceDataSeries() self.__lowDS = feed[instrument].getLowDataSeries() self.__highDS = feed[instrument].getLowDataSeries() def onBars(self, bars): shares = self.getBroker().getShares(self.__instrument) avg_price = Order.getAvgFillPrice(self.__instrument) price = bars[self.__instrument].getPrice() bar = bars[self.__instrument] print(avg_price) But i get the following error: Traceback (most recent call last): File "C:\Program Files\JetBrains\PyCharm Community Edition 2018.1.3\helpers\pydev\pydevd.py", line 1664, in &lt;module&gt; main() File "C:\Program Files\JetBrains\PyCharm Community Edition 2018.1.3\helpers\pydev\pydevd.py", line 1658, in main globals = debugger.run(setup['file'], None, None, is_module) File "C:\Program Files\JetBrains\PyCharm Community Edition 2018.1.3\helpers\pydev\pydevd.py", line 1068, in run pydev_imports.execfile(file, globals, locals) # execute the script File "C:\Program Files\JetBrains\PyCharm Community Edition 2018.1.3\helpers\pydev\_pydev_imps\_pydev_execfile.py", line 18, in execfile exec(compile(contents+"\n", file, 'exec'), glob, loc) File "E:/pyalgotrader/new.py", line 109, in &lt;module&gt; myStrategy.run() File "E:\pyalgotrader\venv\lib\site-packages\pyalgotrade\strategy\__init__.py", line 512, in run self.__dispatcher.run() File "E:\pyalgotrader\venv\lib\site-packages\pyalgotrade\dispatc…
has title: Pyalgotrade - how to get average fill price for all open position
type: Question

http://stackoverflow.com/comment/90965346
comment on: http://stackoverflow.com/q/52007482
score: 0
type: Comment
type: QuestionComment
has text: Duplicate of [https://stackoverflow.com/questions/11232230](https://stackoverflow.com/questions/11232230/logging-to-two-files-with-different-settings)

http://stackoverflow.com/q/52073609
has comment: http://stackoverflow.com/comment/91097460
has comment: http://stackoverflow.com/comment/91097102
tagged with: datetime
has comment: http://stackoverflow.com/comment/91097349
tagged with: python
has answer: http://stackoverflow.com/a/52073945
has comment: http://stackoverflow.com/comment/91097391
has comment: http://stackoverflow.com/comment/91097157
favorite count: 0
has comment: http://stackoverflow.com/comment/91097241
has comment: http://stackoverflow.com/comment/91097262
accepted answer: http://stackoverflow.com/a/52073945
upvote count: 3
type: AnsweredQuestion
has body: I have two lists of datetime ranges. eg. l1 = [(datetime.datetime(2018, 8, 29, 1, 0, 0), datetime.datetime(2018, 8, 29, 3, 0, 0)), (datetime.datetime(2018, 8, 29, 6, 0, 0), datetime.datetime(2018, 8, 29, 9, 0, 0))] l2 = [(datetime.datetime(2018, 8, 29, 2, 0, 0), datetime.datetime(2018, 8, 29, 4, 0, 0)), (datetime.datetime(2018, 8, 29, 5, 0, 0), datetime.datetime(2018, 8, 29, 7, 0, 0))] And I want to get the union of l1 and l2. The desired outputs are: union = [(datetime.datetime(2018, 8, 29, 1, 0, 0), datetime.datetime(2018, 8, 29, 4, 0, 0)), (datetime.datetime(2018, 8, 29, 5, 0, 0), datetime.datetime(2018, 8, 29, 9, 0, 0))] intersection = [(datetime.datetime(2018, 8, 29, 2, 0, 0), datetime.datetime(2018, 8, 29, 3, 0, 0)), (datetime.datetime(2018, 8, 29, 6, 0, 0), datetime.datetime(2018, 8, 29, 7, 0, 0))] Real data may not be this perfectly aligned.
has answer: http://stackoverflow.com/a/52074881
type: Question
tagged with: union
answer count: 2
possible better answer: http://stackoverflow.com/a/52074881
downvote count: 0
tagged with: intersection
has comment: http://stackoverflow.com/comment/91097193
has comment: http://stackoverflow.com/comment/91097369
has comment: http://stackoverflow.com/comment/91097570
has title: Get unions and intersections of list of datetime ranges python
has comment: http://stackoverflow.com/comment/91097720
score: 3

http://stackoverflow.com/q/52012800
has comment: http://stackoverflow.com/comment/90976524
has answer: http://stackoverflow.com/a/52049281
accepted answer: http://stackoverflow.com/a/52049281
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/90976562
favorite count: 0
tagged with: lapack
tagged with: python-3.x
tagged with: python
tagged with: debian
linked to: http://stackoverflow.com/q/11443302
score: 2
type: AnsweredQuestion
upvote count: 2
has comment: http://stackoverflow.com/comment/90976553
has comment: http://stackoverflow.com/comment/90976535
has title: Can't get Python3 numpy to see BLAS/LAPACK
type: Question
tagged with: blas
has body: I'm running Linaro Debian Stretch on a Tinkerboard and I can't seem to be able to get numpy on Python3 to see any installed BLAS/LAPACK resources. Running np.__config__.show() under python3 gives NOT AVAILABLE for every single entry. I've installed the BLAS/LAPACK via sudo apt-get install libblas-dev liblapack-dev, and python3-numpy and python3-scipy via apt-get as well. Numpy and scipy both run perfectly fine. I've also installed ATLAS and OpenBLAS without luck, and have tried manual compilation of OpenBLAS and numpy too. Nothing changes the output of np.__config__.show(). Python2, however, shows that these resources are installed. How can I get Python3 to see these resources too?

http://stackoverflow.com/comment/91264271
has text: [SOLVED] Thanks. Seems like a missing package problem. Changed the virtual environment and installed required backends and packages using conda. Works fine.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52105383

http://stackoverflow.com/comment/91097965
score: 0
type: Comment
type: QuestionComment
has text: We are in the correct directory however we may not have configured the app correctly. The code you refer to needs to be added to `__init__.py` correct?
comment on: http://stackoverflow.com/q/52073561

http://stackoverflow.com/comment/91140307
score: 0
type: QuestionComment
has text: Possible duplicate of [converting utf-16 -> utf-8 AND remove BOM](https://stackoverflow.com/questions/8827419/converting-utf-16-utf-8-and-remove-bom)
type: Comment
comment on: http://stackoverflow.com/q/52095133

http://stackoverflow.com/a/52032348
type: Answer
score: 2
answers question: http://stackoverflow.com/q/52032262
downvote count: 0
has body: You can use sets to compare if the nodes appear in a, &lt;= operator for sets is equivalent to issubset(). itertools module provides some useful functions, itertools.product() is equivalent to nested for loops. E.g.: In []: import itertools as it [m for m, n in it.product(z, a) if set(m) &lt;= set(n)] Out[]: [[1, 2]]
has comment: http://stackoverflow.com/comment/91015007
upvote count: 2

http://stackoverflow.com/comment/90936551
type: Comment
comment on: http://stackoverflow.com/a/51992639
score: 0
type: AnswerComment
has text: @Cristo It really depends on what you’re doing. Personally, I’ve rarely had a use for something as specific as an “int holder” that wasn’t even more specific, like a “user object” (that happens to have no fields but an int user id), but that doesn’t mean you don’t have a good use for it. As long as you’re thinking of terms of “how do I model this data in Python” rather than “how do I translate this C++ model to a Python model”, your intuitions are probably going to be fine.

http://stackoverflow.com/comment/90983542
type: AnswerComment
has text: I can circumvent certification check, but how do I include the username & password
type: Comment
comment on: http://stackoverflow.com/a/52016750
score: 0

http://stackoverflow.com/comment/91151067
score: 0
type: Comment
type: QuestionComment
has text: @EugenePrikazchikov I do use virtualenv quite extensively, but there are some packages that I'd like always installed
comment on: http://stackoverflow.com/q/52099487

http://stackoverflow.com/a/52048286
upvote count: 8
type: Answer
score: 8
has comment: http://stackoverflow.com/comment/137523733
has comment: http://stackoverflow.com/comment/91118544
accepted answer of: http://stackoverflow.com/q/52045659
answers question: http://stackoverflow.com/q/52045659
has body: You can get the exemplar characters for each locale using the pyicu module: import locale from icu import LocaleData default, encoding = locale.getdefaultlocale() languages = [default] + ['en_US', 'fr_FR', 'es_ES'] for language in languages: data = LocaleData(language) alphabet = data.getExemplarSet() print(language, alphabet) Output pt_BR [a-zà-ãçéêíò-õú] en_US [a-z] fr_FR [a-zàâæ-ëîïôùûüÿœ] es_ES [a-záéíñóúü] To get the current locale is enough to do: default, _ = locale.getdefaultlocale() data = LocaleData(default) alphabet = data.getExemplarSet() print(default, alphabet)
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/a/61662836
type: Answer
has body: Best way to send an email using CRON is to use Postfix and mailutils. Follow below steps to send email with cron job results/errors. Step 1 — Installing Postfix First, update the package database: sudo apt update Next, install mailtuils: sudo apt install mailutils Finally, install postfix: sudo apt install postfix Near the end of the installation process, you will be presented with a window that looks like the one in the image below. The default option is Internet Site. That’s the recommended option for this tutorial, so press TAB, then ENTER Select No Configuration Step 2 — Configuring Postfix sudo nano /etc/postfix/main.cf Then paste below code on the empty file. mailbox_size_limit = 0 recipient_delimiter = + inet_interfaces = loopback-only mydestination = $myhostname, localhost.$your_domain, $your_domain Save and close the file. Finally, restart Postfix. sudo systemctl restart postfix Step 3 — Testing the SMTP Server echo "This is the body of the email" | mail -s "This is the subject line" your_email_address
score: 0
answers question: http://stackoverflow.com/q/52022134

http://stackoverflow.com/comment/91149864
has text: which line triggers the error?
comment on: http://stackoverflow.com/q/52099565
score: 0
type: Comment
type: QuestionComment

tcp
tags question: http://stackoverflow.com/q/51988711
type: Tag
tags question: http://stackoverflow.com/q/51995311
tags question: http://stackoverflow.com/q/52077150
tags question: http://stackoverflow.com/q/51975728
tag name: tcp

http://stackoverflow.com/q/51980790
has body: I am trying to plot a bar char with python. Following is my code. I am getting 0 value for each of my bar. from __future__ import division import matplotlib.pyplot as plt import numpy as np x = [0,1,2,3,4,5,6,7,8,9,10,11,12] freq = [0.93, 0.87,0.86,0.87,0.93,0.84,0.74,0.79,0.78,0.95,0.88,0.8, 0.71] width = 0.5 # width of the bars fig, ax = plt.subplots() rects1 = ax.bar(x, freq, width, color='r') ax.set_ylim(0,1) ax.set_ylabel('auc-roc') ax.set_xticks(np.add(x,(width/2.2))) # set the position of the x ticks ax.set_xticklabels(('X1', 'X2', 'X3', 'X4', 'X5', 'X6', 'X7', 'X8', 'X9', 'X10', 'X11', 'X12', 'X13')) def autolabel(rects): for rect in rects: height = rect.get_height() ax.text(rect.get_x() + rect.get_width()/2., 1.0*height, '%d' % (height), ha='center', va='bottom') autolabel(rects1) plt.show()
has title: How to plot a bar chart with bar values?
answer count: 1
score: 0
has answer: http://stackoverflow.com/a/51980820
accepted answer: http://stackoverflow.com/a/51980820
tagged with: python
type: Question
type: AnsweredQuestion
tagged with: matplotlib

http://stackoverflow.com/a/51978019
type: Answer
accepted answer of: http://stackoverflow.com/q/51977911
answers question: http://stackoverflow.com/q/51977911
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/90906240
upvote count: 1
has body: You can specify a key attribute for the sorted function. The key can be any function and thus encapsulate your logic. A common way to achieve priority in sorting is to rely on tuple ordering. You key will thus return a (priority, attribute) pair. Code def priority_sort_key(attr, priority, default=float('inf')): def key_func(obj): key = getattr(obj, attr) return (priority.get(key, default), key) return key_func Example class SimpleObject: def __init__(self, name): self.name = name def __repr__(self): return self.name lst = [SimpleObject('apple'), SimpleObject('banana'), SimpleObject('foo')] priority = { 'foo': 1, } print(sorted(lst, key=priority_sort_key('name', priority))) Output [foo, apple, banana]
type: AcceptedAnswer

http://stackoverflow.com/q/52042843
favorite count: 0
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/91133151
has title: Splitting coef into arrays applicable for multi class
type: Question
tagged with: split
has comment: http://stackoverflow.com/comment/91142806
tagged with: arrays
has answer: http://stackoverflow.com/a/52094609
score: 4
has body: I use this function to plot the best and worst features (coef) for each label. def plot_coefficients(classifier, feature_names, top_features=20): coef = classifier.coef_.ravel() for i in np.split(coef,6): top_positive_coefficients = np.argsort(i)[-top_features:] top_negative_coefficients = np.argsort(i)[:top_features] top_coefficients = np.hstack([top_negative_coefficients, top_positive_coefficients]) # create plot plt.figure(figsize=(15, 5)) colors = ["red" if c &lt; 0 else "blue" for c in i[top_coefficients]] plt.bar(np.arange(2 * top_features), i[top_coefficients], color=colors) feature_names = np.array(feature_names) plt.xticks(np.arange(1, 1 + 2 * top_features), feature_names[top_coefficients], rotation=60, ha="right") plt.show() Applying it to sklearn.LinearSVC: if (name == "LinearSVC"): print(clf.coef_) print(clf.intercept_) plot_coefficients(clf, cv.get_feature_names()) The CountVectorizer used has a dimension of (15258, 26728). It's a multi-class decision problem with 6 labels. Using .ravel returns a flat array with a length of 6*26728=160368. Meaning that all indicies that are higher than 26728 are out of bound for axis 1. Here are the top and bottom indices for one label: i[ 0. 0. 0.07465654 ... -0.02112607 0. -0.13656274] Top [39336 35593 29445 29715 36418 28631 28332 40843 34760 35887 48455 27753 33291 54136 36067 33961 34644 38816 36407 35781] i[ 0. 0. 0.07465654 ... -0.02112607 0. -0.13656274] Bot [39397 40215 34521 39392 34586 32206 36526 42766 48373 31783 35404 30296 33165 29964 50325 53620 34805 32596 34807 40895] The first entry in the "top" list has the index 39336. This is equal to the entry 39337-26728=12608 in the vocabulary. What would I need to change in the code to make this applicable? EDIT: X_train = sparse.hstack([training_sentences,entities1train,predictionstraining_entity1,entities2train,predictionstraining_entity2,graphpath_training,graphpathlength_training]) y_train = DFTrain["R"] X_test = sparse.hstack([testing_sentences,entities1te…
upvote count: 4
downvote count: 0
answer count: 1
tagged with: scikit-learn

http://stackoverflow.com/q/51961552
has comment: http://stackoverflow.com/comment/90873734
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/90875326
has body: I have a file (an Apache log file) I need to convert to csv. So the spaces have to be replaced by commas. But one of the columns has fields which have spaces in between them. But that particular field is enclosed in quotation marks. I don't want to remove the spaces which are in the text between quotation marks. How do I go about it? Example of line in the log: 127.0.0.1 - - [17/Aug/2018:12:57:39 +0530] "GET /mysoft-webappp/app/getNotifications?number=5&amp;_=1534489899492&amp;_hkstd=52bf9c52845cecc32af837db8f8e7385c71b229f67f4ef7c42e9ed5c3c14bMTUzNDQ5MDg1OTYzNg== HTTP/1.1" 200 46 ECC40515BD09C8C2FE6FB9ECCFFB40 127.0.0.1
has answer: http://stackoverflow.com/a/51961824
type: Question
has title: While editing a line of text in python, how do i avoid editing a specific part of text in quotation marks?
score: -1
upvote count: 2
downvote count: 3
answer count: 1

http://stackoverflow.com/q/52101446
has answer: http://stackoverflow.com/a/52102124
tagged with: python
favorite count: 0
accepted answer: http://stackoverflow.com/a/52102124
has title: Python - How to split a text taken from a html site
downvote count: 1
has comment: http://stackoverflow.com/comment/91154519
type: AnsweredQuestion
score: -1
type: Question
answer count: 2
upvote count: 0
linked to: http://stackoverflow.com/q/2294493
has body: So I am making a small script where I print out everytime there has been an update on my UPS tracking basically. Right now I have done a script that looks like: tracking_full_site = 'https://wwwapps.ups.com/WebTracking/track?track=yes&amp;trackNums=' + url #URL is the last tracking numbers that I can't provide due to incase someone changes anything with my tracking. headers = { 'User-Agent': ('Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36' ' (KHTML, like Gecko) Chrome/68.0.3440.75 Safari/537.36') } resp = s.get(tracking_full_site, headers=headers, timeout=12) resp.raise_for_status() bs4 = soup(resp.text, 'lxml') old_list = [] for item in bs4.findAll('tr', {'valign': 'top'}): where_is_it = " ".join(item.text.split()) old_list.append(where_is_it) print(old_list) sys.exit() However the outprints that I get is: United States 28.08.2018 6:16 Package departed international carrier facility Edgewood, NY, United States 27.08.2018 20:00 Package transferred to post office United States 27.08.2018 18:42 Package processed by international carrier EDGEWOOD, NY, United States 24.08.2018 15:51 Package processed by UPS Mail Innovations origin facility 24.08.2018 12:55 Package received for processing by UPS Mail Innovations United States 22.08.2018 8:19 Shipment information received by UPS Mail Innovations which looks pretty well with the function " ".join(item.text.split()) My question is, How can I split it so etc I can print out Just the country etc or the date, time or description? EDIT: This is the full HTML is anyone want to see: &lt;table summary="" border="0" cellpadding="0" cellspacing="0" class="dataTable"&gt; &lt;tbody&gt; &lt;tr&gt; &lt;th scope="col"&gt;Location&lt;/th&gt; &lt;th scope="col"&gt;Date&lt;/th&gt; &lt;th scope="col"&gt;Local Time&lt;/th&gt; &lt;th scope="col" class="full"&gt;Activity&amp;nbsp;(&lt;a class="btnlnkR helpIconR" href="javascript:helpModLvl('https://www.ups.com/content/se/en/tracking/tracking/description.html')"&gt;What's this?&lt;/a&gt;)&l…
tagged with: beautifulsoup
linked to: http://stackoverflow.com/q/1732348
possible better answer: http://stackoverflow.com/a/52102064
has comment: http://stackoverflow.com/comment/91154599
has answer: http://stackoverflow.com/a/52102064

http://stackoverflow.com/comment/91049443
score: 0
has text: Thank you, this fixed the issue i was having.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52049379

http://stackoverflow.com/q/52078431
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/91107323
tagged with: python
has comment: http://stackoverflow.com/comment/91106815
has comment: http://stackoverflow.com/comment/91107059
has title: Input function interpreted as variable for some reason
upvote count: 2
has comment: http://stackoverflow.com/comment/91107046
downvote count: 3
type: Question
has comment: http://stackoverflow.com/comment/91107166
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52078569
has body: Been looking around and can't find an answer. So I call either raw_input() or input() to fill out a simple variable. But instead of running the function, I get UnboundLocalError: local variable 'input' referenced before assignment My code doesn't have 'input()' anywhere before that first call, and never makes a variable sharing the name. Same happens for 'raw_input()'. I'm confused here, as calls to the functions work fine in other code, and also on the console, but for some reason throw errors on this. No previous calls. Funny enough, it worked on my first run of the code, but now doesn't. What am I looking for? Edit: Someone asked for the code. Not much to show. end = False lightsoff = [] lightson = [] bias = [] i = 0 while not end: print "Set #" + str(i + 1) +", LED off: ", offFile = input() EDIT: To correct here, a variable named 'input' is referred to much later in the code (it's long). I wrote a couple of references backwards. I didn't know Python made a list (or something) of what's going to be a local variable before running, thus throwing up problems like this.
score: -1
accepted answer: http://stackoverflow.com/a/52078569
has comment: http://stackoverflow.com/comment/91107204
has comment: http://stackoverflow.com/comment/91107587

http://stackoverflow.com/q/52027431
answer count: 0
upvote count: 2
type: UnansweredQuestion
has body: I am learning python and I just want to know how to change the below string1 to a list. Input string: string1 = Hello Output list: to_list = [H, E, L, L, O]
duplicate of: http://stackoverflow.com/q/5501641
tagged with: python
score: 1
has comment: http://stackoverflow.com/comment/91005038
downvote count: 1
type: Question
linked to: http://stackoverflow.com/q/5501641
has title: How do I make this string into a list in python3?
has comment: http://stackoverflow.com/comment/91005292
has comment: http://stackoverflow.com/comment/91005246
has comment: http://stackoverflow.com/comment/91005051
favorite count: 0
tagged with: python-3.x

http://stackoverflow.com/a/52066820
score: 5
answers question: http://stackoverflow.com/q/52054196
has comment: http://stackoverflow.com/comment/139182293
upvote count: 5
type: Answer
has body: Unfortunately not. The generic IMAP search language as defined in RFC 3501 §6.4.4 does not include any provision for searching by time. SINCE is defined to take a &lt;date&gt; item, which is in turn defined as date-day &quot;-&quot; date-month &quot;-&quot; date-year, either with or without quotation marks. IMAP is not even time zone aware, so you will have to locally filter out the first few messages that don't fit in your range based on their INTERNALDATE item. You may even have to fetch an extra days worth of messages. If you're using Gmail, you may be able to use the Gmail search language which is available as an extension.
downvote count: 0

http://stackoverflow.com/comment/90990772
has text: https://github.com/requests/requests/issues/3353
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52019531
score: 0

http://stackoverflow.com/comment/90869596
score: 0
has text: But sometimes the c++ number is bigger than python. Sometimes it is smaller. It is not just a constant shift.
comment on: http://stackoverflow.com/q/51959575
type: Comment
type: QuestionComment

http://stackoverflow.com/a/52093445
downvote count: 1
has body: The "for i in range(5)" was spawning the same process 5 times, creating repetition. This can be achieved simply by removing it and creating the process in a simpler way. for item in items: p = multiprocessing.Process(target=run, args=(item[0], item[1],)) p.start()
has comment: http://stackoverflow.com/comment/91140235
has comment: http://stackoverflow.com/comment/91137013
has comment: http://stackoverflow.com/comment/91138579
upvote count: 0
type: AcceptedAnswer
score: -1
accepted answer of: http://stackoverflow.com/q/52092321
answers question: http://stackoverflow.com/q/52092321
has comment: http://stackoverflow.com/comment/91137867
type: Answer

http://stackoverflow.com/comment/90965772
type: QuestionComment
comment on: http://stackoverflow.com/q/52007488
has text: Many large dynamic sites have a public, documented API that you can use without having to scrape the HTML and/or have terms of service that don’t allow you to use their site programmatically and will actively detect attempts to do so and break them. So, the first thing you should do is read their site to see if either or both of those is true.
score: 0
type: Comment

http://stackoverflow.com/comment/91232602
has text: Still not convinced @ivallesp? Don't hesitate in further discussion if it's not clear.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52112494
type: Comment

http://stackoverflow.com/comment/91053661
type: Comment
has text: Thank You for Your answer can you please explain what is p and a in the function distance
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52051613

http://stackoverflow.com/comment/91109097
comment on: http://stackoverflow.com/q/52079391
has text: Welcome to SO. Please provide a [mcve]. This means include all data [in your question](https://stackoverflow.com/posts/52079391/edit), i.e. no images/links, just text.
type: Comment
type: QuestionComment
score: 2

http://stackoverflow.com/comment/91016105
has text: @dan-klasson, you are still not telling us everything :) Because `requests.post('http://httpbin.org/post', params={'Foo': 'Bar'}).json()` still shows proper query string is sent (case preserved).
comment on: http://stackoverflow.com/q/52032661
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/52042000
score: 1
answers question: http://stackoverflow.com/q/52029187
upvote count: 1
has body: Ok I found something that seems to answer my expectations: It's a ncurse interface to view tables. It has Vim key bindings (perfect), and the tables can be scrolled vertically and horizontally. It can be called from ipython. However, it doesn't support pandas dataframe at the moment, but a PR is available: https://github.com/TabViewer/tabview/pull/116 I'm open to other suggestions but it will do the trick for now.
type: Answer
downvote count: 0

http://stackoverflow.com/q/52029107
tagged with: python
score: 2
answer count: 0
upvote count: 2
has title: Jupyter Notebook: custom.js is not read
type: Question
has body: I am using Jupyter Notebook 5.6.0, in Python 2.7, on Windows 7. I have created %HOMEPATH%.jupyter\custom\custom.js file and added the following code to turn off autosave. define([ 'base/js/events' ], function(IPython, events) { events.on("notebook_loaded.Notebook", function () { IPython.notebook.set_autosave_interval(0); // Disable autosave } // Additional events.on() statements here ); } ); Unfortunately, it has no effect on autosave. However, the problem is not with the code (which one can find in various places), but the fact that Notebook does seem to even read custom.js, neither when the Notebook server starts nor when I open a ipynb file. Further actions I did: 1) I verified that it can find and read it using the appropriate Python code. 2) I added an alert() message in custom.js which is never shown 3) I added the following as an alternative for turning autosave off: Jupyter.notebook.set_autosave_interval(0); that I saw in some other post in stackoverflow.com. Of course, none of these will have any effect if Notebook never reads custom.js. Any idea why is that happening? ... One day later: I cleaned custom.js leaving only Jupyter.notebook.set_autosave_interval(0); Autosave is finally turned off! (So, most probably Notebook didn't like something in custom.js and rejected it totally!) So I consider this question solved.
downvote count: 0
favorite count: 0
tagged with: jupyter-notebook
type: UnansweredQuestion

http://stackoverflow.com/comment/90915581
has text: Sorry if I was not clear, but I want element-wise multiplication, not matrix multiplication
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51983014
type: Comment

http://stackoverflow.com/q/52017524
tagged with: optimization
has answer: http://stackoverflow.com/a/52017705
answer count: 1
tagged with: flatten
has comment: http://stackoverflow.com/comment/90985120
has body: Flattening lists of lists is a well-known problem but how does one flatten a list of lists of lists in the most pythonic way? My ultimate goal is to create a numpy array as follows: [In]: mylist = [[[1,2,3], [4]], [[5,6], [7,8]]] [Out]: array([[1, 2, 3, 4], [5, 6, 7, 8]]) but even just completely flattening into a long list will do (can be easily converted into the right-shaped array anyway). A typical output array will have dimensions (10000, 10) so looping through the rows-to-be is very inefficient. All ideas will be appreciated! (edit) Best solution I can think of: import itertools for i in range(len(mylist)): mylist[i] = list(itertools.chain.from_iterable(mylist[i])) np.array(mylist)
favorite count: 0
type: UnansweredQuestion
tagged with: python
linked to: http://stackoverflow.com/q/952914
score: 2
upvote count: 3
duplicate of: http://stackoverflow.com/q/952914
downvote count: 1
has comment: http://stackoverflow.com/comment/90985302
type: Question
tagged with: numpy
has title: How to completely flatten a list in Python?
tagged with: python-itertools
has comment: http://stackoverflow.com/comment/90985521
linked to: http://stackoverflow.com/q/10632111
has comment: http://stackoverflow.com/comment/90985730

binary-tree
tag name: binary-tree
type: Tag
tags question: http://stackoverflow.com/q/51996982
tags question: http://stackoverflow.com/q/52015279

http://stackoverflow.com/comment/90866075
type: Comment
score: 0
comment on: http://stackoverflow.com/q/51956657
type: QuestionComment
has text: Haven't tried this. What does it say in `ntpath.py` line 85 anyway? [**Did you see this**](https://stackoverflow.com/q/18649512/129130)? Maybe some generic approaches you can test quickly: **1)** Test install on a clean virtual? **2)** Do a test install with a freshly created local admin user? **3)** Do you have access to an English machine?

http://stackoverflow.com/q/52021760
score: 1
tagged with: non-linear-regression
has body: I have trained a NN with a vector input and scalar output (regression). Now I want to find the global minimun of the NN using GD with pytorch. I’m new to programming in general, python specifically, and pytorch even more specifically. I believe what I’m trying to do must have been done a thousand times before, if not ten thousand times. I’ll be super happy and grateful if anyone could point me to some code somewhere (maybe in github) where there’s an example of what I’m trying to do that I could adjust to my needs.
upvote count: 1
has comment: http://stackoverflow.com/comment/90994110
has title: Find global minimun with GD in PyTorch
answer count: 1
downvote count: 0
favorite count: 0
tagged with: gradient-descent
tagged with: python
has answer: http://stackoverflow.com/a/52024252
has comment: http://stackoverflow.com/comment/91003308
tagged with: pytorch
type: UnansweredQuestion
tagged with: regression
type: Question

http://stackoverflow.com/a/52055097
has comment: http://stackoverflow.com/comment/91060616
has comment: http://stackoverflow.com/comment/91060647
has comment: http://stackoverflow.com/comment/91062508
answers question: http://stackoverflow.com/q/52054899
has comment: http://stackoverflow.com/comment/91061853
has comment: http://stackoverflow.com/comment/91060625
has comment: http://stackoverflow.com/comment/91060384
has comment: http://stackoverflow.com/comment/91061326
has comment: http://stackoverflow.com/comment/91060698
score: 0
has comment: http://stackoverflow.com/comment/91062608
upvote count: 1
has comment: http://stackoverflow.com/comment/91062540
has comment: http://stackoverflow.com/comment/91061395
type: AcceptedAnswer
downvote count: 1
has body: This will store it to a file, also its not a good practice to use built in functions and utilities as variable names. so I modified the name as lists try: with open("listofnames.txt","r") as fd: lists=eval(fd.read()) except: lists='Bob','Jim', print("Hello, What\'s your name ?") Name = input("Enter your Name: ") if Name in lists: print("Nice to meet you again", Name) else: lists.insert(0, Name) with open("listofnames.txt","w") as f: f.write(str(lists)) print("Hi " + Name + ", Nice too meet you for the first time.") # Troubleshoot print(lists)
has comment: http://stackoverflow.com/comment/91061690
has comment: http://stackoverflow.com/comment/91060736
type: Answer
accepted answer of: http://stackoverflow.com/q/52054899
has comment: http://stackoverflow.com/comment/91060408

http://stackoverflow.com/a/52120573
accepted answer of: http://stackoverflow.com/q/52106903
score: 0
has body: The syntax <% %> does not actually work in bottle. Always use % and the %end to encapsulate code. Make sure the % is the first non whitespace character of the line. I have run into this myself and have never gotten the above syntax to work either. It has not been a problem since. UPDATE with EXAMPLE: from bottle import run, request, post, get, template, error, static_file from pathlib import Path import re # Show a list of files ready to be moved @get('/move_new_movies') def move_new_movies(): movies = generate_movie_list() return template('move_new_movies', movies = movies) # Generate a list of files for move_new_movies page def generate_movie_list(): ... do some stuff ... return movie_list if __name__ == '__main__': run(debug=True, reloader=True) And your template: Enter path to new movies Folder File Name % for movie in movies: {{movie['folder']}} {{movie['file_name']}} % end Now you would need your javascript to just filter the table once they click enter on the input field. However you might find it easier to just use datatables.net and they can filter on whatever they want.
answers question: http://stackoverflow.com/q/52106903
type: Answer
has comment: http://stackoverflow.com/comment/91192894
has comment: http://stackoverflow.com/comment/91194413
type: AcceptedAnswer

http://stackoverflow.com/q/52087613
has comment: http://stackoverflow.com/comment/91125654
type: Question
tagged with: http://stackoverflow.com/tag/csv
tagged with: datetime
tagged with: python
upvote count: 1
answer count: 1
has answer: http://stackoverflow.com/a/52087758
has comment: http://stackoverflow.com/comment/91125562
has comment: http://stackoverflow.com/comment/91125592
has title: Filtering rows by years; AttributeError: Can only use .dt accessor with datetimelike values
has body: This code is used to show which delivery's are late, prints out the "Material" number associated with it, and shows how many days late the delivery was. My issue now lies with trying to filter the data set to only read a specified range of time; in my following code I attempted to filter the data from 2017 to 2018, however I am receiving an error ( listed below the block of code). How can I filter rows to show only a specified range of time, while conducting the same analysis: which is to see which Material part numbers had a late delivery and to see how many days late it was( without running into an error ) import pandas as pd from datetime import datetime from datetime import timedelta df = pd.read_csv('otd.csv') diff_delivery_date = [] date_format = '%m/%d/%Y' df2 = df[(df['Delivery Date'].dt.year &gt;= 2017) &amp; (df['Delivery Date'].dt.year &lt;= 2018)] for x,y,z in zip(df2['Material'], df2['Delivery Date'], df2['source desired delivery date']): actual_deliv_date = datetime.strptime(y, date_format) supposed_deliv_date = datetime.strptime(z, date_format) diff_deliv_date = supposed_deliv_date - actual_deliv_date diff_delivery_date.append(diff_deliv_date) df['Diff Deliv Date'] = diff_delivery_date print(df2) Full Error: Traceback (most recent call last): File "C:\Users\khalha\eclipse-workspace\Python\Heyy\Code.py", line 13, in &lt;module&gt; df2 = df[(df['Delivery Date'].dt.year &gt;= 2017) &amp; (df['Delivery Date'].dt.year &lt;= 2018)] File "C:\Users\khalha\AppData\Local\Programs\Python\Python37\lib\site-packages\pandas\core\generic.py", line 4372, in __getattr__ return object.__getattribute__(self, name) File "C:\Users\khalha\AppData\Local\Programs\Python\Python37\lib\site-packages\pandas\core\accessor.py", line 133, in __get__ accessor_obj = self._accessor(obj) File "C:\Users\khalha\AppData\Local\Programs\Python\Python37\lib\site-packages\pandas\core\indexes\accessors.py", line 325, in __new__ raise AttributeError("Can only use .dt accessor with datetimelike …
tagged with: pandas
has comment: http://stackoverflow.com/comment/91125575
type: AnsweredQuestion
downvote count: 0
has comment: http://stackoverflow.com/comment/91125610
score: 1
accepted answer: http://stackoverflow.com/a/52087758
favorite count: 0

http://stackoverflow.com/comment/113633171
type: Comment
comment on: http://stackoverflow.com/a/52040014
score: 0
type: AnswerComment
has text: text_type is not defined

http://stackoverflow.com/comment/91061367
score: 0
type: Comment
type: QuestionComment
has text: Please include the full error trace
comment on: http://stackoverflow.com/q/52055658

http://stackoverflow.com/a/51972464
has body: This solution should fit a more broad set of cases (for example, if the variable you want to replace does not always fall in the index 2 position): [[some_new_value if i==y else i for i in each_list] for each_list in my_list] Here is your example (with sample inputs): y = 'y' n = 'n' some_new_value = 'NEW' my_list = [[1,2,y,5],[5,6,y,4],[9,4,n,3],[3,2,n,5]] output = [[some_new_value if i==y else i for i in each_list] for each_list in my_list] Which gives: [[1, 2, 'NEW', 5], [5, 6, 'NEW', 4], [9, 4, 'n', 3], [3, 2, 'n', 5]] And here is another sample input, where the values are not always located in the same index position (or if there are multiple occurrences) for each list in your list of lists: my_list = [[1,y,2,5],[y,6,y,4],[9,4,n,y],[y,2,n,5]] Which gives: [[1, 'NEW', 2, 5], ['NEW', 6, 'NEW', 4], [9, 4, 'n', 'NEW'], ['NEW', 2, 'n', 5]] EDIT Modified answer to change the last element in each list if y is present anyway in the list: [i[:-1] + [some_new_value] if y in i else i for i in my_list] If it will always be located at index 2, then you can do: [i[:-1] + [some_new_value] if i[2]==y else i for i in my_list]
score: 1
has comment: http://stackoverflow.com/comment/90896055
upvote count: 1
accepted answer of: http://stackoverflow.com/q/51972227
answers question: http://stackoverflow.com/q/51972227
has comment: http://stackoverflow.com/comment/90895855
type: AcceptedAnswer
downvote count: 0
type: Answer

http://stackoverflow.com/q/52033164
type: UnansweredQuestion
has title: Python turtle problems
has comment: http://stackoverflow.com/comment/91016551
has comment: http://stackoverflow.com/comment/91016998
tagged with: python-3.x
tagged with: turtle-graphics
type: Question
tagged with: python
score: 0
has body: The website doesnt explain things well A solution would be much appreactiated This is the question: Write a function to draw a rectangle of any size and colour. We will use this function to make some art! We've started your function already; it's called draw_rect. It takes these arguments: width — number of turtle steps height — number of turtle steps colour — the pencolor to use Your function should draw a rectangle with the bottom-left corner at the starting position. Use a pen with the correct colour, and set the size to 3. If we call your function like this: draw_rect(110, 30, 'cornflowerblue') Then your function should draw: We've provided a function that calls draw_rect for you, so you can test your function. This is my code: from turtle import * def draw_rect(width, height, colour): # Draw a rectangle with code! #help needed here! pencolor('cornflowerblue') pensize(3) forward(110) left(90) forward(30) left(90) forward(110) left(90) forward(30) left(90) def draw_city(): draw_rect(30, 120, 'royalblue') goto(-10, 0) draw_rect(80, 30, 'cornflowerblue') goto(-30, 0) draw_rect(80, 60, 'coral') goto(-45, 0) draw_rect(50, 80, 'plum') goto(-55, 0) draw_rect(90, 15, 'orange') goto(-75, 0) draw_rect(20, 40, 'pink') if __name__ == "__main__": # Test your code here! draw_rect(110, 40, 'green') # Uncomment this to draw a city: #draw_city() I'm honestly stuck and to reiterate an answer would be much appreactiated
answer count: 0

http://stackoverflow.com/comment/90942509
type: QuestionComment
has text: I dont think if the format you posted have delimiter as ','.
comment on: http://stackoverflow.com/q/51996545
score: 0
type: Comment

http://stackoverflow.com/comment/91117743
score: 0
type: Comment
has text: @NChauhan Good idea.
type: AnswerComment
comment on: http://stackoverflow.com/a/52083671

http://stackoverflow.com/a/52091674
downvote count: 0
has body: I think you need: import numpy as np df['D'] = (df['A']&gt;5) &amp; (df['B']==True) print(df) Output: A B C D 0 5 True 10 False 1 6 False 2 False 2 1 True 5 False Additional If your desired column is not boolean then you can use np.where: df['D'] = np.where((df['A']&gt;5) &amp; (df['B']==True), 'TRUE','FALSE')
type: Answer
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/52091535
has comment: http://stackoverflow.com/comment/91133209

http://stackoverflow.com/comment/91038385
comment on: http://stackoverflow.com/q/52043718
type: Comment
type: QuestionComment
score: 0
has text: the overhead time of the call is insignificant ... its the stack memory

http://stackoverflow.com/comment/90962485
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52006097
has text: Hey Max, my question is specific to using setuptools :)

http://stackoverflow.com/comment/91058474
comment on: http://stackoverflow.com/q/52054127
type: Comment
type: QuestionComment
score: 2
has text: you are modifiying your list while iterating over it, you should not do that.

http://stackoverflow.com/comment/91044015
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52046063
has text: Yep. This got it. I don't really understand why I was getting the value from the back-reference (e.g. `7`) without the zfill. I understand what you're saying about the character count of the back-reference, but if that's what was being operated on, I'd have expected the value to show up as the back-reference string itself (e.g. `\\1` or `\1`). Clearly that's not the case. While I still haven't wrapped my head around why my code doesn't work, I appreciate that your code does. Thanks!

http://stackoverflow.com/q/51991572
has body: I have a dataframe with multiple headers that is set up as below. I would like to combine the row and column into one line. Any suggestions? I am able to bring down one header but not more. Code import pandas as pd from pandas import ExcelWriter df = pd.read_csv('Sample_Cookbook4.csv',header=[0,1],index_col=[0]) df = df.stack(dropna=False) df.index = df.index.get_level_values(0) + df.index.get_level_values(1) df = df.reset_index() print(df) Current Dataframe Header1 | Header2 | xxx1|xxx2|xxx3|xxx4||xxx1|xxx2|xxx3|xxx4||xxx1|xxx2|xxx3|xxx4 | ColX|ColY |ColA|ColB|ColC|ColD||ColD|ColE|ColF|ColG||ColH|ColI|ColJ|ColDK| 1 | ds | 1 | |+1 |-1 | ....................................... 2 | dh | .......................................................... 3 | ge | .......................................................... 4 | ew | .......................................................... 5 | er | .......................................................... Output ds - Header 1 - xx1 - ColA: 1 ds - Header 1 - xx2 - ColB: "" ds - Header 1 - xx2 - ColB: -1
has title: Reshape dataframe in pandas
answer count: 0
type: UnansweredQuestion
upvote count: 1
has comment: http://stackoverflow.com/comment/90933112
score: 1
type: Question
has comment: http://stackoverflow.com/comment/90932992
downvote count: 0
favorite count: 0
tagged with: pandas
tagged with: python

http://stackoverflow.com/comment/91033392
score: 0
type: Comment
type: QuestionComment
has text: What are your data types? (`df.dtypes`)
comment on: http://stackoverflow.com/q/52041246

http://stackoverflow.com/comment/91093056
has text: Also, your desired example output looks structurally identical to your input, except for the duplicated rows, but your code would ignore a number of original columns while adding some new ones. So, which of the two is your desired output? Also also ... :) the line `if waterclass == 'Water'` is missing a colon in the end and leads me to the question: Do you want this done only if `Asset` is `Water` in your input?
type: Comment
score: 0
comment on: http://stackoverflow.com/q/52070106
type: QuestionComment

ubuntu-server
type: Tag
tag name: ubuntu-server
tags question: http://stackoverflow.com/q/52084725

http://stackoverflow.com/comment/91047377
score: 1
comment on: http://stackoverflow.com/q/52047937
has text: `args` should be a tuple: `args = (build_id,)`
type: Comment
type: QuestionComment

http://stackoverflow.com/a/51989182
upvote count: 1
downvote count: 0
has body: You can use re.sub: import re list1 = ['0x001', '0x002', '0x0a3'] new_result = [re.sub('(?&lt;=x)[0]+', '', i) for i in list1] Output: ['0x1', '0x2', '0xa3']
score: 1
type: Answer
answers question: http://stackoverflow.com/q/51989161

http://stackoverflow.com/a/52053408
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52030518
has comment: http://stackoverflow.com/comment/91120359
has comment: http://stackoverflow.com/comment/91080618
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/52030518
has comment: http://stackoverflow.com/comment/91100999
has body: You can write environment variables to file named environment.properties in simple key=value format: browser=chrome evn=staging and put it to path/to/allure-results/environment.properties before generating a report with commandline or CI plugin
type: Answer
has comment: http://stackoverflow.com/comment/91399887
has comment: http://stackoverflow.com/comment/91120396
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/91120445

http://stackoverflow.com/q/51965320
has comment: http://stackoverflow.com/comment/90880618
has title: How to pass arguments in pytest to the parametrize decorator
linked to: http://stackoverflow.com/q/40880259
has body: I have a test case where the parametrize decorator uses an iterator (that receives two path files as arguments) which test their validity. def iter_wb_results(expected_path, test_path): test_file = open(test_path, "r") ... @pytest.mark.parametrize("first, second", iter_wb_results(EXPECTED_RESULTS_PATH, TEST_PATH), ids=repr) def test_cell_compare(first, second): assert first == second, "No way" The question is how do I pass arguments (the EXPECTED_RESULTS_PATH, TEST_PATH) to the iterator (iter_wb_results) from the command line?
duplicate of: http://stackoverflow.com/q/40880259
has comment: http://stackoverflow.com/comment/90880499
downvote count: 0
favorite count: 0
type: UnansweredQuestion
tagged with: python
score: 2
tagged with: pytest
answer count: 0
upvote count: 2
type: Question

http://stackoverflow.com/a/52050102
has comment: http://stackoverflow.com/comment/91084782
has body: You're not writing a line break to signal the end of a line. Try adding \n like this: shoppinglist_file.write("%s\n" % (thing_to_add))
score: 0
answers question: http://stackoverflow.com/q/52049540
type: Answer

http://stackoverflow.com/comment/90903855
type: AnswerComment
score: 0
type: Comment
has text: `.str.len()` is _much_ faster than `.apply(len)`. `.apply` is a very slow method and should be avoided at any cost.
comment on: http://stackoverflow.com/a/51976821

http://stackoverflow.com/comment/91112350
has text: check now @Rahul Agarwal
comment on: http://stackoverflow.com/a/52060269
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/90952685
comment on: http://stackoverflow.com/a/52000301
score: 0
type: AnswerComment
has text: What you can do now is open your admin interface and check if your objects are there ! (if you dont have an admin account run python manage.py createsuperuser)
type: Comment

http://stackoverflow.com/comment/91039076
type: Comment
comment on: http://stackoverflow.com/q/52011285
score: 1
has text: If you're using a client library, they usually will handle the token refresh, if your original request was for a refreshable token. You should include in your question the relevant code.
type: QuestionComment

http://stackoverflow.com/q/52079177
type: UnansweredQuestion
has body: This is my API FULL OUTPUT - JSON file "took": 150, "total": 3377, "hits": [{ Extra - not relevant JSON information }, { Extra - not relevant JSON information }, ....... total - mean total amount of posts. API limit to 250 posts per request I need to pass through the pages and get all the posts, and then write to the single JSON file. What I have: This is how I pull data from API: def post_puller(): apiUrl = "https://XXXX.XXXX.com/1.0/projects/{}/inbox/search.json".format(config.project_id) json={ 'metrics': ['doc','impression','reach','engagement','repost'], 'flag': {'rt': False}, 'focuses': [{'id':XXXXX, 'include': True}], 'from': '{c.date_from}'.format(c=config), 'to': '{c.date_to}'.format(c=config), 'tz': '{c.tz}'.format(c=config), "start": 0, 'limit': 250 } headers = { 'Content-Type': 'application/json', 'Authorization': 'Bearer {k.token}'.format(k=key) } response = requests.post(url = apiUrl, headers=headers, json=json) result = response.text with open(config.data, "w+") as op: op.write(result.encode("utf-8")) This is my python code which gets the data, modified it and writes to the file: def modify_file_emoji(FILE_NAME,OUTPUT): print("Ready to remove issues from {} file".format(OUTPUT)) jsonFile = open(FILE_NAME, "r") data = json.load(jsonFile) jsonFile.close() #Modify JSON File, that BQ will accept it. with open(OUTPUT, "w+") as outfileJSON: outfileJSON.write(json.dumps(data['hits'])) with open(OUTPUT, "r") as infileInsight: insightData = infileInsight.read()\ .replace("","")\ with open(OUTPUT, "w+") as outfileInsight: outfileInsight.write(insightData) print("File: {} modified - removed all the known issues".format(OUTPUT))
has title: Pass through API pages with PYTHON and JSON
tagged with: http://stackoverflow.com/tag/json
has comment: http://stackoverflow.com/comment/91108487
type: Question
has comment: http://stackoverflow.com/comment/91108675
tagged with: api
has comment: http://stackoverflow.com/comment/91108603
score: 0
tagged with: python
answer count: 0

http://stackoverflow.com/q/52054605
type: Question
answer count: 2
tagged with: api
tagged with: quora
has comment: http://stackoverflow.com/comment/91059909
has answer: http://stackoverflow.com/a/52058101
tagged with: python
score: 0
tagged with: selenium
tagged with: web-scraping
has title: how to click on a webpage all buttons with specific text, one by one
has body: I have this quora webpage as a sample It does contain 4 "View Upvoters" buttons Using this code, I want to get all 4 button in order to click them one by one later. upvoter_list = wait.until(EC.presence_of_all_elements_located((By.CLASS_NAME, 'AnswerVoterListModalLink'))) print(len(upvoter_list)) gives me 4, which is correct when I print the text of the first element of upvoter_list print(upvoter_list[0].text) I get 'view upvoters' as a result but when I print the remaining, i get the empty result, print(upvoter_list[1].text) what is the problem?
has comment: http://stackoverflow.com/comment/91079816
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/52058101
possible better answer: http://stackoverflow.com/a/52063632
has answer: http://stackoverflow.com/a/52063632
linked to: http://stackoverflow.com/q/43933778

http://stackoverflow.com/comment/91127389
score: 0
type: Comment
type: QuestionComment
has text: Can you post a sample of your dataframe and a desired output?
comment on: http://stackoverflow.com/q/52088456

http://stackoverflow.com/comment/90953033
comment on: http://stackoverflow.com/q/52001440
score: 1
type: Comment
type: QuestionComment
has text: There's an answer [here](https://stackoverflow.com/questions/11853551/python-multiple-users-append-to-the-same-file-at-the-same-time) about concurrency and [here](https://stackoverflow.com/questions/7395542/is-explicitly-closing-files-important) about closing files

http://stackoverflow.com/q/52021506
answer count: 2
has body: Alright. Now I am really stumped. I am scraping data with beautiful soup and the pages have a structured format such as the link is https://www.brightscope.com/ratings/a the ratings go through other. Each letter, such as a, b, c, ..., after ratings has multiple pages for them. I am trying to create a while loop to go to each page and while a certain condition exists scrape all the hrefs (which I haven't gotten to that code yet). However, when I run the code the while loop continues to run non stop. How can I fix it to go to each page and search for a condition to run then if it isn't found go to the next letter? Before any might ask, I have searched the code and don't see any li tags while it continues to run. For instance: https://www.brightscope.com/ratings/A/18 is the highest it will go for the A's but it keeps running. import requests from bs4 import BeautifulSoup url = "https://www.brightscope.com/ratings/" page = requests.get(url) soup = BeautifulSoup(page.text, 'html.parser') hrefs = [] ratings = [] ks = [] pages_scrape = [] for href in soup.findAll('a'): if 'href' in href.attrs: hrefs.append(href.attrs['href']) for good_ratings in hrefs: if good_ratings.startswith('/ratings/'): ratings.append(url[:-9]+good_ratings) del ratings[0] del ratings[27:] count = 1 # So it runs each letter a, b, c, ... for each_rating in ratings: #Pulls the page page = requests.get(each_rating) #Does its soup thing soup = BeautifulSoup(page.text, 'html.parser') #Supposed to stay in A, B, C,... until it can't find the 'li' tag while soup.find('li'): page = requests.get(each_rating+str(count)) print(page.url) count = count+1 #Keeps running this and never breaks else: count = 1 break
has comment: http://stackoverflow.com/comment/90993458
has comment: http://stackoverflow.com/comment/90993490
has comment: http://stackoverflow.com/comment/90993449
tagged with: beautifulsoup
has comment: http://stackoverflow.com/comment/90993525
has comment: http://stackoverflow.com/comment/90993441
has answer: http://stackoverflow.com/a/52021665
tagged with: python
has comment: http://stackoverflow.com/comment/90993455
has title: While loop with beautiful soup and python
type: UnansweredQuestion
tagged with: loops
type: Question
has comment: http://stackoverflow.com/comment/90993432
has answer: http://stackoverflow.com/a/52022525
score: 0

http://stackoverflow.com/comment/90999066
score: 0
comment on: http://stackoverflow.com/q/52024351
type: Comment
has text: Like I said, I can't do that because they are based on specific python 2 dependencies that work only on python 2.
type: QuestionComment

http://stackoverflow.com/q/52022489
possible better answer: http://stackoverflow.com/a/52022508
favorite count: 0
has comment: http://stackoverflow.com/comment/90995370
has answer: http://stackoverflow.com/a/52022548
has comment: http://stackoverflow.com/comment/90995341
tagged with: python
tagged with: python-3.x
score: 2
upvote count: 2
accepted answer: http://stackoverflow.com/a/52022548
type: Question
type: AnsweredQuestion
has title: Sorting a list of objects by attibute doesn't sort?
has body: i want to programm a hold'em pokersimulator in python to learn the language (python 3.7). I started by creating a Card-class that contains value (eg. 5 or K) and a suit (eg hearts or spades). A deck of cards is created by matching each value with each suit: suits = ["Hearts","Diamonds","Spades","Clubs"] values = ["2","3","4","5","6","7","8","9","10","11","12","13","14"] #note that i replaced the values J by 10, Q by 11...to later easier compare them class Card(object): value = 0 suit = "" def __init__(self, value, suit): self.value = value self.suit = suit def create_card(value, suit): card = Card(value, suit) return card deck = [] for i in values: for j in suits: deck.append(create_card(i,j)) random.shuffle(deck) so now i have a shuffled list of Card-objects and take two cards and assign them to a player. I then draw 5 more cards, the commoncards: player1 = [] for i in range(2): player1.append(deck.pop(0)) commoncards = [] for i in range(5): commoncards.append(deck.pop(0)) Now i have two lists of Card-objects, one for my players wholecards and one for the common cards. So far so good. Now i want to determine the players hand (eg a pair, two pair or three of a kind etc) and i thought a nice way would be to join the players list and a copy of the commoncards list and sort it by value to check if two 'neighbour' elements have the same value: commoncardscopy=commoncards.copy() player1.extend(commoncardscopy) player1.sort(key=lambda Card : Card.value) for i in range(len(player1)): print(player1[i].value) This should print 7 sorted cardvalues (eg 2,2,4,5,8,8,12), right? Well, it doesn't. Here is an example output: 10 13 13 14 7 7 9 Does anyone know why? Any help or feedback is appreciated :)
has comment: http://stackoverflow.com/comment/90995297
has answer: http://stackoverflow.com/a/52022508
answer count: 2
downvote count: 0
tagged with: sorting

http://stackoverflow.com/comment/90888066
score: 4
type: QuestionComment
has text: You've mistyped `sale-info`. It should be `sales-info`
type: Comment
comment on: http://stackoverflow.com/q/51968850

http://stackoverflow.com/q/51989388
tagged with: pandas
has comment: http://stackoverflow.com/comment/90928601
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/90928515
tagged with: python
accepted answer: http://stackoverflow.com/a/51989662
type: AnsweredQuestion
score: 1
has answer: http://stackoverflow.com/a/51990075
upvote count: 1
has title: How to group by date and find consecutive day count
type: Question
tagged with: numpy
has body: So I have a table like product date_purchased apple 2018-08-01 apple 2018-08-02 apple 2018-08-03 apple 2018-08-10 apple 2018-08-11 banana 2018-08-14 I am trying to look for how many times the product was purchased on consecutive days. like apple 2018-08-01 1 apple 2018-08-02 2 apple 2018-08-03 3 apple 2018-08-10 1 apple 2018-08-11 2 banana 2018-08-14 1 The first column in product, second column is the last date it was purchased and the third column is the days it was purchased consecutively. [EDIT]: Changed the output format
possible better answer: http://stackoverflow.com/a/51990075
tagged with: dataframe
has answer: http://stackoverflow.com/a/51989662
has comment: http://stackoverflow.com/comment/90929383
answer count: 2

http://stackoverflow.com/a/51984223
has comment: http://stackoverflow.com/comment/90919152
has comment: http://stackoverflow.com/comment/90918544
downvote count: 0
has comment: http://stackoverflow.com/comment/90918246
type: Answer
answers question: http://stackoverflow.com/q/51984121
has body: Sounds like you are using lambda wrong because you need map as well: c = [{"h_mag":"19.7","i_deg":"9.65","moid_au":"0.035"},{"h_mag":"20.5","i_deg":"14.52","moid_au":"0.028"}] list(map(lambda rec: rec.get('moid_au'), c)) ['0.035', '0.028'] Each lambda grabs a record from your list and you map your function to that.
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/90918887

http://stackoverflow.com/comment/90989976
type: QuestionComment
comment on: http://stackoverflow.com/q/52019795
score: 1
has text: first code: use `load` instead `loads`
type: Comment

http://stackoverflow.com/q/52102706
score: 0
upvote count: 1
downvote count: 1
tagged with: tensorflow
type: Question
has answer: http://stackoverflow.com/a/52107710
linked to: http://stackoverflow.com/q/52199843
answer count: 1
has body: I have a problem about finding a value in from other tensor. The description of this problem is as follows. For example, Input Tensor s_idx = ( 1, 3, 5, 7) e_idx = ( 3, 4, 5, 8) label_s_idx = (2, 2, 3, 6) label_e_idx = (2, 3, 4, 8) In the figure above, the value of s_idx[1] is equal to label_s_idx[2] and the value of e_idx[1] is equal to label_e_idx[2]. In other words, the problem is to give output[i] a value of 1 if the conditions s_idx[i] == label_s_idx[i] and e_idx[i] == label_s_idx[j] for some j in range of the length of label_s_idx (== length of label_e_idx) are satisfied. Thus, in the above example, the output tensor is output = ( 0, 1, 0, 0) How do I code like this on Tensorflow in Python?
has comment: http://stackoverflow.com/comment/91156918
favorite count: 0
accepted answer: http://stackoverflow.com/a/52107710
tagged with: python
has comment: http://stackoverflow.com/comment/91159280
has title: How to find a value in tensor from other tensor in Tensorflow
type: AnsweredQuestion

http://stackoverflow.com/comment/91097951
comment on: http://stackoverflow.com/q/52053792
has text: Hi. Thanks for responding. What I am trying to get is a single list of all the attributes, including their heirarchy. There may be a bunch of attributes in other json strings I am missing here.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91048229
score: 0
comment on: http://stackoverflow.com/q/52048698
type: QuestionComment
has text: what is `Help`?
type: Comment

http://stackoverflow.com/comment/90896696
type: Comment
type: QuestionComment
has text: ok thanks. the downvotes were unnecessary I started with 3.6 version I did not know 3.5 didn't have f strings.
comment on: http://stackoverflow.com/q/51973089
score: 0

http://stackoverflow.com/q/52064366
tagged with: tensorflow
type: UnansweredQuestion
answer count: 0
downvote count: 0
score: 1
favorite count: 0
has title: Could the default value of a TensorFlow op attribute be NaN or Inf?
type: Question
tagged with: python
tagged with: c++
upvote count: 1
has body: My case is to add vmin and vmax attributes to the TensorFlow ImageSummary Op. Here is my code for this op registration: REGISTER_OP("ImageSummary") .Input("tag: string") .Input("tensor: T") .Output("summary: string") .Attr("vmin: float = NaN") .Attr("vmax: float = NaN") .Attr("clip: bool = false") .Attr("max_images: int &gt;= 1 = 3") .Attr("T: {uint8, float, half, float64} = DT_FLOAT") .Attr( "bad_color: tensor = { dtype: DT_UINT8 " "tensor_shape: { dim { size: 4 } } " "int_val: 255 int_val: 0 int_val: 0 int_val: 255 }") .SetShapeFn(shape_inference::ScalarShape); Although this works for the C++ test code, there were some errors when building the whole project: bazel-out/darwin-opt/genfiles/tensorflow/cc/ops/logging_ops.h:237:19: error: cannot initialize a member subobject of type 'float' with an lvalue of type 'float (const char *)' float vmin_ = nanf; ^~~~ bazel-out/darwin-opt/genfiles/tensorflow/cc/ops/logging_ops.h:238:19: error: cannot initialize a member subobject of type 'float' with an lvalue of type 'float (const char *)' float vmax_ = nanf; I think it should be float vmin = nanf("") and float vmax = nanf("") in logging_ops.h. Is this an issue in TensorFlow compiler? Or I may have some misunderstanding of the grammar for setting the default value? Are there any suggestions for my case?

http://stackoverflow.com/a/53608493
score: 0
type: Answer
answers question: http://stackoverflow.com/q/52037135
has body: To get a mapping of the actual character to the name in the cmap table, you can do something like this: font = TTFont(fontPath) ch_to_name = {} # key will be the codepoint in hex, value will be name cmap = font["cmap"] for ch, name in cmap.getBestCmap().items(): ch_to_name["{:04X}".format(ch)] = name

http://stackoverflow.com/comment/90902505
type: Comment
comment on: http://stackoverflow.com/q/51972632
score: 0
type: QuestionComment
has text: @KathanVyas Hmm, that's odd. The error you're getting is saying you're NOT getting back a hostname. Step through the function: (1) see what you get with: socket.gethostname() then (2) see what socket.gethostbyname_ex(socket.gethostname()) returns.

http://stackoverflow.com/comment/90943384
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/51997053
type: Comment
has text: What is your desired output from this code?

http://stackoverflow.com/q/52111530
has comment: http://stackoverflow.com/comment/91173987
has answer: http://stackoverflow.com/a/52111897
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91174044
tagged with: python
tagged with: request
downvote count: 0
score: 1
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/52111896
has title: form data request with many elements with same name
upvote count: 1
has body: I do need to create a long parameter list for a web page post which is not a dictionary based cause of multiple same keys. Chromium shows this string as form data in the original request p_action=RUN&amp;p_mode=1&amp;p_exec_mode=&amp;p_page_url=&amp;p_redirect_url=&amp;p_reference_path=&amp;p_arg_names=_title&amp;p_arg_values=ARRAYSTART&amp;p_arg_values=kschulz&amp;p_arg_values=ARRAYEND&amp;p_arg_names=reqnum&amp;p_arg_values=ARRAYSTART&amp;p_arg_values=0&amp;p_arg_values=ARRAYEND&amp;p_arg_names=_orderby_ord_1&amp;p_arg_values=ASC .... much more entries follow. I know this is a crazy form data but I can not change this. p_arg_names is used multiple times and sometimes followed by multiple p_arg_value entries. Array Start and Array Stop are even existing... So I need the right order too. params=dict... can not work here. How can I provide requests.push(URL,DATA) a longer pure string without losing the Content-Type:application/x-www-form-urlencoded
linked to: http://stackoverflow.com/q/20759981

http://stackoverflow.com/a/52075427
downvote count: 0
has body: Create a set of the individual words from every element in the list with more than one word. Then use a list-comprehension to filter elements that are entirely in that set. This solution is O(n) which is the best you can do efficiency-wise (better than just checking in the list as that is O(n^2)). parts = {w for e in list1 if ' ' in e for w in e.split()} out = [e for e in list1 if e not in parts]
upvote count: 2
type: Answer
answers question: http://stackoverflow.com/q/52075263
score: 2

http://stackoverflow.com/a/52034040
upvote count: 7
has comment: http://stackoverflow.com/comment/91018144
answers question: http://stackoverflow.com/q/52033852
downvote count: 0
has body: The code runs fine for me. Look at the following example server code: from flask import Flask from flask import jsonify app = Flask(__name__) @app.route('/') def hello(): d = {'left': 0.17037454, 'right': 0.82339555, '_unknown_': 0.0059609693} message = { 'status': 200, 'message': 'OK', 'scores': d } resp = jsonify(message) resp.status_code = 200 print(resp) return resp if __name__ == '__main__': app.run() And the following curl returns fine: $ curl http://localhost:5000/ { "message": "OK", "scores": { "_unknown_": 0.0059609693, "left": 0.17037454, "right": 0.82339555 }, "status": 200 }
has comment: http://stackoverflow.com/comment/137042655
has comment: http://stackoverflow.com/comment/91018340
type: Answer
score: 7

http://stackoverflow.com/q/52037507
answer count: 3
tagged with: pandas
tagged with: python
upvote count: 3
has answer: http://stackoverflow.com/a/52038587
type: UnansweredQuestion
downvote count: 1
has answer: http://stackoverflow.com/a/52037734
has answer: http://stackoverflow.com/a/52037711
tagged with: dataframe
has title: Python Pandas: update dataframe values from another dataframe
type: Question
score: 2
favorite count: 0
has body: I have these two dataframes: (update: I've added one column stuffto df1 to specify that the two dataframes have not the same schemas) df1 = pd.DataFrame({'id': ['1','2','3'], 'val': [0, 0, 0], 'stuff': ['foo', 'bar', 'spam']}) df2 = pd.DataFrame({'id': ['2','3'], 'val': [10, 20]}) print(df1) id val stuff 0 1 0 foo 1 2 0 bar 2 3 0 spam print(df2) id val 0 2 10 1 3 20 I want to update the values in df1 val column with the values from df2 val column based on the id column. Desired result after transformation on df1: print(df1) id val stuff 0 1 0 foo 1 2 10 bar 2 3 20 spam I could use a join (merge) but then I would need several more steps to end up with the expected result (casting the column from float to int, dropping column, etc.). (BTW, if you have a simple and elegant way to it with a join, I am also interested). I am trying to use slicing methods but could not figure out how. Example: &gt;&gt;&gt; df1.loc[df1['id'].isin(df2['id']), 'val'] = df2['val'] gives: print(df1) id val stuff 0 1 0.0 foo 1 2 20.0 bar 2 3 NaN spam Update: One more constraint: do not modify the original df1 index.

http://stackoverflow.com/q/51962106
score: 7
tagged with: max-pooling
has title: Keras Model with Maxpooling1D and channel_first
has comment: http://stackoverflow.com/comment/90874709
has comment: http://stackoverflow.com/comment/90875105
upvote count: 7
has comment: http://stackoverflow.com/comment/90874642
answer count: 1
has answer: http://stackoverflow.com/a/51963170
accepted answer: http://stackoverflow.com/a/51963170
tagged with: keras
tagged with: python
has body: I have a problem with my current attempt to build a sequential model for time series classification in Keras. I want to work with channels_first data, because it is more convenient from a perprocessing perspective (I only work with one channel, though). This works fine for the Convolution1D layers I'm using, as I can specify data_sample='channels_first', but somehow this won't work for Maxpooling1D, which doesn't have this option as it seems. The model I want to build is structured as follows: model = Sequential() model.add(Convolution1D(filters=16, kernel_size=35, activation='relu', input_shape=(1, window_length), data_format='channels_first')) model.add(MaxPooling1D(pool_size=5) model.add(Convolution1D(filters=16, kernel_size=10, activation='relu', data_format='channels_first')) [...] #several other layers here With window_length = 5000 I get the following summary after all three layers are added: _________________________________________________________________ Layer (type) Output Shape Param # ================================================================= conv1d_1 (Conv1D) (None, 32, 4966) 1152 _________________________________________________________________ max_pooling1d_1 (MaxPooling1 (None, 4, 4966) 0 _________________________________________________________________ conv1d_2 (Conv1D) (None, 16, 4957) 656 ================================================================= Total params: 1,808 Trainable params: 1,808 Non-trainable params: 0 Now, I wonder if this is correct, as I would expect the third dimension (i.e. the number of neurons in a feature map) and not the second (i.e. the number of filters) to be reduced by the pooling layer? As I see it, MaxPooling1D does not recognize the channels_first ordering and while the Keras documentation says there exists a keyword data_format for MaxPooling2D, there's no such keyword for MaxPooling1D. I tested the whole setup with a channels_last data format, and it worked as I expected. But since the conversion from ch…
favorite count: 0
has comment: http://stackoverflow.com/comment/90875018
downvote count: 0
tagged with: machine-learning
has comment: http://stackoverflow.com/comment/90905682
type: Question
type: AnsweredQuestion
tagged with: conv-neural-network

http://stackoverflow.com/comment/91014900
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52031838
has text: Can u try once ` $httpProvider.defaults.xsrfCookieName = 'csrftoken'; $httpProvider.defaults.xsrfHeaderName = 'X-CSRFToken';` i had to add these lines in my DJango app to make it's form work with angularjs
score: 0

http://stackoverflow.com/a/52001363
has comment: http://stackoverflow.com/comment/90961501
type: Answer
answers question: http://stackoverflow.com/q/52001152
score: 0
has comment: http://stackoverflow.com/comment/90953715
has body: dir is a built-in function. When it is passed an object it uses the object's __dict__ (if defined) and its corresponding type object to attempt to display attributes. Note that built-in dir can result in strange outputs if __getattr__ has been overridden in the object. Read more: https://docs.python.org/3/library/functions.html#dir Addressing comment: Apologies, I don't have enough reputation to comment. All objects in Python implicitly have a bunch of special attributes, one of these is the __dict__ attribute. In Python, classes are objects too. Therefore your otherclass class already has a __dict__. In your code, try: otherclass.__dict__ In the output you'll see some of the output corresponds to the output of the dir call. Edit 2: Like I said, classes are objects in Python. They implicitly have all of the methods objects have. Try: object.__dict__ and you'll find dir in there.

http://stackoverflow.com/q/51984646
has title: Dynamic Data Web Scraping with Python, BeautifulSoup
favorite count: 0
tagged with: beautifulsoup
has answer: http://stackoverflow.com/a/51985365
tagged with: http://stackoverflow.com/tag/html
linked to: http://stackoverflow.com/q/51982930
has body: I am trying to extract this data(number) for many pages from the HTML. The data is different for each page. When I try to use soup.select('span[class="pull-right"]') it should give me the number, but only the tag comes. I believe it is because Javascript is used in the webpage. 180,476 is the position of data at this specific HTML that I want for many pages: Pageviews: 180,476 Daily average: 8,594 My code(this is in a loop to work for many pages): res = requests.get(wiki_page, timeout =None) soup = bs4.BeautifulSoup(res.text, 'html.parser') ab=soup.select('span[class="pull-right"]') print(ab) output: [\n \n \n Logarithmic scale \n, \n \n \n Begin at zero \n, \n \n \n Show values \n] Example URL:https://tools.wmflabs.org/pageviews/?project=en.wikipedia.org&platform=all-access&agent=user&range=latest-20&pages=Star_Wars:_The_Last_Jedi I want the Pageviews
tagged with: python
linked to: http://stackoverflow.com/q/6183276
has comment: http://stackoverflow.com/comment/90918663
type: AnsweredQuestion
tagged with: web-scraping
upvote count: 1
type: Question
accepted answer: http://stackoverflow.com/a/51985365
score: 1
has comment: http://stackoverflow.com/comment/90919819
answer count: 2
possible better answer: http://stackoverflow.com/a/51985144
downvote count: 0
has answer: http://stackoverflow.com/a/51985144
tagged with: javascript

http://stackoverflow.com/comment/91000642
type: Comment
comment on: http://stackoverflow.com/q/52023174
score: 0
has text: Listening to keystrokes systemwide is not a problem that is solvable by means of asyncio. If you rather mean listening to input sent to a certain fd I can help you.
type: QuestionComment

http://stackoverflow.com/comment/91135813
type: QuestionComment
has text: When I run this command from my laptop with a program located on the server, will it still run on the server even if I shut the notebook down?
comment on: http://stackoverflow.com/q/52092806
score: 0
type: Comment

http://stackoverflow.com/comment/90874819
type: Comment
score: 0
type: AnswerComment
has text: Thanks for the sophisticated examples.
comment on: http://stackoverflow.com/a/51961668

http://stackoverflow.com/a/63785471
answers question: http://stackoverflow.com/q/52034771
downvote count: 1
type: Answer
score: 7
has body: # tested in Python 3.8.5 32-bit # overloads the method # imports libraries from the base distribution # confuses some linters # undermines type-hinting by documenting *kwargs or dispatch signature from functools import singledispatch class Car: def __init__(self, color: str, brand: str) -> None: self.color = color self.brand = brand @singledispatch def describe_car(color: str, kind: str) -> str: return "Little " + color + " " + kind @describe_car.register(Car) def _(car: Car) -> str: return describe_car(car.color, car.brand) newcar = Car("red", "corvette") print(describe_car("green", "pinto")) print(describe_car(newcar)) pythonout> Little green pinto Little red corvette
upvote count: 8

http://stackoverflow.com/q/52112137
type: AnsweredQuestion
has body: Sorting in Dask Based on this answer I want to build the combined column dynamically df_post['sort_column'] = df_post.apply(lambda r:str([r[col1],r[col2],r[col3]]), axis=1) df_post = df_post.set_index('sort_column') df_post = df_post.map_partitions(lambda x: x.sort_index()) I am not able to figure out a way to make this [r[col1],r[col2],r[col3]] dynamic based on a list of columns provided by config file.
has comment: http://stackoverflow.com/comment/91175552
accepted answer: http://stackoverflow.com/a/52119221
downvote count: 1
type: Question
linked to: http://stackoverflow.com/q/50809462
tagged with: sorting
tagged with: apply
tagged with: pandas
upvote count: 0
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/52119221
tagged with: dask
tagged with: python
has title: Build a combined column in dask dataframe for sorting
score: -1

http://stackoverflow.com/comment/91137243
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52087965
type: AnswerComment
has text: I fixed the error @gangabass. I've eliminated the 'u' from the: source_json = re.sub(ur'//[^\n]+', "", source_json). So now it looks like: source_json = re.sub(r'//[^\n]+', "", source_json). The problem is that in the final csv where I store the information it return the right headers but the information is ",,," so it didn't retrieves nothing. I will update the code in my question, so you can see how it looks now. I don't have errors, but it doesn't work as intended.

http://stackoverflow.com/q/52025970
has comment: http://stackoverflow.com/comment/91002691
has comment: http://stackoverflow.com/comment/91002714
has comment: http://stackoverflow.com/comment/91002215
tagged with: django-templates
has body: I have encountered a problem when i wanted to display some information from my list and some other information from my object. Here is what i have done so far. I have this two class here : class CoursesNames(models.Model): DB = "data structure" SF = "software enginering" courseChoices = ( (DB, "data structure"), (SF, "software enginering"), ) courses = models.CharField(max_length=50, choices=courseChoices) class Document(models.Model): course_name = models.ForeignKey( CoursesNames, on_delete=models.CASCADE, related_name='document_courses') title = models.CharField(max_length=100) description = models.TextField(help_text="some text for now") Here is my view def showDocuments(request, *args, **kwargs): documents = Document.objects.all() context = { "documents": documents, "files": [], # an empty list for now } # After writing some logic context["files"].append(item) file_name = request.POST["course"] context["filename"] = file_name return render(request, 'dashboard.html', context) and here is my html page: # i am stuck here ! {% if files %} {% for file in files%} {% for document in documents %} {% if document.course_name == filename %} {{filename}} {{document.title }} this is a text where you should the best compilation of files that will definitely will help you get a st straight a inshallah Download {% endif %} {% endfor %} {% endfor %} i want to show some real data instead of showing "here is some text" by using the Document Class i have shown above so i can use {{document.title}} and {{document.description}} but i can't find a way to do so any help will be appreciated
tagged with: django
tagged with: python
type: AnsweredQuestion
score: 1
type: Question
has title: Django loop through a list and objects in the same time
upvote count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/52028289
accepted answer: http://stackoverflow.com/a/52028289
answer count: 1
favorite count: 0

http://stackoverflow.com/a/59814559
score: 7
downvote count: 0
type: Answer
has body: If you're using django-pytest and have enabled the optimization --reuse-db and have made DB migrations between test runs you need to re-create the DB tables again. pytest --create-db
answers question: http://stackoverflow.com/q/52048778
upvote count: 7

http://stackoverflow.com/q/52022436
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/91015726
type: UnansweredQuestion
tagged with: django
tagged with: python
tagged with: odoo
type: Question
has answer: http://stackoverflow.com/a/57951020
has body: I can not connect with odoo in any way, this is what I am doing: view.py class UserSerializer(ModelSerializer): class Meta: model = User fields = '__all__' class ProxiedTransport(Transport): def set_proxy(self, host, port=None, headers=None): self.proxy = host, port self.proxy_headers = headers def make_connection(self, host): connection = http.client.HTTPConnection(*self.proxy) connection.set_tunnel(host, headers=self.proxy_headers) self._connection = host, connection return connection class ResUser(ViewSet): url = 'http://localhost' db = 'odoo8' username = 'admin' password = 'admin' def list(self,request,format=None): p = ProxiedTransport() p.set_proxy('proxy.server',8080) common = ServerProxy('{}/xmlrpc/2/common'.format(self.url),p) uid = common.authenticate(self.db,self.username,self.password,{}) return Response({}) But he throws me an error: Request Method: GET Request URL: http://localhost:8000/odoo-api/res/ Django Version: 2.1 Exception Type: gaierror Exception Value: [Errno -2] Name or service not known Exception Location: /usr/lib/python3.6/socket.py in getaddrinfo, line 745 Where can be the problem?
has comment: http://stackoverflow.com/comment/91001107
score: 0
tagged with: xmlrpclib
answer count: 1
has title: django error when connecting with odoo xmlrpc

http://stackoverflow.com/comment/91061863
comment on: http://stackoverflow.com/q/52043671
score: 0
type: Comment
type: QuestionComment
has text: Maybe your camera isn't capable of 1280x720, not all cameras shoot all resolutions.

http://stackoverflow.com/q/52003960
upvote count: 7
has comment: http://stackoverflow.com/comment/90957597
has answer: http://stackoverflow.com/a/52005015
has title: Conditionally offseting values by group with Pandas
has answer: http://stackoverflow.com/a/52004459
has answer: http://stackoverflow.com/a/52004625
type: AnsweredQuestion
tagged with: performance
score: 7
tagged with: dataframe
possible better answer: http://stackoverflow.com/a/52004459
type: Question
tagged with: pandas-groupby
downvote count: 0
has body: I am looking for a more efficient and maintainable way to offset values conditionally by group. Easiest to show an example. Value is always non-negative for Offset == False and always negative for Offset == True. What I'm looking to do is "collapse" positive Values (flooring at 0) against negative ones by Label. Note Label + Offset combined are always unique. Since Offset is Boolean, you can only have a maximum of 2 rows per Label. Example 1 df = pd.DataFrame({'Label': ['L1', 'L2', 'L3', 'L3'], 'Offset': [False, False, False, True], 'Value': [100, 100, 50, -100]}) # input # Label Offset Value # 0 L1 False 100 # 1 L2 False 100 # 2 L3 False 50 # 3 L3 True -100 Desired output: Label Offset Value 0 L1 False 100 1 L2 False 100 2 L3 False 0 3 L3 True -50 Example 2 df = pd.DataFrame({'Label': ['L1', 'L2', 'L3', 'L3'], 'Offset': [False, False, False, True], 'Value': [100, 100, 100, -50]}) # input # Label Offset Value # 0 L1 False 100 # 1 L2 False 100 # 2 L3 False 100 # 3 L3 True -50 Desired output: Label Offset Value 0 L1 False 100 1 L2 False 100 2 L3 False 50 3 L3 True 0 Current inefficient solution My current solution is a manual loop which is slow and difficult to maintain: for label in df['Label'].unique(): mask = df['Label'] == label if len(df.loc[mask]) == 2: val_false = df.loc[~df['Offset'] &amp; mask, 'Value'].iloc[0] val_true = df.loc[df['Offset'] &amp; mask, 'Value'].iloc[0] if val_false &gt; abs(val_true): df.loc[~df['Offset'] &amp; mask, 'Value'] += val_true df.loc[df['Offset'] &amp; mask, 'Value'] = 0 else: df.loc[~df['Offset'] &amp; mask, 'Value'] = 0 df.loc[df['Offset'] &amp; mask, 'Value'] += val_false I'm looking for a vectorised, or at least partially vectorised, solution to improve performance and get rid of this mess.
accepted answer: http://stackoverflow.com/a/52004625
favorite count: 0
answer count: 3
has comment: http://stackoverflow.com/comment/90957571
tagged with: pandas
tagged with: python

http://stackoverflow.com/a/52059883
answers question: http://stackoverflow.com/q/52059772
downvote count: 0
score: 1
type: Answer
has body: Your approach is too naive. First you will have to tokenize the user input (what if the user inputs math,physics instead of math and physics? .split will not separate math from physics in this case). Then you will need to call favsub.count with each memeber of list (which is a bad variable name by the way as it shadows the built-in list). I will suggest another naive (but easier) approach. Forget about splitting and tokenizing the user input. Simply search each recognized subject and sum the results: subjects_list = ["math", "physics", "biology", "computer science"] favsub = input("What are your favorite subjects? \n") favsub = favsub.lower() count = 0 for subject in subjects_list: if subject in favsub: count += 1 print(count) This is essentially the same as @schwobaseggl's answer but with an explicit counter.
upvote count: 1

http://stackoverflow.com/comment/91147909
type: Comment
has text: Now I see. Your function seems to assume Nx2 arrays for P0 and P1. I was able to feed it Nx3 by changing `ImnnT = np.eye(2)-nnT` to `ImnnT = np.eye(3)-nnT`. When I did it with the same z values for each point (all in a 2D plane), I got the same answer as just feeding the x & y data in. Does this change make sense for a 3D collection of points?
comment on: http://stackoverflow.com/a/52089867
type: AnswerComment
score: 1

http://stackoverflow.com/comment/91054310
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52046282
has text: Did you try to use `gdal_translate` from GDAL? `gdal_translate -of GTiff file.nc test.tiff`

http://stackoverflow.com/q/52011401
has comment: http://stackoverflow.com/comment/90973919
has comment: http://stackoverflow.com/comment/90974469
has answer: http://stackoverflow.com/a/52011445
tagged with: function
has body: Hello I'm not too sure how to word this, but I'm a beginner in python so I know my code will look really rough but its what I've found from trial and error to work for me. So onto my question, I'm trying to build a mock bank interface this is what the main menu looks like: #!/usr/bin/env python from time import sleep from CustomerCreator import CreateCustomer users = {} def main(): value = 0 while value == 0: print("Hello and Thank You for Choosing to Bank With the Best!\n\t\tYour Service is Appreciated!") sleep(0.5); print("Please choose one of the following: " "\nCreate New User: 1" "\nManage Your Account: 2" "\nTerminate Your Account: 3" "\nExit Application: 0") sleep(0.25); selection = int(input("Your Selection: ")) value += selection if value == 1: print("Welcome To The New User Menu") CreateCustomer.create_user() # make a class to reset the user back to the main menu if value == 2: input("Enter Account Number or Name to Access: ") # make a class to reset the user back to the main menu if value == 2: test = input("Enter Account Name to Terminate: ") input("Are You Sure You Want to Terminate " + test + "?") # make a class to reset the user back to the main menu main() You can see that in the beginning of the code i declare a dictionary in which to store the users, I've already come up with code that will ask for the user to input a name for their bank account and it'll generate a random "account number" to assign the user, the code is as follows: #!/usr/bin/env python from time import sleep import random class CreateCustomer: @staticmethod def create_user(): def new_user() -&gt; str: print("Welcome to The 'Create New User' Interface") sleep(0.5) x = input("Enter Name to Use for Account Access\n*Name is Case Sensitive to Access Account*: ") print(x) return x def account_generator() -&gt; int: x = '0123456789' acctlen = 8 acctnum = ''.join(random.sample(x, acctlen)) print(acctnum) return int(acctnum) user = new_user() account_number = account_generator() return us…
type: UnansweredQuestion
tagged with: class
has title: How to update dictionary via class python 3
tagged with: python
tagged with: python-3.x
type: Question
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/52011436
tagged with: dictionary

http://stackoverflow.com/q/51969610
has body: I have two classes, a main class which creates instances of my other class. class Builder: def __init__(self, id): self.id = id def build_thing(self, main_ftr, main_attr, attrs = {}): # note the main ftr/attrs gets added to attrs no matter what attrs[main_ftr] = attrs.get(main_ftr, []) + [main_attr] return Thing(main_ftr, main_attr, attrs) class Thing: def __init__(self, main_ftr, main_attr, attrs): self.main_ftr = main_ftr self.main_attr = main_attr self.attrs = attrs The issue I'm having has to do with the attrs dictionary that gets passed to the Thing class. The problem is that each time I use the Builder class to create a Thing class, the attrs argument retains it's previous values b = Builder('123') t = b.build_thing('name', 'john') print(t.attrs) # {'name': ['john'] } # Goal is this creates a new "Thing" with only attrs = {'name':['mike']} t2 = b.build_thing('name', 'mike') print(t2.attrs) # {'name': ['john', 'mike']} My Question is 2 part: Why is this happening? How do I fix it?
type: Question
upvote count: 2
linked to: http://stackoverflow.com/q/1132941
answer count: 1
accepted answer: http://stackoverflow.com/a/51969775
favorite count: 0
tagged with: class
tagged with: scope
has comment: http://stackoverflow.com/comment/90890535
tagged with: python
tagged with: dictionary
has answer: http://stackoverflow.com/a/51969775
has title: python OOP class method retaining variable. Weird scoping thing
downvote count: 0
score: 2
type: AnsweredQuestion
tagged with: oop

http://stackoverflow.com/q/51971463
has title: Vectorized way to arrange vector into matrix (numpy)
has comment: http://stackoverflow.com/comment/90893735
has answer: http://stackoverflow.com/a/51971624
possible better answer: http://stackoverflow.com/a/51971624
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90893630
has answer: http://stackoverflow.com/a/51971655
type: Question
tagged with: numpy
score: 0
answer count: 2
has body: I have 4 vectors of the same dimentions (say 3) a= [1, 5, 9] b= [2, 6, 10] c= [3, 7, 11] d= [4, 8, 12] What i want to do with numpy is to create a matrix of dimensions 3x2x2 that has this structure so the resultan matrices will be like this [ [[1, 2],[3,4]], [[5, 6],[7,8]], [[9, 10],[11,12]], ] I know that it is pretty easy using a for loop but I'm looking for a vectorized approach. Thanks in advance
accepted answer: http://stackoverflow.com/a/51971655
tagged with: python

http://stackoverflow.com/q/51985455
favorite count: 0
tagged with: python
has title: Checking discord command parameters
downvote count: 1
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51986744
has comment: http://stackoverflow.com/comment/90920398
type: Question
tagged with: discord.py
has answer: http://stackoverflow.com/a/51986744
has comment: http://stackoverflow.com/comment/90920311
score: 0
upvote count: 1
has body: I dont have much to say, im trying to make an bot for discord using python. The command is when I do +permissions &lt;user&gt; It shows a list of the user's permissions Heres the problem: So, the permission im starting with is "Administrator" And depending if the user has the permission it shows an unique message saying if he has the permission or not As you see in here if ctx.message.user.server_permissions.administrator == True: embed.add_field(name="Administrator", value=":white_ckeck_mark: Permission Granted!", inline=True) if ctx.message.user.server_permissions.administrator == False: embed.add_field(name="Administrator", value=":x: Permission Denied!", inline=True) But it shows the error saying that I didnt inputed an argument (user) ALL CODE @bot.command(pass_context=True) async def permissions(ctx, user: discord.Member): embed = discord.Embed(name="USER_PERMISSIONS", description="------------------------------------------------------", color=0x0099ff) embed.set_author(name="USER_PERMISSIONS: {}'s Permissions".format(user.name)) if ctx.message.user.server_permissions.administrator == True: embed.add_field(name="Administrator", value=":white_ckeck_mark: Permission Granted!", inline=True) if ctx.message.user.server_permissions.administrator == False: embed.add_field(name="Administrator", value=":x: Permission Denied!", inline=True) if ctx.message.user.server_permissions.view_audit_logs == True: embed.add_field(name="View Audit Logs", value=":white_ckeck_mark: Permission Granted!", inline=True) if ctx.message.user.server_permissions.view_audit_logs == False: embed.add_field(name="View Audit Logs", value=":x: Permission Denied!", inline=True) embed.set_thumbnail(url=user.avatar_url) embed.set_footer(text="Requested by {}".format(author), icon_url=author.avatar_url) await bot.say(embed=embed)
answer count: 1
has comment: http://stackoverflow.com/comment/90920875

http://stackoverflow.com/q/52098283
tagged with: pandas
has title: getting top n entries for each group, where n is different for each group
downvote count: 0
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/52098324
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/52098324
score: 1
upvote count: 1
has body: imagine having this df: group time index cutoff A 2018-04-01 05:07:00 0.8 2 A 2018-04-01 05:07:00 0.7 2 A 2018-04-01 05:07:00 0.6 2 B 2018-04-01 05:57:00 0.9 4 B 2018-04-01 05:57:00 0.87 4 B 2018-04-01 05:57:00 0.7 4 B 2018-04-01 05:57:00 0.67 4 B 2018-04-01 05:57:00 0.5 4 B 2018-04-01 05:57:00 0.47 4 I would want to change this df into: group time index cutoff A 2018-04-01 05:07:00 0.8 2 A 2018-04-01 05:07:00 0.7 2 B 2018-04-01 05:57:00 0.9 4 B 2018-04-01 05:57:00 0.87 4 B 2018-04-01 05:57:00 0.7 4 B 2018-04-01 05:57:00 0.67 4 That means for each grouping (group, time), order by index and only select top n entries, where n is equal to the cutoff value specified in 'cutoff' for each group. Any help is appreciated. Thanks in advance!
type: Question
tagged with: dataframe

http://stackoverflow.com/q/51961233
has answer: http://stackoverflow.com/a/66925056
has title: How to print whole sparse matrix?
downvote count: 0
linked to: http://stackoverflow.com/q/22961541
has answer: http://stackoverflow.com/a/76973860
favorite count: 0
has answer: http://stackoverflow.com/a/51961305
answer count: 3
has body: I want to print the whole matrix. When I print X it tells me location where values are stored expcept zeros. Can I print whole matrix including zeros? X = sparse.csr_matrix(1./2.*np.array([[0.,1.],[1.,0.]])) print(X)
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/106452898
tagged with: python
upvote count: 7
score: 7
tagged with: scipy
type: Question

http://stackoverflow.com/q/52082123
has comment: http://stackoverflow.com/comment/91114865
has comment: http://stackoverflow.com/comment/91146030
has title: This code of python is working very slow?
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/91128301
has answer: http://stackoverflow.com/a/75282973
has comment: http://stackoverflow.com/comment/91153526
has comment: http://stackoverflow.com/comment/91120947
answer count: 1
has comment: http://stackoverflow.com/comment/91149839
has comment: http://stackoverflow.com/comment/91153464
has comment: http://stackoverflow.com/comment/91128072
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91151736
tagged with: python
linked to: http://stackoverflow.com/q/46642992
has comment: http://stackoverflow.com/comment/91148985
tagged with: screenshot
linked to: http://stackoverflow.com/q/50324736
score: 0
tagged with: selenium
type: Question
has body: I am trying to get the screenshot of the below URLs through the use of selenium but when I run this code it runs very very very slow. The most amazing thing is it sometimes runs normal but most of the times it runs very slow. so I need a help. I just print the screenshots and URL into the HTML file. So don't Confuse. waybackurls401 = {} waybackurls403 = {} webarchive_urls403 = [] webarchive_urls403.append('https://web.archive.org/web/2012062112352/http://xx.com/') webarchive_urls403.append('https://web.archive.org/web/2012062112352/http://xx2.com/') print "\t[~]Findind of 403 staruscode urls\n" GEckodriver = 'F:/geckodriver.exe' firefox_options = Options() firefox_options .add_argument("-headless") driver = webdriver.Firefox(executable_path=GEckodriver, firefox_options = firefox_options ) for x in webarchive_urls403: try: print "\t", x driver.get(x) driver.set_page_load_timeout(6) imgfilename = x.split('web')[-1] newfile= imgfilename.replace('/', '.') +'.png' driver.get_screenshot_as_file(newfile) value = " ".format(newfile, x) key = " {0} URL ".format(x, newfile, x) waybackurls403[key] = value except TimeoutException as ex: print "Can't take screenshot because. Timeout." driver.quit() EDIT:- According to the Kiril comment, I made some change to see where it actually stops. for x in webarchive_urls403: print time.time()-start try: print "\t", x print 'test122' driver.get(x) print 'test1' driver.set_page_load_timeout(10) imgfilename = x.split('web')[-1] newfile= imgfilename.replace('/', '.') +'.png' driver.get_screenshot_as_file(newfile) print 'test2' value = " ".format(newfile, x) key = " {0} URL ".format(x, newfile, x) waybackurls403[key] = value print 'test3' except TimeoutException as ex: print ex driver.quit() Now as you can see I provide some random prints for ex. print test122 to see where it actually stuck. And I found that I can print test122 but not print test1 after the driver.get() set it means the code is stuck after the driver.get() Now that's the whole…
has comment: http://stackoverflow.com/comment/91792168

http://stackoverflow.com/a/52052421
type: Answer
has body: Maybe the tasks file is not visible from the path you are executing it. try: python.exe -m celery worker.celery --app=nsi -P eventlet -f celery.logs -l info
score: 2
has comment: http://stackoverflow.com/comment/91253396
has comment: http://stackoverflow.com/comment/91057300
has comment: http://stackoverflow.com/comment/108363217
downvote count: 0
upvote count: 2
answers question: http://stackoverflow.com/q/52042942

http://stackoverflow.com/comment/91047479
has text: You should just need to create a programmer instance since it is extending user, and either user **keyword *args or copy the argument signature from User in Programmer constructor to populate the properties Programmer is inheriting
comment on: http://stackoverflow.com/q/52048296
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91119790
score: 0
has text: ... I would appreciate it if the people closevoting this question as "too broad" would explain why they think so. It seems like a sensibly scoped question to me!
type: Comment
comment on: http://stackoverflow.com/q/52079835
type: QuestionComment

http://stackoverflow.com/a/52067942
has body: Up through gensim 3.6.0, the loss value reported may not be very sensible, only resetting the tally each call to train(), rather than each internal epoch. There are some fixes forthcoming in this issue: https://github.com/RaRe-Technologies/gensim/pull/2135 In the meantime, the difference between the previous value, and the latest, may be more meaningful. In that case, your data suggest the 1st epoch had a total loss of 745896, while the last had (9676936-9280568=) 396,368 – which may indicate the kind of progress hoped-for.
has comment: http://stackoverflow.com/comment/92204821
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/91119289
has comment: http://stackoverflow.com/comment/94672622
score: 6
has comment: http://stackoverflow.com/comment/92216219
type: Answer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52038651
has comment: http://stackoverflow.com/comment/91119309
answers question: http://stackoverflow.com/q/52038651
has comment: http://stackoverflow.com/comment/91097502
upvote count: 6
has comment: http://stackoverflow.com/comment/91119234

http://stackoverflow.com/a/52020208
type: Answer
score: 2
answers question: http://stackoverflow.com/q/52020194
has body: The for-loop: for s in (n): Expects n to be some sort of iterable: a list, tuple, dictionary, etc, but you are passing an integer (int) - hence the error. If you want s to take the values 0, 1, 2, ..., n then you should use the range() function to produce an iterable sequence of the numbers up to the number passed into it. Therefore, what your probably want is: for s in range(n): which will allow you to work with an integer variable s in that code block. If you want to debug your code, it often helps to print out the values of variables to check they are evaluating to what you think they should be. For instance, for i in range(4): print(i) gives: 0 1 2 3 which is to be expected.
accepted answer of: http://stackoverflow.com/q/52020194
type: AcceptedAnswer
downvote count: 0
upvote count: 2

http://stackoverflow.com/q/52015279
tagged with: binary-tree
has answer: http://stackoverflow.com/a/52018392
score: 0
answer count: 2
has comment: http://stackoverflow.com/comment/90980888
tagged with: variable-assignment
favorite count: 0
type: UnansweredQuestion
has body: There are two solution for a problem: Problem is : Enter the root node of a binary tree and an integer to print out the path where the sum of the node values in the binary tree is the input integer. A path is defined as a path from the root node of the tree to the next node until the leaf node passes. (Note: In the list of return values, the array with the largest array length is ahead) solution one # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def FindPath(self, root, expectNumber): if not root: return [] result=[] path=[root] path_sum=0 def find(root,path,path_sum): isleaf= root.left==None and root.right==None # a bool,whether is leaf node path_sum+=root.val if isleaf and path_sum==expectNumber: t=[] for i in path: t.append(i.val) result.append(t) # add a appropriate path's value to result if path_sum&lt;expectNumber: if root.left: find(root.left,path+[root.left],path_sum)#note!!!!! if root.right: find(root.right,path+[root.right],path_sum)#note!!!!! find(root,path,path_sum) return result solution 2 class Solution: def FindPath(self, root, expectNumber): if not root: return [] result=[] path=[] path_sum=0 def find(root,path,path_sum): isleaf= root.left==None and root.right==None path.append(root)#note!!!!! path_sum+=root.val if isleaf and path_sum==expectNumber: t=[] for i in path: t.append(i.val) result.append(t) if path_sum&lt;expectNumber: if root.left: find(root.left,path,path_sum) if root.right: find(root.right,path,path_sum) path.pop()#note!!!!! find(root,path,path_sum) return result I don't know why in solution 1 the path list don't need pop operation but solution 2 need. In other word why solution 1 don't share a path list, but solution 2 does. Please help me, I cann't find such paper figure me out! My point is not about class , you can use function to solve this problem too. What I care is Python variable value assignment in recursion!!!
tagged with: python
has comment: http://stackoverflow.com/comment/90980975
tagged with: recursion
has comment: http://stackoverflow.com/comment/90980987
has title: Python variable value assignment in recursion
upvote count: 1
downvote count: 1
type: Question
has answer: http://stackoverflow.com/a/52015667
tagged with: variables

http://stackoverflow.com/q/52030403
favorite count: 0
downvote count: 3
tagged with: python
type: AnsweredQuestion
has title: Python sort none ignore (or stable)
type: Question
tagged with: nonetype
score: -2
has body: I have lists whose items are either numbers or None. I want to sort them, so that the None items stay at the same place, while the numerical values get sorted. For example, I want this list: [None, None, 20, None, 10] to be sorted into: [None, None, 10, None, 20] and this one: [None, 50, 20, None, None] into: [None, 20, 50, None, None]
tagged with: sorting
upvote count: 1
answer count: 1
has answer: http://stackoverflow.com/a/52030450
accepted answer: http://stackoverflow.com/a/52030450

http://stackoverflow.com/a/52015620
type: AcceptedAnswer
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/102599327
answers question: http://stackoverflow.com/q/51979312
score: 1
upvote count: 1
accepted answer of: http://stackoverflow.com/q/51979312
has body: You have something very bizarre in your migration: models.IntegerField(default=builtins.id) This is referring to the builtin id function, which requires an argument because it returns the internal ID of an object in Python. It has nothing to do with database IDs, and doesn't belong here at all. I can only guess that you were asked for a default when creating the migration and you just typed in id. You should delete that default from the migration, but that may make it unable to execute. You could also try a default of 0, which makes sense there; but your actual models code shows that field as the primary key, so you presumably have another subsequent migration that changes the field again; and 0 wouldn't work as a pk. If you're still in development and don't have any data you need to keep, I would suggest deleting your database and migrations completely and starting again with makemigrations.
has comment: http://stackoverflow.com/comment/90996639

http://stackoverflow.com/a/52074632
has body: Translating my previous answer from C++ to python and modifying the position of the text I show how to add a footer. from PyQt5 import QtCore, QtGui, QtWidgets, QtPrintSupport textMargins = 12 borderMargins = 10 def mmToPixels(printer, mm): return mm * 0.039370147 * printer.resolution() def paintPage(pageNumber, pageCount, painter, doc, textRect, footerHeight): painter.save() textPageRect = QtCore.QRectF(QtCore.QPointF(0, pageNumber*doc.pageSize().height()), doc.pageSize()) painter.setClipRect(textRect) painter.translate(0, -textPageRect.top()) painter.translate(textRect.left(), textRect.top()) doc.drawContents(painter) painter.restore() footerRect = QtCore.QRectF(textRect) footerRect.setTop(textRect.bottom()) footerRect.setHeight(footerHeight) # draw footer painter.save() pen = painter.pen() pen.setColor(QtCore.Qt.blue) painter.setPen(pen) painter.drawText(footerRect, QtCore.Qt.AlignCenter, "Page {} of {}".format(pageNumber+1, pageCount)) painter.restore() def printDocument(printer, doc): painter = QtGui.QPainter(printer) doc.documentLayout().setPaintDevice(printer) doc.setPageSize(QtCore.QSizeF(printer.pageRect().size())) pageSize = printer.pageRect().size() tm = mmToPixels(printer, textMargins) footerHeight = painter.fontMetrics().height() textRect = QtCore.QRectF(tm, tm, pageSize.width() - 2 * tm, pageSize.height() - 2 * tm - footerHeight) doc.setPageSize(textRect.size()) pageCount = doc.pageCount() for pageIndex in range(pageCount): if pageIndex != 0: printer.newPage() paintPage(pageIndex, pageCount, painter, doc, textRect, footerHeight) if __name__ == '__main__': import sys app = QtWidgets.QApplication(sys.argv) document = QtGui.QTextDocument() cursor = QtGui.QTextCursor(document) blockFormat = QtGui.QTextBlockFormat() for i in range(10): cursor.insertBlock(blockFormat) cursor.insertHtml(" This is the {} page ".format(i+1)) blockFormat.setPageBreakPolicy(QtGui.QTextFormat.PageBreak_AlwaysBefore) printer = QtPrintSupport.QPrinter(QtPrintSupport.QPrinter.HighRes…
type: Answer
accepted answer of: http://stackoverflow.com/q/52073747
score: 2
has comment: http://stackoverflow.com/comment/91150673
answers question: http://stackoverflow.com/q/52073747
upvote count: 2
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/52025073
has answer: http://stackoverflow.com/a/52088907
possible better answer: http://stackoverflow.com/a/52025617
downvote count: 0
has answer: http://stackoverflow.com/a/52025617
favorite count: 0
tagged with: process-pool
accepted answer: http://stackoverflow.com/a/52088907
score: 3
tagged with: python
type: AnsweredQuestion
upvote count: 3
has body: I have a class A that when initiated changes a mutable class attribute nums. when initiating the class via a Process pool with maxtasksperchild= 1, I notice that nums has the values of several different processes. which is an undesirable behavior for me. my questions are: are the processes sharing memory ? am i not understanding maxtasksperchild and the workings of a Process pool correctly ? EDIT: I am guessing that that the pool pickles the previous processes it started (and not the original one) and thus saving the values of nums, is that correct? and if so, how can i force it to use the original process? here is an example code: from multiprocessing import Pool class A: nums = [] def __init__(self, num=None): self.__class__.nums.append(num) # I use 'self.__class__' for the sake of explicitly print(self.__class__.nums) assert len(self.__class__.nums) &lt; 2 # checking that they don't share memory if __name__ == '__main__': with Pool(maxtasksperchild=1) as pool: pool.map(A, range(99)) # the assert is being raised EDIT because of answer by k.wahome: using instance attributes doesn't answer my question I need to use class attributes because in my original code (not shown here) i have several instances per process. my question is specifically about the workings of a multiprocessing pool. btw, doing the following does work from multiprocessing import Process if __name__ == '__main__': prs = [] for i in range(99): pr = Process(target=A, args=[i]) pr.start() prs.append(pr) [pr.join() for pr in prs] # the assert was not raised
tagged with: multiprocessing
type: Question
has title: class attributes and memory shared between Processes in process pool?
tagged with: python-multiprocessing
answer count: 2

http://stackoverflow.com/comment/91115521
comment on: http://stackoverflow.com/a/52082160
type: AnswerComment
score: 0
type: Comment
has text: Yes, I realize now what you were attempting in the original post, I think you were very close, hopefully this gets you what you need

http://stackoverflow.com/comment/90940061
type: AnswerComment
score: 0
has text: My fault, the data isn't all digits. There are both digits and text.
type: Comment
comment on: http://stackoverflow.com/a/51994671

http://stackoverflow.com/q/52087527
tagged with: pyqt
has comment: http://stackoverflow.com/comment/91125850
score: 0
has answer: http://stackoverflow.com/a/52325795
has title: PyQt5 callback of different name being invoked on valueChanged
answer count: 1
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/91125860
tagged with: pyqt5
has body: I want more than one callback available to an object, but defining any subsequent callback in an object overwrites all previous callbacks. However, the callbacks are decorated, which seems to be messing with things. How should I define object-level callbacks, so I can use self in them? In the following example, which you can run on any computer with Python 3.x and PyQt5.11.x, a spinbox is hooked up to two valueChanged callbacks. These are called A and C. However, the second callback C never triggers, and a third callback D triggers instead. D should not trigger. The callbacks print their letters and the spinbox value, so the expected output when spinning the spinbox is: got A 1 got C 1 However, the actual output is: got A 1 got D 1 This is wrong because the spinbox is hooked up to callbackA self.callbackC I do not know why D is being called, since I don't actually reference it anywhere. However, if we remove any of the decorators from C or D they work again. What am I doing wrong? The code in question is: from PyQt5 import QtWidgets from PyQt5.QtCore import pyqtSlot def silenceCallbacks(*elements): """Silence events for the duration of a callback. Mostly skipped for this reproduction.""" def silenceCallbacksOf(callback): def silencedCallback(self, *args, **kwargs): callback(self, *args, **kwargs) return silencedCallback return silenceCallbacksOf @pyqtSlot(int) @silenceCallbacks() def callbackA(px: int): #correctly called print('got A', px) @pyqtSlot(int) #this overwrites the last three functions @silenceCallbacks() def callbackB(px: int): #correctly not called print('got B', px) class RecordingSettings(QtWidgets.QDialog): @pyqtSlot(int) @silenceCallbacks() def callbackC(self, px: int): #incorrectly not called print('got C', px) @pyqtSlot(int) #this overwrites the previous pyqtSlot-decorated function @silenceCallbacks() def callbackD(self, px: int): #incorrectly called print('got D', px) def __init__(self, window): super().__init__() spin = QtWidgets.QSpinBox() spin.…
type: Question
has comment: http://stackoverflow.com/comment/91125466

http://stackoverflow.com/a/52035175
upvote count: 1
has comment: http://stackoverflow.com/comment/91022122
has comment: http://stackoverflow.com/comment/91027582
score: 1
answers question: http://stackoverflow.com/q/52034930
downvote count: 0
type: Answer
has body: you can write commands on windows command processor to do these functions : -Merge PDF files together, or split them apart -Encrypt and decrypt -Scale, crop and rotate pages -Read and set document info and metadata -Copy, add or remove bookmarks -Stamp logos, text, dates, page numbers -Add or remove attachments -Losslessly compress PDF files it can work also in different OS such as / MAC / Ubunto / Linux scale command example : cpdf -scale-to-fit a3portrait in.pdf -o out.pdf using this tool Coherent PDF Command Line Tools , you may download it from here click here to open link you can as well use python script to execute the code for you on the command processor / terminals . hope my post helped you , good luck
has comment: http://stackoverflow.com/comment/91027366
has comment: http://stackoverflow.com/comment/91027246

http://stackoverflow.com/comment/90980589
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52011058
type: AnswerComment
has text: The chrome was opened but after I close the window (after alot of time without any response but the error massage) I get this exception, your answer doesn't help me at all, but thanks for the try.

http://stackoverflow.com/q/52044633
score: 0
answer count: 2
tagged with: beautifulsoup
type: UnansweredQuestion
tagged with: python
has body: I'm trying to work with BeautifulSoup for tag in soup.find_all('td', attrs= {'class': "txtd hidden-phone mobile-f12 stack-mobile"}): print(tag) And the output is 16P54KtKHTgkc9d4UQFZf81iv99z41mCsn 13ApArvHxx1ATNZ3AtMbvi7AB3MbT1nns9 UPD: print(tag.text) gives me a full text but with no spaces, how do I split it?
has title: BeautifulSoup - find_all .text
has comment: http://stackoverflow.com/comment/91040671
has comment: http://stackoverflow.com/comment/91040578
has answer: http://stackoverflow.com/a/52044676
type: Question
has answer: http://stackoverflow.com/a/52044945

http://stackoverflow.com/comment/91187790
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52102642
has text: Thank you, Oluwafemi, it's working. Please create answer.

http://stackoverflow.com/comment/91003866
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52026789
has text: Possible duplicate of [Reading a file without newlines](https://stackoverflow.com/questions/12330522/reading-a-file-without-newlines)
score: 1

http://stackoverflow.com/comment/91003121
type: Comment
type: QuestionComment
score: 0
has text: @charlietfl okay thankyou, do i use javascript to send it to the server? or can html do that?
comment on: http://stackoverflow.com/q/52026423

http://stackoverflow.com/comment/90997976
score: 0
type: AnswerComment
type: Comment
has text: node.eval() with tf.InteractiveSession() or print(sess.run(node)) when a session is passed will print the result of any operation including the loss function that you mentioned in your code. It seems that you have some other problems in your code. If you want help, first you should post the entire code, and second, do not post test-code and questions regarding test-code and upon receiving an answer say "I really want [something else...]".
comment on: http://stackoverflow.com/a/52023169

http://stackoverflow.com/comment/90972190
type: QuestionComment
comment on: http://stackoverflow.com/q/52010127
has text: Try `tifffile.imsave('complex.tif', complex_numpy_array)`.
score: 0
type: Comment

http://stackoverflow.com/a/52017083
accepted answer of: http://stackoverflow.com/q/52016751
downvote count: 0
answers question: http://stackoverflow.com/q/52016751
score: 1
has comment: http://stackoverflow.com/comment/90984515
upvote count: 1
type: AcceptedAnswer
has body: You may use the following pattern: (\()([a-zA-Z])\S+ ?(?:([a-zA-Z])\S+)?(\)) (\() First capturing group. Match and capture a ). ([a-zA-Z]) Match and capture letter. \S+ ? Any non whitespace characters, followed by optional whitespace. (?:([a-zA-Z])\S+)? Non capturing group. Match and capture letters, then match any non whitespace. The non capturing group is optional. (\)) Match and capture a ). Replacing with: \1___\4\U\2\3. You can try the regex here. For input strings: (hello world) The (Frontal Lobe) is a part of the (brain) The output is: (___)HW The (___)FL is a part of the (___)B
has comment: http://stackoverflow.com/comment/90985516
type: Answer

http://stackoverflow.com/comment/91006938
type: QuestionComment
has text: what if sum of your list less than total rows?
comment on: http://stackoverflow.com/q/52028288
score: 0
type: Comment

http://stackoverflow.com/q/51987320
answer count: 1
downvote count: 0
score: 1
favorite count: 0
has title: Pass variables from .py to .kv file
tagged with: python
tagged with: kivy
type: AnsweredQuestion
tagged with: kivy-language
has answer: http://stackoverflow.com/a/51988390
upvote count: 1
type: Question
accepted answer: http://stackoverflow.com/a/51988390
has body: I am trying to use variables from python file to .kv file so I searched similar questions and found out the way use Property and coded like this: # in python file class Test2App(App): abcd = StringProperty('test') def build(self): return presentation # in kv file &lt;MyButton@Button&gt;: text: "contents (%s)"%(app.abcd) background_color: (255, 255, 255,1)` and an error comes up. AttributeError: 'NoneType' object has no attribute 'bind' File "/usr/local/lib/python2.7/dist-packages/kivy/lang/builder.py", line 249, in create_handler return eval(value, idmap), bound_list File "/root/Desktop/hi/t2.kv", line 61, in &lt;module&gt; text: "contents (%s)"%(app.abcd) File "/usr/local/lib/python2.7/dist-packages/kivy/lang/parser.py", line 75, in __getattribute__ object.__getattribute__(self, '_ensure_app')() File "/usr/local/lib/python2.7/dist-packages/kivy/lang/parser.py", line 70, in _ensure_app app.bind(on_stop=lambda instance: File "/usr/local/lib/python2.7/dist-packages/kivy/lang/builder.py", line 615, in _apply_rule rctx['ids']) File "/usr/local/lib/python2.7/dist-packages/kivy/lang/builder.py", line 254, in create_handler cause=tb) t2.py #-*- coding: utf-8 -*- __version__ = "1.0" import kivy import os kivy.require('1.10.0') from kivy.app import App from kivy.lang import Builder from kivy.uix.button import Button from kivy.uix.screenmanager import ScreenManager, Screen from kivy.uix.boxlayout import BoxLayout from kivy.uix.gridlayout import GridLayout from kivy.uix.image import Image from kivy.uix.label import Label from kivy.animation import Animation from kivy.clock import Clock from kivy.properties import StringProperty #from kivy.config import Config #windows size fixed #Config.set('graphics', 'resizable', 0) from kivy.core.window import Window Window.size = (540, 960) #Window.size = (1080, 1920) ##########FOR BUS INFORMATION UPDATE############# from urllib import urlencode, quote_plus from urllib2 import Request as RQ from urllib2 import urlopen as UO import urllib i…

http://stackoverflow.com/q/51962316
type: UnansweredQuestion
tagged with: python
linked to: http://stackoverflow.com/q/20109391
has comment: http://stackoverflow.com/comment/90875205
type: Question
has title: [Python][Pandas] Efficiently crossing and comparing the values in columns of two groupby
has comment: http://stackoverflow.com/comment/90949736
score: 0
has body: I am currently trying to cross the data of two dataframes (df and marche_type_jointure) about bus journeys grouped by certain columns (in english: stop, direction, type of day, season, year) as the code here shows: df_grouped = df.groupby(['arret', 'sens', 'type_jour','saison', 'annee']) marche_type_jointure_grouped = marche_type_jointure.groupby(['arret', 'sens', 'type_jour','saison', 'annee']) Which gives me the following dataframes with the following relevant columns (see screenshots df_variables_1, df_variables_2, marche_type_variables) and you can use the following dataframes as examples (only the most important variables as you can see): df_jointure = pd.DataFrame([ ['Aller','VIG01A' , time(7,21,28),'vac_s' ,'hiver' ,1978 , 'NaN' ], ['Aller','VIG01A' , time(18,7,35),'vac_s' ,'hiver' ,1978 , 'NaN' ], ['Aller','LYC30R' , time(7,21,54),'vac_s' ,'hiver' ,1978 , 'NaN' ], ['Aller','LYC30R' , time(14,43,42),'vac_s' ,'hiver' ,1978 , 'NaN' ] ], columns=['sens', 'arret', 'heure_arrivee_reelle', 'type_jour', 'saison', 'annee', 'temps_trajet_mt']) marche_type_jointure = df = pd.DataFrame([ ['VIG01A', time(6,0,0), time(6,29,0), 'hiver', 'Aller', 4, 'vac_s', 1978], ['VIG01A', time(7,0,0), time(7,29,0), 'hiver', 'Aller', 4, 'vac_s', 1978], ['VIG01A', time(7,0,0), time(7,59,0), 'hiver', 'Aller', 4, 'vac_s', 1978], ['VIG01A', time(18,30,0), time(18,59,0), 'hiver', 'Aller', 4, 'vac_s', 1978], ['LYC30R', time(6,0,0), time(6,29,0), 'hiver', 'Aller', 1, 'semaine', 1978], ['LYC30R', time(7,45,0), time(7,59,0), 'hiver', 'Aller', 1, 'semaine', 1978], ['LYC30R', time(9,30,0), time(15,59,00), 'hiver', 'Aller', 1, 'semaine', 1978]], columns=['arret', 'heure_debut_periode', 'heure_fin_periode', 'saison', 'sens', 'temps_trajet_sur_periode', 'type_jour', 'annee]) Here are also the most important variables: in df : 'sens' (column 6), 'arret' (stop, column 9), 'heure_arrivee_reelle' (actual time of arrival (of the bus), column 13), 'type_jour' (type of day, with 'vac_s' which means holidays,…
tagged with: pandas-groupby
tagged with: pandas
has comment: http://stackoverflow.com/comment/90949354
answer count: 0

http://stackoverflow.com/q/52039799
has body: I have this folder: sa that has folders a,b,c. These folders have folders: PST and DBOUND. If for example folder b has empty pst folder and existing dbounds, the following code should NOT append contents from that folder at all and skip it. code: import geopandas as gpd from glob import glob ps=[] db=[] for i in glob(r'C:\Users\user\Desktop\sa' + '**/*/*/*', recursive=True): if i.endswith('PST.shp'): ps.append(i) if i.endswith('DBOUND.shp'): db.append(i) How to make it not append from a folder, if their subfolder has either PST or DBOUND folders empty? and append only from folders that have all the needed subfolders there? Explanation To help you understand: If all the folders a and b are ok it returns this: C:\Users\user\Desktop\sa\a\DBOUND\DBOUND.shp C:\Users\user\Desktop\sa\a\PST\PST.shp C:\Users\user\Desktop\sa\b\DBOUND\DBOUND.shp C:\Users\user\Desktop\sa\b\PST\PST.shp If c has empty either PST or DBOUND folders, it should not appear at all in the list. It should skip the folder and not append it.
type: Question
linked to: http://stackoverflow.com/q/49284015
downvote count: 0
has title: Append to a list only if all files exist in a folder?
has comment: http://stackoverflow.com/comment/91030491
linked to: http://stackoverflow.com/q/25675352
has comment: http://stackoverflow.com/comment/91030316
tagged with: exception
has comment: http://stackoverflow.com/comment/91030611
favorite count: 0
has comment: http://stackoverflow.com/comment/91030564
has comment: http://stackoverflow.com/comment/91030311
type: UnansweredQuestion
upvote count: 1
tagged with: python
answer count: 0
score: 1

kinect
type: Tag
tag name: kinect
tags question: http://stackoverflow.com/q/52004739

http://stackoverflow.com/comment/91018582
has text: No, you can't. You are complicating stuff. It's better to learn pandas and python properly before going to this stuff
type: Comment
score: 0
comment on: http://stackoverflow.com/a/52033668
type: AnswerComment

http://stackoverflow.com/q/51989966
has title: Why is scipy's entropy function returning a value greater than 1?
has comment: http://stackoverflow.com/comment/90932022
tagged with: python
type: AnsweredQuestion
has body: Scipy's entropy function calculates the Kullback–Leibler divergence using base e as the default. According to wikipedia, the KL divergence cannot be greater than one when using base e. I found a case where scipy's entropy function returns a value greater than one. This confused me because I thought that the KL divergence should always return a value less than one when using base e. Am I not actually calculating the KL-divergence with scipy's entropy function? Can the KL-divergence using base e return a value greater than one? import numpy as np from scipy.stats import entropy a = np.array([9.99998036e-101, 9.99998036e-101, 9.99998036e-101, 9.99998036e-101, 9.99998036e-101, 9.99998036e-101, 9.99998036e-101, 9.99998036e-101, 9.99998036e-101, 9.99998036e-101, 9.99998036e-101, 9.99998036e-101, 2.10191815e-311, 1.40899754e-289, 1.51339868e-268, 2.60462468e-248, 7.18266540e-229, 3.17376526e-210, 2.24704957e-192, 2.54917227e-175, 4.63376925e-159, 1.34964112e-143, 6.29869946e-129, 4.71012196e-115, 5.64367638e-102, 1.08352949e-089, 3.33325126e-078, 1.64302455e-067, 1.29768336e-057, 1.64226070e-048, 3.33015272e-040, 1.08201899e-032, 5.63318870e-026, 4.69918344e-020, 6.28115023e-015, 1.34525510e-010, 4.61656331e-007, 2.53852607e-004, 2.23662484e-002, 3.15757258e-001, 7.14269696e-001, 2.58892691e-001, 1.50357826e-002, 1.39920378e-004, 2.08633761e-007, 5.10231155e-011, 1.00634451e-008, 1.38362196e-005, 3.08403844e-003, 1.15059177e-001, 7.94326422e-001, 1.23289276e+000, 4.70067360e-001, 3.73297736e-002, 5.22437696e-004, 1.20375305e-006, 4.47599703e-010, 2.67171382e-014, 2.55648664e-019, 3.92010948e-025, 9.63196683e-032, 1.60547392e-031, 6.16530117e-025, 3.79363060e-019, 3.74033228e-014, 5.90944148e-010, 1.49663225e-006, 6.08796110e-004, 4.02164040e-002, 4.57222409e-001, 1.12643499e+000, 8.52135681e-001, 1.72454239e-001, 9.30417906e-002, 5.59827871e-001, 5.79409118e-001, 1.03846717e-001, 1.84731916e-001, 6.84387807e-001, 4.11946755e-001, 3.97315469e-002, 6.14184915e-004, 1.2169483…
tagged with: scipy
type: Question
has answer: http://stackoverflow.com/a/52009591
accepted answer: http://stackoverflow.com/a/52009591
has comment: http://stackoverflow.com/comment/90930146
tagged with: statistics
score: 0
tagged with: metrics
answer count: 1

vpython
tags question: http://stackoverflow.com/q/51973396
tag name: vpython
type: Tag
tags question: http://stackoverflow.com/q/52037267
tags question: http://stackoverflow.com/q/51991414

http://stackoverflow.com/a/52021597
accepted answer of: http://stackoverflow.com/q/52021254
type: Answer
has comment: http://stackoverflow.com/comment/90993796
has body: When you use multiprocessing, everything you pass to a worker has to be pickled. Unfortunately, many BeautifulSoup trees can't be pickled. There are a few different reasons for this. Some of them are bugs that have since been fixed, so you could try making sure you have the latest bs4 version, and some are specific to different parsers or tree builders… but there's a good chance nothing like this will help. But the fundamental problem is that many elements in the tree contain references to the rest of the tree. Occasionally, this leads to an actual infinite loop, because the circular references are too indirect for its circular reference detection. But that's usually a bug that gets fixed. But, even more importantly, even when the loop isn't infinite, it can still drag in more than 1000 elements from all over the rest of the tree, and that's already enough to cause a RecursionError. And I think the latter is what's happening here. If I take your code and try to pickle divList[0], it fails. (If I bump the recursion limit way up and count the frames, it needs a depth of 23080, which is way, way past the default of 1000.) But if I take that exact same div and parse it separately, it succeeds with no problem. So, one possibility is to just do sys.setrecursionlimit(25000). That will solve the problem for this exact page, but a slightly different page might need even more than that. (Plus, it's usually not a great idea to set the recursion limit that high—not so much because of the wasted memory, but because it means actual infinite recursion takes 25x as long, and 25x as much wasted resources, to detect.) Another trick is to write code that "prunes the tree", eliminating any upward links from the div before/as you pickle it. This is a great solution, except that it might be a lot of work, and requires diving into the internals of how BeautifulSoup works, which I doubt you want to do. The easiest workaround is a bit clunky, but… you can convert the soup to a string, pass …
answers question: http://stackoverflow.com/q/52021254
has comment: http://stackoverflow.com/comment/90993831
has comment: http://stackoverflow.com/comment/90993810
score: 22
upvote count: 22
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/90993751

http://stackoverflow.com/comment/91199758
type: QuestionComment
has text: Maybe it is a configuration problem of pc? Since the remote linux machine would not have it problem...
comment on: http://stackoverflow.com/q/51996906
score: 0
type: Comment

http://stackoverflow.com/a/52037858
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/91026299
has comment: http://stackoverflow.com/comment/91026835
answers question: http://stackoverflow.com/q/52036319
upvote count: 1
score: 1
has body: For the labels and bins, you can use pandas.cut. Note that you can't use a singleton as a bin in this function. Therefore you will have to create it afterwards. Here is how you can do this. First I recreate one of your dataframes: import io temp = u""" GeneID A 1 0.3 2 0.0 3 143 4 9 5 0.6""" foo = pd.read_csv(io.StringIO(temp),delim_whitespace = True) Then I create the new column and fill the NaN values with the label l1 which corresponds to the singleton [0]. foo['Exp_prof'] = pd.cut(foo.A,bins = [0,1,10,100,np.inf],labels = ['l2','l3','l4','l5']) foo['Exp_prof'] = foo['Exp_prof'].cat.add_categories(['l1']) foo['Exp_prof'] = foo['Exp_prof'].fillna('l1') And I use this new column to compute the probabilities: foo['Prob_val'] = foo.Exp_prof.map((foo.Exp_prof.value_counts()/len(foo)).to_dict()) And the output is: GeneID A Exp_prof Prob_val 0 1 0.3 l2 0.4 1 2 0.0 l1 0.2 2 3 143.0 l5 0.2 3 4 9.0 l3 0.2 4 5 0.6 l2 0.4

http://stackoverflow.com/comment/91174433
type: QuestionComment
comment on: http://stackoverflow.com/q/52111694
has text: Please clarify your specific problem or add additional details to highlight exactly what you need. As it's currently written, it’s hard to tell exactly what you're asking. See the [How to Ask](https://stackoverflow.com/help/how-to-ask) page for help clarifying this question. Also please provide what you have tried with an [MVCE](https://stackoverflow.com/help/mcve).
score: 0
type: Comment

http://stackoverflow.com/comment/90985250
type: AnswerComment
comment on: http://stackoverflow.com/a/52012510
type: Comment
score: 0
has text: Ok so I couldn't get the python script to run not as a sudo user. However, it turned out my full script needed python3 to run. For some reason, python3 does not require sudo to run (maybe because I installed python3 as my user? So I was able to remove apache from the sudo user group and run the script with python3.

http://stackoverflow.com/comment/90881896
type: Comment
has text: Thanks this works well. Thanks! I'll try and maybe get a list of choices automatically from Django - as a list of all the models so it's less typing. Thanks
comment on: http://stackoverflow.com/a/51965788
type: AnswerComment
score: 0

http://stackoverflow.com/a/52066220
upvote count: 1
type: AcceptedAnswer
has body: You just need to loop over your p_record list. Here's a simple example. p_record = [ ['Alan', 0, 0], ['Betty', 0, 0], ['Cindy', 0, 0], ] game = True while game: for player in p_record: print(player) player[1] += 1 if player[1] &gt; 3: game = False break output ['Alan', 0, 0] ['Betty', 0, 0] ['Cindy', 0, 0] ['Alan', 1, 0] ['Betty', 1, 0] ['Cindy', 1, 0] ['Alan', 2, 0] ['Betty', 2, 0] ['Cindy', 2, 0] ['Alan', 3, 0] You may also find the examples here helpful: Asking the user for input until they give a valid response.
type: Answer
accepted answer of: http://stackoverflow.com/q/52065898
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/52065898

http://stackoverflow.com/a/52082976
has body: You can use the builtin min() method. Let A = a*list1[t] and B = b*list1[t+1]. With your approach: if A + B &lt; 5000: mylist.append(A + B) else: mylist.append(5000) With min() approach: mylist.append(min((A + B), 5000))
downvote count: 0
upvote count: 6
answers question: http://stackoverflow.com/q/52082762
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/52082762
type: Answer
score: 6
has comment: http://stackoverflow.com/comment/91158588

http://stackoverflow.com/comment/91518599
has text: it worked! not fully understood why, but thank you. what if i need to find maximum absolute value? df.loc[[df.loc[df['Load'].str.contains('SLU'), 'FZ\n(kN)'].abs().idxmax()]] is correct?
comment on: http://stackoverflow.com/a/52105548
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/90957570
type: QuestionComment
type: Comment
score: 0
has text: The problem is that this flask app is used as an API only, I don't have any pages. I believe apache2 is set up correctly because the response is correct when i test it with curl targeting localhost, it returns test array. I want to point out that this is my first time hosting flask app and using apache so I might be wrong.
comment on: http://stackoverflow.com/q/52003887

http://stackoverflow.com/q/51968221
type: UnansweredQuestion
has body: Let's say I have a data frame that looks like this: df2 = pd.DataFrame(['Apple', 'orange', 'pear', 'Apple'], columns=['A']) df4 = pd.DataFrame({'Q':['chair', 'desk', 'monitor', 'chair'], 'R':['red', 'blue', 'yellow', 'purple'], 'S': ['english', 'german', 'spanish', 'english']}) df3 = pd.merge(df2, df4, left_index=True, right_index=True) df3 A Q R S 0 Apple chair red english 1 orange desk blue german 2 pear monitor yellow spanish 3 Apple chair purple english What I want to do is create an array that looks like this: df3_array_col_a = ['Apple', 'orange', 'pear', 'Apple'] df3_array_col_b = ['chair', 'desk', 'monitor', 'chair'] etc. Is there a way to do this? What I tried doing was this: df6 = df3 df6 = df6.columns.get_values() df6.tolist() But this gives me this: ['A', 'Q', 'R', 'S'] I then tried doing this: df6 = df6.A.get_values() But this gives me this: Traceback (most recent call last): File "&lt;pyshell#54&gt;", line 1, in &lt;module&gt; df6 = df6.A.get_values() AttributeError: 'numpy.ndarray' object has no attribute 'A'
type: Question
has comment: http://stackoverflow.com/comment/90886756
score: 0
tagged with: pandas
tagged with: python-3.x
duplicate of: http://stackoverflow.com/q/14822680
has title: Pandas Convert Particular columns to a list
has comment: http://stackoverflow.com/comment/90886681
tagged with: python
has comment: http://stackoverflow.com/comment/90886921
linked to: http://stackoverflow.com/q/14822680
has comment: http://stackoverflow.com/comment/90886677
has comment: http://stackoverflow.com/comment/90886886
answer count: 0

http://stackoverflow.com/comment/90976234
score: 0
comment on: http://stackoverflow.com/q/52011425
type: QuestionComment
type: Comment
has text: Below is the shell script . ( ./mtr -T -P 443 -o "LSWNBAVJMXI" --report --json --report-cycles $CYCLES $ ( ./mtr -T -P 443 -o "LSWNBAVJMXI" --report --json --report-cycles $CYCLES $ } while true; do ./mtr -T -P 443 -o "LSWNBAVJMXI" --report --json --report-cycles $CYCLES $M$ .@AndreiCioara

http://stackoverflow.com/comment/90999856
comment on: http://stackoverflow.com/q/52024026
has text: I think you forgot to use your `train_step` after `sess.run(training_init_op)`.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/52210610
accepted answer of: http://stackoverflow.com/q/52034983
has comment: http://stackoverflow.com/comment/91371025
has comment: http://stackoverflow.com/comment/91371949
answers question: http://stackoverflow.com/q/52034983
has comment: http://stackoverflow.com/comment/91372435
score: 6
has comment: http://stackoverflow.com/comment/91371677
has comment: http://stackoverflow.com/comment/91370930
type: AcceptedAnswer
downvote count: 0
has body: Although I have already mentioned part of this answer in a related answer, but let's inspect the source code step-by-step with more details to find the answer concretely. First, Let's feedforward(!): there is a call to weighted_loss function which takes y_true, y_pred, sample_weight and mask as inputs: weighted_loss = weighted_losses[i] # ... output_loss = weighted_loss(y_true, y_pred, sample_weight, mask) weighted_loss is actually an element of a list which contains all the (augmented) loss functions passed to fit method: weighted_losses = [ weighted_masked_objective(fn) for fn in loss_functions] The "augmented" word I mentioned is important here. That's because, as you can see above, the actual loss function is wrapped by another function called weighted_masked_objective which has been defined as follows: def weighted_masked_objective(fn): """Adds support for masking and sample-weighting to an objective function. It transforms an objective function `fn(y_true, y_pred)` into a sample-weighted, cost-masked objective function `fn(y_true, y_pred, weights, mask)`. # Arguments fn: The objective function to wrap, with signature `fn(y_true, y_pred)`. # Returns A function with signature `fn(y_true, y_pred, weights, mask)`. """ if fn is None: return None def weighted(y_true, y_pred, weights, mask=None): """Wrapper function. # Arguments y_true: `y_true` argument of `fn`. y_pred: `y_pred` argument of `fn`. weights: Weights tensor. mask: Mask tensor. # Returns Scalar tensor. """ # score_array has ndim &gt;= 2 score_array = fn(y_true, y_pred) if mask is not None: # Cast the mask to floatX to avoid float64 upcasting in Theano mask = K.cast(mask, K.floatx()) # mask should have the same shape as score_array score_array *= mask # the loss per batch should be proportional # to the number of unmasked samples. score_array /= K.mean(mask) # apply sample weighting if weights is not None: # reduce score_array to same ndim as weight array ndim = K.ndim(score_array) weight_ndim = K.ndim(we…
type: Answer
upvote count: 6
has comment: http://stackoverflow.com/comment/91371699

http://stackoverflow.com/a/56580871
type: Answer
answers question: http://stackoverflow.com/q/52034778
score: 1
upvote count: 1
has body: Since redis-cluster allows 10000 - 32 open connections to be made for each cluster. Now if you have 10 servers than each server cannot make more than 1000 open connection. So the issue probably for your case will be, for each server if you are having 50 workers, then the number of max connections in redis initialisation should not be more than 20. Try reducing this max connections per worker as it worked out perfectly for me. Eg: StrictRedisCluster(startup_nodes=host, decode_responses=True, loop=loop, max_connections=35) So you need to reduce this max_connections limit per worker.
downvote count: 0

http://stackoverflow.com/q/52000473
tagged with: list
score: 1
tagged with: file
type: Question
possible better answer: http://stackoverflow.com/a/52000561
upvote count: 2
has title: Replace a certain value at a certain place in a text file in Python
answer count: 3
downvote count: 1
favorite count: 0
tagged with: python-3.x
has body: I want to code something that will replace a certain value, on a certain line, in a text file (thefile.txt). I've searched for a long time a solution to my problem but didn't found it. Here is the code I wrote: clist = [1, 2, 0, 0, 0, 0] with open("thefile.txt", "w") as dataFile: for line in dataFile: (key, val1, val2 ,val3, val4, val5) = line.split() if key == clist[0]: #Find correct line line = line.replace(val1, clist[1]) #Replace the value I want, but not the others My text file look like this: 1 0 0 0 13 0 2 9 4 5 2 3 3 0 0 4 0 0 For some reason, it doesn't work. I'm still a beginner at python, so I believe the problem might be with the fact that I tried to "read" the file in write mode (line.split). I don't know if line.split for each line is considered as reading.
has answer: http://stackoverflow.com/a/52000552
accepted answer: http://stackoverflow.com/a/52000552
has answer: http://stackoverflow.com/a/52000563
tagged with: python
has answer: http://stackoverflow.com/a/52000561
type: AnsweredQuestion

http://stackoverflow.com/comment/90946753
comment on: http://stackoverflow.com/q/51998631
type: QuestionComment
has text: >>"It would result in quite a performance improvement since I don't need to serialize (and transport) them repeatedly." why and where to are you serializing and transporting them? Can't you achieve the same by just transporting/messaging the function name? << I run those functions at the "recieving" end, so no :(
score: 0
type: Comment

http://stackoverflow.com/q/52059723
answer count: 1
tagged with: python-3.x
tagged with: time
tagged with: python
has answer: http://stackoverflow.com/a/52060024
type: AnsweredQuestion
has title: Calculate difference of Row Values with 1 Minute Interval Time
type: Question
has body: I have a Dataframe like mentioned below: TIME PRCESS_NO VALUE 13:40:34 1111 10254 13:40:37 1111 25855 13:40:45 1111 10254 13:40:53 1111 10254 13:40:58 1111 68522 13:41:08 1111 10254 13:41:34 1111 10254 13:41:56 1111 25855 13:42:14 1111 10254 13:42:20 1111 10254 13:42:29 1111 68522 13:42:33 2222 68522 13:42:37 2222 25855 13:42:53 2222 10254 13:42:59 2222 10254 13:43:04 2222 25855 13:43:17 2222 10254 13:43:32 2222 10254 13:44:10 2222 68522 13:44:16 3333 68522 13:44:16 3333 25855 13:44:22 3333 25855 13:44:29 3333 68522 13:44:34 3333 68522 13:44:38 3333 10254 13:44:47 3333 10254 13:44:51 3333 10254 I want to calculate the difference of VALUE’s at every 1 Minute Interval for individual PROCESS_No. Is it possible ?
accepted answer: http://stackoverflow.com/a/52060024
score: 0
tagged with: pandas-groupby
tagged with: pandas

http://stackoverflow.com/comment/90947989
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51999037
has text: Wow, that might just enable me to use global variables!

http://stackoverflow.com/comment/91130446
type: Comment
has text: For that, it is best to use `button` tags for submitting with different values rather than a different name: ` Upload `. Then read the value of `clicked_button` in flask.
comment on: http://stackoverflow.com/q/52090187
score: 0
type: QuestionComment

http://stackoverflow.com/comment/90956228
has text: With `path('<str:query>', my_view)` and then handle the `query` value in the view function.
comment on: http://stackoverflow.com/q/52003529
score: 2
type: Comment
type: QuestionComment

http://stackoverflow.com/a/52077106
upvote count: 3
has comment: http://stackoverflow.com/comment/91105386
has comment: http://stackoverflow.com/comment/91105482
downvote count: 0
has body: This is nothing to do with numpy, consider: &gt;&gt;&gt; temp = np.linspace(1,2,11) &gt;&gt;&gt; temp array([1. , 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 1.7, 1.8, 1.9, 2. ]) &gt;&gt;&gt; # ^ look, numpy displays it fine &gt;&gt;&gt; for t in temp: ... print(t) ... 1.0 1.1 1.2 1.3 1.4 1.5 1.6 1.7000000000000002 1.8 1.9 2.0 The "issue" is with how computers represent floats in general. See: https://docs.python.org/3/tutorial/floatingpoint.html.
type: Answer
answers question: http://stackoverflow.com/q/52077048
score: 3

lxml
tags question: http://stackoverflow.com/q/52055435
tags question: http://stackoverflow.com/q/52059566
tags question: http://stackoverflow.com/q/51986817
tags question: http://stackoverflow.com/q/51981121
type: Tag
tags question: http://stackoverflow.com/q/51973998
tags question: http://stackoverflow.com/q/52101476
tags question: http://stackoverflow.com/q/52102257
tags question: http://stackoverflow.com/q/52056548
tag name: lxml
tags question: http://stackoverflow.com/q/51966541

http://stackoverflow.com/a/52046775
score: 4
has body: Well, I can confirm that this happens also in Ubuntu 18.04, pandas 0.23.4, matplotlib 2.2.3 with TkAgg backend. I am not sure, if this is a bug or a feature, but you can emulate the expected behavior: from matplotlib import pyplot as plt import pandas as pd #create your sample data df = pd.DataFrame({ 'Time': [0, 5, 10, 15, 20, 25], 'Capomulin': [45.0, 44.26608641544399, 43.08429058188399, 42.06431734681251, 40.71632532212173, 39.93952782686818], 'Infubinol': [45.0, 47.062001033088, 49.40390857087143, 51.29639655633334, 53.19769093422999, 55.71525236228889], 'Ketapril': [45.0, 47.38917452114348, 49.582268974622714, 52.39997374321578, 54.92093473734737, 57.678981717731574], 'Placebo': [45.0, 47.125589188437495, 49.42332947868749, 51.35974169802999, 54.36441702681052, 57.48257374394706]}) df.set_index('Time', inplace=True) errors = pd.DataFrame({ 'Time': [0, 5, 10, 15, 20, 25], 'Capomulin': [0.0, 0.44859285020103756, 0.7026843745238932, 0.8386172472985688, 0.9097306924832056, 0.8816421535181787], 'Infubinol': [0.0, 0.23510230430767506, 0.2823459146215716, 0.35770500497539054, 0.4762095134790833, 0.5503145721542003], 'Ketapril': [0.0, 0.26481852016728674, 0.35742125637213723, 0.5802679659678779, 0.7264838239834724, 0.7554127528910378], 'Placebo': [0.0, 0.21809078325219497, 0.40206380730509245, 0.6144614435805993, 0.8396091719248746, 1.0348719877946384]}) errors.set_index('Time', inplace=True) #plot error bars ax = df.plot(figsize=(12,8), yerr = errors, legend = False) #reset color cycle so that the marker colors match ax.set_prop_cycle(None) #plot the markers df.plot(figsize=(12,8), style=['^-', 'o--', 'x-.', 'D-'], markersize=14, ax = ax) plt.show() Sample output:
upvote count: 4
type: AcceptedAnswer
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/52035184
answers question: http://stackoverflow.com/q/52035184

http://stackoverflow.com/a/51976908
answers question: http://stackoverflow.com/q/51975996
has body: Every time the script click one page number in the loop, the page changed and selenium treat it as new page. So those page numbers found on the page before click are invalid on new page. To fix you problem, simple way is to find page numbers on new page again in each iteration of the loop. count = 1 next_page_string = "javascript:__doPostBack('ctl00$MainContent$grdResults','Page$" + str(count) + "')" td_page_number_list = driver.find_elements_by_xpath( "//*[@id='MainContent_grdResults']/tbody/tr[22]/td/table/tbody/tr/td/a") for x in td_page_number_list: if x.get_attribute("href") == next_page_string: driver.execute_script("__doPostBack('ctl00$MainContent$grdResults','Page$" + str(count) + "')") // find page numbers on new page again after click // i think you need to add some wait before find again // like: time.sleep(5) or using selenium wait api td_page_number_list = driver.find_elements_by_xpath( "//*[@id='MainContent_grdResults']/tbody/tr[22]/td/table/tbody/tr/td/a")
score: 0
type: Answer

http://stackoverflow.com/a/54617942
type: Answer
score: 2
upvote count: 2
downvote count: 0
has body: To those who might still want to see the difference between recursive and iterative function. iterative def iterative_sum(n): result = 1 for i in range(2,n+1): result *= i return result print(iterative_sum(5)) iteration is when a loop repeatedly executes until the controlling condition becomes false recursive def recursive_sum(n): if n == 1: return 1 else: return n * recursive_sum(n-1) print(recursive_sum(5)) recursive function is when a function calls itself This link explains it much better https://techdifferences.com/difference-between-recursion-and-iteration-2.html
answers question: http://stackoverflow.com/q/51994148

http://stackoverflow.com/a/53523116
answers question: http://stackoverflow.com/q/51994295
score: 0
type: Answer
has body: I using sklearn_crfsuite estimator crf = sklearn_crfsuite.CRF( algorithm='lbfgs', c1=0.1, c2=0.1, max_iterations=2, all_possible_transitions=True ) I'm saving the model as described below: model = 'model.joblib' joblib.dump(crf, model) and when I try to deploy the model it reports this error: ERROR: (gcloud.alpha.ml-engine.versions.create) Bad model detected with error: "Failed to load model: Could not load the model: /tmp/model/0001/model.joblib. No module named sklearn_crfsuite.estimator. (Error code: 0)" deploy model: gcloud alpha ml-engine versions create v1 --model teste --origin $ORI --python-version 2.7 --runtime-version 1.8 --framework scikit-learn

http://stackoverflow.com/comment/91069708
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52059567
has text: @GaryHoliday I do not know. Something like `with open('giantfile.json') as fd: json.load(fd)`

http://stackoverflow.com/q/51977659
answer count: 0
type: UnansweredQuestion
has title: Pyinstaller .py to .exe with Sklearn classifier
type: Question
has comment: http://stackoverflow.com/comment/90940106
has comment: http://stackoverflow.com/comment/90926223
linked to: http://stackoverflow.com/q/35533803
has comment: http://stackoverflow.com/comment/90919460
has body: I've been trying to convert a .py file to a .exe file for 2 days now with no luck. I've gotten the farthest with pyinstaller but went I launch the .exe it closes (import errors). In the warning file it has errors such as missing module named _scproxy - imported by urllib.request If you need the entire list I can give it to you but it's over 300 lines. I've tried the following with pyinstaller with no luck Creating a single file exe Creating a single directory exe Removing all path altering code Creating a exe with the noupx option Putting just the files I need in a directory and creating it (I had other related files that I thought it might be messing up on) I am using the following Windows 7 pro Python 3.6 Anaconda 5.2.0 VS code (is this relevant?) My .py file basically runs a pre-made sklearn classifier. The classifier for the .py is in the same directory exported and imported using pickle (file name is clf.pickle). Any help would be appreciated and if you need more info please ask. Thanks.
linked to: http://stackoverflow.com/q/41570359
score: 0
tagged with: importerror
tagged with: pyinstaller
tagged with: python
has comment: http://stackoverflow.com/comment/90905450

http://stackoverflow.com/a/52073111
type: Answer
score: 10
has body: Use SeriesGroupBy.value_counts and select first value of index: df = df.groupby('col1')['col2'].apply(lambda x: x.value_counts().index[0]).reset_index() print (df) col1 col2 0 blue nb 1 green gx Or add DataFrame.drop_duplicates: df = df.groupby('col1')['col2'].value_counts().reset_index(name='v') df = df.drop_duplicates('col1')'col1','col2' print (df) col1 col2 0 blue nb 2 green gx Or use Series.mode and select first value by positions by Series.iat: df = df.groupby('col1')['col2'].apply(lambda x: x.mode().iat[0]).reset_index() print (df) col1 col2 0 blue nb 1 green gx EDIT: Problem is with only NaNs groups: d = {'col1': ['green','green','green','blue','blue','blue'], 'col2': [np.nan,np.nan,np.nan,'nb','nb','mj']} df = pd.DataFrame(data=d) f = lambda x: np.nan if x.isnull().all() else x.value_counts().index[0] #or #f = lambda x: next(iter(x.value_counts().index), np.nan) #another solution #f = lambda x: next(iter(x.mode()), np.nan) df = df.groupby('col1')['col2'].apply(f).reset_index() print (df) col1 col2 0 blue nb 1 green NaN
upvote count: 10
has comment: http://stackoverflow.com/comment/91096671
accepted answer of: http://stackoverflow.com/q/52073054
answers question: http://stackoverflow.com/q/52073054
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/91096442
has comment: http://stackoverflow.com/comment/91096515

http://stackoverflow.com/comment/90900141
comment on: http://stackoverflow.com/q/51974524
type: Comment
type: QuestionComment
score: 1
has text: `np.dot` is optimized for pairs of 2d arrays. So a repeated application of `dot` like this might well be the fastest. Mathematically I don't think there's a way of expressing this as some sort of 'parallel' 3d operation. I think there is some sort of 'chained dot' function, but at best it chooses an optimal order in which to do the individual products.

http://stackoverflow.com/comment/91096634
has text: Why do you check `if (x[i]-x_el[i]) == 0:`? You're turning off the error bar there.
comment on: http://stackoverflow.com/q/52072770
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/68968228
type: Answer
answers question: http://stackoverflow.com/q/51986517
has body: Regarding to the error faced by Sachin Ingle, (-2147352567, 'Exception occurred.', (0, 'Microsoft Excel', 'That name is already taken. Try a different one.', 'xlmain11.chm', 0, -2146827284), None) facing this error It's probably because you have created a file of same name before. Try create it with different name. The answer by Parfait on new_wb.SaveAs(Filename='MasterMerge.xlsx', FileFormat=xlWorkbookDefault) will make the file named "MasterMerge.xlsx" and probably you have created the file already. And btw can add in xlapp.Quit() at finally: block to solve the in-use problem I done some changes on Parfait answer (Thanks mate) def merge_excel_files(filepath_list,filename,delete_original_files=False): import os, errno import win32com.client as win32 try: # INITIALIZE EXCEL COM APP xlapp = win32.gencache.EnsureDispatch('Excel.Application') # ASSIGN CONSTANTS xlPasteValues = -4163; lPasteFormats = -4122; xlWorkbookDefault = 51 # CREATE NEW WOKRBOOK (PROMPTS IF EXISTS) new_wb = xlapp.Workbooks.Add() new_wb.SaveAs(Filename=filename, FileFormat=xlWorkbookDefault) # Gain filename in a directory # xl_files = [f for f in os.listdir(path) if f.endswith('.xls') or f.endswith('.xlsx')] for wb in filepath_list: xlwb = xlapp.Workbooks.Open(wb) # LOOP THROUGH EVERY WORKSHEET, COPYING TO NEW WORKSHEET for xlsh in xlwb.Worksheets: new_sh = new_wb.Worksheets.Add() new_sh.Name = xlsh.Name new_wb.Save() new_sh.Move(After=new_wb.Worksheets(new_wb.Worksheets.Count)) xlsh.Cells.Copy(new_sh.Cells) new_sh = None xlwb.Close(False) xlwb = None # REMOVNIG DEFAULT SHEET AND LAUNCHING TO SCREEN new_wb.Worksheets('Sheet1').Delete() new_wb.Save() # xlapp.Visible = True except Exception as e: print(e) finally: # Close the Excel file since done writing xlapp.Quit() # RELEASE RESOURCES xlsh = None; new_sh = None; xlwb = None; new_wb = None; xlapp = None # Delete the initial file if delete_original_files: for count,x in enumerate(filepath_list): print(f"Deleting the {count+1}/{len(filepath_list)} or…
score: 0

http://stackoverflow.com/comment/96191866
comment on: http://stackoverflow.com/a/52098091
type: AnswerComment
has text: The command `conda install -c conda-forge vs2015_runtime=14` does not work as of Feb 2019. The error is: PackagesNotFoundError: The following packages are not available from current channels: - vs2015_runtime=14
score: 2
type: Comment

http://stackoverflow.com/comment/138359593
has text: Great suggestion - I've updated my original answer to use your code!
comment on: http://stackoverflow.com/a/78300407
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/52020982
tagged with: python
linked to: http://stackoverflow.com/q/37252756
duplicate of: http://stackoverflow.com/q/37252756
has body: I have written a simple code of python GUI for sleeping my code for 10 seconds. At the same time, the GUI should run without freezing. Is not possible by defining primari thready and secondary thread? While I click on "Run" button pythonw.exe has stopped working. Does anyone have any thoughts on how I may be able to troubleshoot this? Thank you. import sys, threading from PyQt4 import QtGui, QtCore from PyQt4.QtCore import pyqtSlot from PyQt4.QtGui import * class Window(QtGui.QMainWindow): def __init__(self): super(Window,self).__init__() self.setGeometry(400,150, 550, 500) self.setWindowTitle("my first program") self.home() def home(self): self.button_1 = QtGui.QPushButton('Run', self) self.button_1.resize(60,25) self.button_1.move(230,230) self.button_1.clicked.connect(self.Thread_test) self.textbox_1 = QTextEdit(self) self.textbox_1.move(15,290) self.textbox_1.resize(510,170) self.show() def Thread_test(self): t = threading.Thread(target=self.calculation) t.start() def calculation(self): msg="program is working" self.textbox_1.setText(msg) time.sleep(5) msg="program was slept for few sec." self.textbox_1.setText(msg) def run(): app=QtGui.QApplication(sys.argv) GUI=Window() sys.exit(app.exec_()) run()
type: Question
tagged with: pyqt4
has title: How to use Threading in Python pyqt4 GUI design
has answer: http://stackoverflow.com/a/52021257
score: 0
answer count: 1
type: UnansweredQuestion
tagged with: multithreading

http://stackoverflow.com/q/52030866
tagged with: python
upvote count: 6
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52038702
has answer: http://stackoverflow.com/a/52035987
has comment: http://stackoverflow.com/comment/91013125
tagged with: scipy
downvote count: 1
type: Question
score: 5
has answer: http://stackoverflow.com/a/52030910
has body: I am fitting a set of experimental data (sample) within two different experimental regions and can be expressed with two mathematical functions as follows: 1st region: y = m*x + c ( the slope can be constrained to zero) 2nd region: y = d*exp(-k*x) the experimental data is shown below and I coded it in python as follows: def func(x, m, c, d, k): return m*x+ c + d*np.exp(-k*x) popt, pcov = curve_fit(func, t, y) Unfortunately, my data is not fitting properly and fitted (returned) parameters do not make sense (see picture below). Any assistance will be appreciated.
answer count: 3
possible better answer: http://stackoverflow.com/a/52030910
accepted answer: http://stackoverflow.com/a/52035987
has comment: http://stackoverflow.com/comment/91012299
has comment: http://stackoverflow.com/comment/91012283
favorite count: 0
has title: Fitting of experimental data within two different regions
tagged with: curve-fitting

http://stackoverflow.com/q/52052961
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/39190250
tagged with: subprocess
tagged with: pipe
score: 0
type: Question
has title: Setting up a pipeline using subprocess.Popen: Why close stdout but not stdin?
answer count: 1
has answer: http://stackoverflow.com/a/52052962
linked to: http://stackoverflow.com/q/27796317
has body: The Python 3 documentation for subprocess.popen (1) presents the following sample code for pipelines: from subprocess import Popen, PIPE p1 = Popen(["dmesg"], stdout=PIPE) p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE) p1.stdout.close() # Allow p1 to receive a SIGPIPE if p2 exits. output = p2.communicate()[0] The p1.stdout.close() call after starting the p2 is important in order for p1 to receive a SIGPIPE if p2 exits before p1. Why is this necessary? Previous questions (Replacing Shell Pipeline, Under what condition does a Python subprocess get a SIGPIPE?, Explain example from python subprocess module) have answers stating that p1.stdout has multiple readers, which must all be closed to prevent p1's output pipe from closing. What is the relation between p2.stdin and p1.stdout, and do I have to close p2.stdin?
linked to: http://stackoverflow.com/q/6046779
accepted answer: http://stackoverflow.com/a/52052962
tagged with: python

http://stackoverflow.com/comment/91084845
type: Comment
has text: If `c = [1, 2]`, then `c[1] - c[0]` will be `1` (`2-1`). Is that what you're asking?
comment on: http://stackoverflow.com/q/52067222
score: 0
type: QuestionComment

http://stackoverflow.com/a/52015675
type: AcceptedAnswer
downvote count: 0
type: Answer
has body: You have two index levels, and you can get them either by name or by integer index. The index level at integer index 0 has name proj, a string. The index level at integer index 1 has name 0, an integer. When you call get_level_values(level), pandas searches the index level by name first. So in your situation, calling get_level_values(0) resolves to the second level with the name 0 and get_level_values(1) resolves to the same level, but in this case by integer index 1.
answers question: http://stackoverflow.com/q/52015282
score: 3
accepted answer of: http://stackoverflow.com/q/52015282
upvote count: 3
has comment: http://stackoverflow.com/comment/90985989

http://stackoverflow.com/a/52085345
has comment: http://stackoverflow.com/comment/91121106
type: Answer
has comment: http://stackoverflow.com/comment/91120963
has body: I'll help with the part I think you're stuck on, which is trying to extract the units from the category. Given your data, your best bet may be to use regex, the following should work: import re f = open('data.csv') # I assume the first row has the header you listed in your question header = f.readline().split(',') #since you said its a csv for item in header: print re.search(r'\(.+\)', item).group() print re.sub(r'\(.+\)', '', item) That should print the following for you: (ft/s) Velocity (Mgal/d) Volumetric (klb/d) Mass Flow (ft/s) Sound Speed You can modify the above to store these in a list, then iterate through them to find duplicates and merge the appropriate strings to dictionaries or whatnot.
score: 0
answers question: http://stackoverflow.com/q/52084976

http://stackoverflow.com/comment/90998029
type: Comment
has text: Got the same error
score: 0
comment on: http://stackoverflow.com/q/52023371
type: QuestionComment

http://stackoverflow.com/q/52063802
has answer: http://stackoverflow.com/a/52064034
answer count: 3
has answer: http://stackoverflow.com/a/52064009
accepted answer: http://stackoverflow.com/a/52064012
has comment: http://stackoverflow.com/comment/91078219
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91078265
type: Question
has answer: http://stackoverflow.com/a/52064012
has comment: http://stackoverflow.com/comment/91078309
has title: Python program taking two integer inputs to find even and odd
has comment: http://stackoverflow.com/comment/91077989
has comment: http://stackoverflow.com/comment/91078057
possible better answer: http://stackoverflow.com/a/52064034
has body: Here is the code. When I enter an even number (1st number) say 4 and odd number (2nd number) say 5 it prints '4 and 5 are even' num_1=int(input('first number ')) num_2=int(input('second number ')) if num_1%2==0 &amp; num_2%2==0: print(num_1,'and',num_2,'are even') elif num_1%2!=0 &amp; num_2%2!=0: print(num_1,'and',num_2,'are odd') elif num_1%2!=0 &amp; num_2%2==0: print(num_1,'is odd and ',num_2,'is even') elif num_1%2==0 &amp; num_2%2!=0: print(num_1,'is even',num_2,'is odd') else: print('invalid entry')
score: 0

http://stackoverflow.com/q/52038651
answer count: 2
possible better answer: http://stackoverflow.com/a/59399826
has body: What can cause loss from model.get_latest_training_loss() increase on each epoch? Code, used for training: class EpochSaver(CallbackAny2Vec): '''Callback to save model after each epoch and show training parameters ''' def __init__(self, savedir): self.savedir = savedir self.epoch = 0 os.makedirs(self.savedir, exist_ok=True) def on_epoch_end(self, model): savepath = os.path.join(self.savedir, "model_neg{}_epoch.gz".format(self.epoch)) model.save(savepath) print( "Epoch saved: {}".format(self.epoch + 1), "Start next epoch ... ", sep="\n" ) if os.path.isfile(os.path.join(self.savedir, "model_neg{}_epoch.gz".format(self.epoch - 1))): print("Previous model deleted ") os.remove(os.path.join(self.savedir, "model_neg{}_epoch.gz".format(self.epoch - 1))) self.epoch += 1 print("Model loss:", model.get_latest_training_loss()) def train(): ### Initialize model ### print("Start training Word2Vec model") workers = multiprocessing.cpu_count()/2 model = Word2Vec( DocIter(), size=300, alpha=0.03, min_alpha=0.00025, iter=20, min_count=10, hs=0, negative=10, workers=workers, window=10, callbacks=[EpochSaver("./checkpoints")], compute_loss=True ) Output: Losses from epochs (1 to 20): Model loss: 745896.8125 Model loss: 1403872.0 Model loss: 2022238.875 Model loss: 2552509.0 Model loss: 3065454.0 Model loss: 3549122.0 Model loss: 4096209.75 Model loss: 4615430.0 Model loss: 5103492.5 Model loss: 5570137.5 Model loss: 5955891.0 Model loss: 6395258.0 Model loss: 6845765.0 Model loss: 7260698.5 Model loss: 7712688.0 Model loss: 8144109.5 Model loss: 8542560.0 Model loss: 8903244.0 Model loss: 9280568.0 Model loss: 9676936.0 What am I doing wrong? Language arabian. As input from DocIter - list with tokens.
accepted answer: http://stackoverflow.com/a/52067942
has answer: http://stackoverflow.com/a/59399826
favorite count: 0
has comment: http://stackoverflow.com/comment/91070434
tagged with: word2vec
tagged with: python
tagged with: gensim
score: 8
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52067942
downvote count: 1
type: Question
upvote count: 9
tagged with: loss
has title: Loss does not decrease during training (Word2Vec, Gensim)

http://stackoverflow.com/a/52017898
downvote count: 0
has comment: http://stackoverflow.com/comment/90990647
answers question: http://stackoverflow.com/q/52017864
type: Answer
has comment: http://stackoverflow.com/comment/90989804
score: 2
upvote count: 2
has body: Use list or dict for a variable number of variables. In this case, you can use a dictionary comprehension, with dictionary keys aligned with the power: from numpy.linalg import matrix_power np.random.seed(0) n = 2 A = np.random.random((n, n)) def make_arrays(arr, k): return {i: matrix_power(arr, i) for i in range(1, k+1)} res = make_arrays(A, 4) Result: {1: array([[0.5488135 , 0.71518937], [0.60276338, 0.54488318]]), 2: array([[0.73228622, 0.78220024], [0.65924031, 0.72798764]]), 3: array([[0.87337022, 0.94993107], [0.80060427, 0.86814988]]), 4: array([[1.05190103, 1.14222656], [0.96267139, 1.04562393]])}
accepted answer of: http://stackoverflow.com/q/52017864
has comment: http://stackoverflow.com/comment/90990616
type: AcceptedAnswer

http://stackoverflow.com/q/52060438
tagged with: conv-neural-network
upvote count: 1
has comment: http://stackoverflow.com/comment/91198097
tagged with: tensorflow
tagged with: neural-network
type: UnansweredQuestion
has body: I have a large .npz numpy training file that I want to read more efficiently. I tried to follow the approach from Tensorflow documentation (https://www.tensorflow.org/guide/datasets#consuming_numpy_arrays): As an alternative, you can define the Dataset in terms of tf.placeholder() tensors, and feed the NumPy arrays when you initialize an Iterator over the dataset. However after implementing iterator, my model consumes even 2x more memory. Do you have any clues what might be wrong here? def model(batch_size): x = tf.placeholder(tf.float32,[None, IMGSIZE,IMGSIZE,1]) y = tf.placeholder(tf.float32,[None, n_landmark * 2]) z = tf.placeholder(tf.int32, [None, ]) Ret_dict['x'] = x Ret_dict['y'] = y Ret_dict['z'] = z Ret_dict['iterator'] = iter_ dataset = tf.data.Dataset.from_tensor_slices((x, y, z)).batch(batch_size) iter_ = dataset.make_initializable_iterator() InputImage, GroundTruth, GroundTruth_Em = iter_.get_next() Conv1a = tf.layers.conv2d(InputImage,64,3,1,..) (...) def main(): trainSet = np.load(args.datasetDir) Xtrain = trainSet['Image'] Ytrain = trainSet['Label_1'] Ytrain_em = trainSet['Label_2'] with tf.Session() as sess: my_model = model(BATCH_SIZE) Saver = tf.train.Saver() Saver.restore(sess, args.pretrainedModel) sess.run( [model['Optimizer'], model['iterator'].initializer], feed_dict={model['x']:Xtrain, model['y']:Ytrain, model['z']:Ytrain_em})
tagged with: deep-learning
answer count: 0
downvote count: 0
has comment: http://stackoverflow.com/comment/91292011
score: 1
favorite count: 0
type: Question
tagged with: python
has title: Efficient way to load .npz with Tensorflow iterator
has comment: http://stackoverflow.com/comment/91226045

intersection
tags question: http://stackoverflow.com/q/52077412
type: Tag
tags question: http://stackoverflow.com/q/52079704
tag name: intersection
tags question: http://stackoverflow.com/q/52104310
tags question: http://stackoverflow.com/q/52048314
tags question: http://stackoverflow.com/q/52073609

http://stackoverflow.com/comment/91164446
comment on: http://stackoverflow.com/a/52093523
score: 0
type: Comment
has text: Can you try the wheel files on here? If it works I will update the answer. [wheel](https://www.lfd.uci.edu/~gohlke/pythonlibs/#tensorflow) @KilluaSan. Can you share the code you are trying to run too?
type: AnswerComment

http://stackoverflow.com/a/52047122
answers question: http://stackoverflow.com/q/52046551
accepted answer of: http://stackoverflow.com/q/52046551
type: Answer
score: 2
downvote count: 0
has body: There are several options: 1. convert to QWidget The simplest option for you is to convert the QQuickPaintedItem to QWidget and thus you avoid learning to use QML which is not a simple task for a beginner. For this, some changes must be made: use the update() method in the setters: @SOME_PROPERTY.setter def SOME_PROPERTY(self, type): ... self.SOME_PROPERTYChanged.emit() self.update() # <---- change the paint() method to paintEvent() and create the QPainter since paintEvent() does not provide any. def paintEvent(self, event): painter = QtGui.QPainter(self) painter.save() ... Finally, QWidget does not have the setWidth() or setHeight() method, you must use the resize() method. Using all the above you must create a .py file called radialbar.py. radialbar.py from PyQt5 import QtCore, QtGui, QtWidgets class RadialBar(QtWidgets.QWidget): class DialType(): FullDial = 0 MinToMax = 1 NoDial = 2 sizeChanged = QtCore.pyqtSignal() startAngleChanged = QtCore.pyqtSignal() spanAngleChanged = QtCore.pyqtSignal() minValueChanged = QtCore.pyqtSignal() maxValueChanged = QtCore.pyqtSignal() valueChanged = QtCore.pyqtSignal() dialWidthChanged = QtCore.pyqtSignal() backgroundColorChanged = QtCore.pyqtSignal() foregroundColorChanged = QtCore.pyqtSignal() progressColorChanged = QtCore.pyqtSignal() textColorChanged = QtCore.pyqtSignal() suffixTextChanged = QtCore.pyqtSignal() showTextChanged = QtCore.pyqtSignal() penStyleChanged = QtCore.pyqtSignal() dialTypeChanged = QtCore.pyqtSignal() textFontChanged = QtCore.pyqtSignal() def __init__(self, parent=None): super(RadialBar, self).__init__(parent) self.resize(200, 200) # self.setSmooth(True) # self.setAntialiasing(True) self._Size = 200 self._StartAngle = 40 self._SpanAngle = 280 self._MinValue = 0 self._MaxValue = 100 self._Value = 50 self._DialWidth = 15 self._BackgroundColor = QtCore.Qt.transparent self._DialColor = QtGui.QColor(80,80,80) self._ProgressColor = QtGui.QColor(135,26,5) self._TextColor = QtGui.QColor(0, 0, 0) self._SuffixText…
upvote count: 2
type: AcceptedAnswer

http://stackoverflow.com/a/52054591
answers question: http://stackoverflow.com/q/52054135
score: 0
type: Answer
has body: If you're using Windows. You need to install Python x64(64bit) version from here. Once that's done you need to start command line (Windows + R) enter cmd. In that cmd type pip install tensorflow. Then you can restart your shell and test it with import tensorflow If you're on Ubuntu(Linux) then pip3 install tensorflow will do the job.

http://stackoverflow.com/comment/90897189
comment on: http://stackoverflow.com/q/51973319
has text: So… what's a girl to do? Ignore the message, or install an older PyQt5?
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/91070491
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52039126
has text: are you using python 2 or 3?
score: 0

http://stackoverflow.com/comment/90936047
score: 0
type: QuestionComment
type: Comment
has text: I'll try both Solutions, thanks to you guys
comment on: http://stackoverflow.com/q/51993114

http://stackoverflow.com/q/51958143
has body: Imagine we have a sorted list with size P. How can we choose N indices for which the values reflect the range of the list more smoothly. For example if our list is: List=[0,0,0,0,0,0,0,0,0,0.1,0.1,0.9,0.91,0.91,0.92,0.99,0.99,0.99] Then how we choose let's say 5 indices that somehow shows the full range of the list? In this example it would be something like : indices=[0,9,11,14,15] The final indices list doesn't have to be exactly like the one I wrote here though
favorite count: 0
has comment: http://stackoverflow.com/comment/90866765
has comment: http://stackoverflow.com/comment/90867957
type: UnansweredQuestion
downvote count: 2
has comment: http://stackoverflow.com/comment/90867508
tagged with: python
has comment: http://stackoverflow.com/comment/90866768
tagged with: list
has comment: http://stackoverflow.com/comment/90866826
type: Question
has title: Choosing N changing points in a sorted list
upvote count: 0
score: -2
answer count: 1
has comment: http://stackoverflow.com/comment/90866795
has answer: http://stackoverflow.com/a/51958321

http://stackoverflow.com/q/52028794
has comment: http://stackoverflow.com/comment/91008048
type: Question
has comment: http://stackoverflow.com/comment/91007950
has title: set all neighboring array items equal to 1 if adjacent to nonzero value
has comment: http://stackoverflow.com/comment/91038730
score: 0
answer count: 1
has body: I am looking for an efficient way to set all array indexes neighboring a non-zero value equal to 1. So for example, if I have an array called arr that looks like the following: import numpy as np arr = np.zeros((5,5)) arr[1,1] = arr[2,2] = arr[3,3] = arr[0,5] = 1 arr # array([[ 0., 0., 0., 0., 0.], # [ 0., 1., 0., 0., 0.], # [ 0., 0., 1., 0., 0.], # [ 0., 0., 0., 1., 0.], # [ 1., 0., 0., 0., 0.]]) Is there an easy way to get array called arr2 that keeps all non-zero values, but also sets left/right and up/down neighbors to non-zero values equal to 1? So in this small reproducible example, I would like a result that looks like: arr2 # array([[ 0., 1., 0., 0., 0.], # [ 1., 1., 1., 0., 0.], # [ 0., 1., 1., 1., 0.], # [ 1., 0., 1., 1., 1.], # [ 1., 1., 0., 1., 0.]]) Diagonal neighbors aren't considered.
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/52043844

http://stackoverflow.com/comment/91100568
type: Comment
comment on: http://stackoverflow.com/a/52074839
has text: Sorry I have no time to continue so I won't be able to answer on further questions. Just a few hints: try first with 2 files, then 3 files, and once it works, use `import glob` `for f in glob.glob('*.wav'):`, it will loop on all sound files in the folder. Search SackOverflow questions about looping on files with Python for further help. Best of luck for your project! You can "accept" this answer with the tick mark if it helped ;)
score: 0
type: AnswerComment

http://stackoverflow.com/comment/91166413
type: Comment
score: 1
has text: Indeed, this is part of the [Python DB API](https://www.python.org/dev/peps/pep-0249) which most libraries try to follow.
type: AnswerComment
comment on: http://stackoverflow.com/a/52107602

http://stackoverflow.com/comment/90927953
score: 0
type: Comment
comment on: http://stackoverflow.com/q/51989052
type: QuestionComment
has text: @Dan Can you show us your code?

http://stackoverflow.com/q/52024173
accepted answer: http://stackoverflow.com/a/52024193
favorite count: 0
has title: filling a column values with max value in pandas
tagged with: python
type: AnsweredQuestion
upvote count: 5
has answer: http://stackoverflow.com/a/52024193
type: Question
possible better answer: http://stackoverflow.com/a/52024237
answer count: 2
score: 5
has answer: http://stackoverflow.com/a/52024237
downvote count: 0
has body: I have some data like this: pd.DataFrame({'code': ['a', 'a', 'a', 'b', 'b', 'c'], 'value': [1,2,3, 4, 2, 1] }) +-------+------+-------+ | index | code | value | +-------+------+-------+ | 0 | a | 1 | +-------+------+-------+ | 1 | a | 2 | +-------+------+-------+ | 2 | a | 3 | +-------+------+-------+ | 3 | b | 4 | +-------+------+-------+ | 4 | b | 2 | +-------+------+-------+ | 5 | c | 1 | +-------+------+-------+ i want add a column that contain the max value of each code : | index | code | value | max | |-------|------|-------|-----| | 0 | a | 1 | 3 | | 1 | a | 2 | 3 | | 2 | a | 3 | 3 | | 3 | b | 4 | 4 | | 4 | b | 2 | 4 | | 5 | c | 1 | 1 | is there any way to do this with pandas?
tagged with: pandas

http://stackoverflow.com/comment/90926701
type: Comment
has text: Yours was my first thought, but particularly with '0.9.0' there are a lot of nifty shortcuts that seaborn provides
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51988487

http://stackoverflow.com/a/52026436
type: AcceptedAnswer
downvote count: 0
has body: The defaultdict class implements a object.__reduce__() method where the second element of the returned tuple (the arguments for the constructor) is always going to be the factory object: &gt;&gt;&gt; d = NestedDict() &gt;&gt;&gt; d.__reduce__() (&lt;class '__main__.NestedDict'&gt;, (&lt;class '__main__.NestedDict'&gt;,), None, None, &lt;dict_itemiterator object at 0x110df59a8&gt;) That argument is then passed to the NestedDict() call to re-build the object. The exception is thrown because the NestedDict class doesn’t accept an argument. You can override the __reduce__ method in your subclass: class NestedDict(defaultdict): def __init__(self): super().__init__(self.__class__) def __reduce__(self): return (type(self), (), None, None, iter(self.items())) The above produces the exact same elements defaultdict.__reduce__() returns, except that the second element is now an empty tuple. You could also just accept and ignore a single argument: class NestedDict(defaultdict): def __init__(self, _=None): # accept a factory and ignore it super().__init__(self.__class__) The _ name is commonly used to mean I am ignoring this value. An alternative implementation could just subclass dict and provide a custom __missing__ method; this method is called for keys not in the dictionary: class NestedDict(dict): def __missing__(self, key): nested = self[key] = type(self)() return nested def __repr__(self): return f'{type(self).__name__}({super().__repr__()})' This works exactly like your version, but doesn't need additional pickle support methods: &gt;&gt;&gt; d = NestedDict() &gt;&gt;&gt; d['foo'] NestedDict({}) &gt;&gt;&gt; d['foo']['bar'] NestedDict({}) &gt;&gt;&gt; d NestedDict({'foo': NestedDict({'bar': NestedDict({})})}) &gt;&gt;&gt; pickle.loads(pickle.dumps(d)) NestedDict({'foo': NestedDict({'bar': NestedDict({})})})
accepted answer of: http://stackoverflow.com/q/51991503
type: Answer
answers question: http://stackoverflow.com/q/51991503
upvote count: 2
score: 2

http://stackoverflow.com/comment/90970315
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52009518
type: Comment
has text: I believe the OP is trying to figure how to match whole words and not their parts.

http://stackoverflow.com/comment/90970962
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52010073
has text: This [answer](https://stackoverflow.com/a/51892084/2099607) might help you for the activation and the loss function you need to use. If you want a convolutional architecture, then obviously you need to use convolution layers like `Conv2D`. Usually a set of `Conv2D` and `MaxPooling2D` layers are used successively and at the end you might have one or a few dense layers.

http://stackoverflow.com/comment/90879781
has text: In your code, `a` is now a function that requires an argument (by the definition of `nested`). You have two options. Pass an argument to `a`, i.e. `a(99)` or redefine the function `nested` as `def nested: print(x)`
comment on: http://stackoverflow.com/q/51964872
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51977015
has body: I am continuing to have immense trouble receiving EVT_CHAR events on my custom control. After searching the internet for days, I am at a loss as to why I am not getting the events. I understand that questions pertaining to EVT_CHAR are plenty - I have read through quite a number of them, however none of the solutions provided seem to work. I have ensured the following: The custom control has focus I am binding directly on the source of the event (the custom control) My custom control has wx.WANTS_CHARS. I have tried removing it, with no perceivable difference. I have tried with and without wx.WANTS_CHARS on the frame. I have tried binding to the frame and the control, both with and without the source parameter pointing to each. There are no other keyboard-related event bindings, however I do have accelerators configured, as per the code below. I have also tried to extend upon wx.TextEntry. One possibility I was attempting to chase down is that the custom control will not receive these events as it does not appear to be a text entry control, and that the event only fires on non-readonly/editable controls. I had no luck figuring this out. Version Information: I am testing this on both Python 3.7, and most often on 3.6. wxPython version 4.0.3 Windows 10.1709 Enterprise The following is the code snippets from my frame class, responsible for constructing the GUI and listening on these events. I have also included the (currently useless) event handler for EVT_CHAR. def do_create_gui(self): classname = self.__class__.__name__ app = wx.App() AppTitle = "%s: %s" % (self._comms.port, classname) size = wx.Size(700, 450) frame = wx.Frame(None, title=AppTitle, size=size) panel = wx.Panel(frame) panelSizer = wx.BoxSizer(wx.VERTICAL) sizer = wx.BoxSizer(wx.VERTICAL) # Configure Menu fileMenu = wx.Menu() copyitem = fileMenu.Append(wx.ID_COPY, "&amp;Copy\tCtrl-C") pasteitem = fileMenu.Append(wx.ID_PASTE, "&amp;Paste\tCtrl-V") fileMenu.AppendSeparator() brkitem = fileMenu.Append(wx.I…
has comment: http://stackoverflow.com/comment/90940926
has answer: http://stackoverflow.com/a/52013024
has comment: http://stackoverflow.com/comment/91005144
tagged with: wxwidgets
score: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90927375
downvote count: 0
has title: EVT_CHAR never calls handler
tagged with: wxpython
accepted answer: http://stackoverflow.com/a/52013024
has comment: http://stackoverflow.com/comment/90962495
favorite count: 0
has answer: http://stackoverflow.com/a/51991066
type: Question
upvote count: 2
answer count: 2
tagged with: python
possible better answer: http://stackoverflow.com/a/51991066
has comment: http://stackoverflow.com/comment/91013068

http://stackoverflow.com/comment/91064768
comment on: http://stackoverflow.com/q/52056897
score: 0
has text: Yes I see that but was copy/paste mistake
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/91133758
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52081929
has text: pdb.set_trace() allow you to set a breakpoint where you want in the code, if you put it before the x / x and run it, program will stop and you will be able to inspect all variable at this point. https://docs.python.org/3/library/pdb.html#pdb.set_trace

http://stackoverflow.com/q/52097582
possible better answer: http://stackoverflow.com/a/52097863
has comment: http://stackoverflow.com/comment/91146826
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/91145735
has comment: http://stackoverflow.com/comment/91145662
downvote count: 1
has comment: http://stackoverflow.com/comment/91154140
has body: I wish to know way to make loop of function to recreate the same shape/pattern(google photo logo) with a different rotation and position and different variables such as color. Below is code that will allow me to make one of the pallets with the correct angles but ratio is not exact. Also prefer not use any goto/home function as I need repeat this drawing later. Should I have used left/right for direction instead of set heading? def photo(): speed(1) # turtle speed (debugging) #speed(0) length = 50 penup() color("#4688f4") #Blue petal begin_fill() setheading(25) forward(length/5.5) setheading(0) forward(length) setheading(227) forward(length*0.87) setheading(135) forward(length*0.8) end_fill() color("#3d6ec9") #Blue petal begin_fill() setheading(250) forward(length/5) setheading(270) forward(length/2.6) setheading(0) forward(length/1.6) end_fill() here you see the drawing from the code... Update:
favorite count: 0
has comment: http://stackoverflow.com/comment/91146922
has title: Repeating functions with python turtle
has comment: http://stackoverflow.com/comment/91176870
has comment: http://stackoverflow.com/comment/91146782
has comment: http://stackoverflow.com/comment/91145848
has answer: http://stackoverflow.com/a/52097863
tagged with: python
upvote count: 4
has comment: http://stackoverflow.com/comment/91145551
tagged with: turtle-graphics
has answer: http://stackoverflow.com/a/52103565
accepted answer: http://stackoverflow.com/a/52103565
has comment: http://stackoverflow.com/comment/91146479
type: AnsweredQuestion
score: 3

http://stackoverflow.com/q/52037095
has answer: http://stackoverflow.com/a/52039792
has body: The problem I have is I want to predict the victory of a team over another one, to do that I want to have for each match the winrate of each team before the date of the match. However using a df.groupBy("teamName").agg({"isVictory":"mean"}) provides me the global wirate of the team that is not usable because you are not supposed to know the winrate of all matches at this instant. So what I would like, is to get the winrate of the matches before this one, knowing that I have a column index in my DataFrame that keep the order of the match (i.e. if the index of a match is lower than the index of the current match it means the match has been made before, thus this match should be considered in the mean) Note that my columns are : indexMatch, nameTeam, isVictoryTeam (isVictoryTeam= if Team1 won and 0 if the Team lost ) an example of the dataset: IndexMatch isVictoryTeam team winrate 0 1 1 a NaN 1 2 0 a 1 2 3 1 a 0.5 3 4 1 a 0.6667 The winrate is the output expected. Thank you in advance for your help.
type: Question
accepted answer: http://stackoverflow.com/a/52039792
tagged with: mean
answer count: 1
downvote count: 0
tagged with: pandas
tagged with: python
has comment: http://stackoverflow.com/comment/91024444
favorite count: 0
tagged with: aggregate
has title: Pandas DataFrame: how to get column mean valuebut taking into account only the rows that have lower index than the one I want to get the mean
upvote count: 1
type: AnsweredQuestion
score: 1
tagged with: group-by

concurrency
tag name: concurrency
tags question: http://stackoverflow.com/q/52075515
type: Tag
tags question: http://stackoverflow.com/q/51996912

http://stackoverflow.com/q/51998606
favorite count: 0
has answer: http://stackoverflow.com/a/51998689
tagged with: python
accepted answer: http://stackoverflow.com/a/51998689
has comment: http://stackoverflow.com/comment/90946221
type: AnsweredQuestion
has title: apparent 'newline character' at the end of my code
score: 1
has body: I'm being told by the website I use that there is an extra newline character being printed at the end. I don't really know where abouts it is though or what is causing it. I thought it would be where I put ("Name: ") with the space, but no it's not. listo = [] name = input("Name: ") listo.append(name) while name: while name: name = input("Name: ") if name: listo.append(name) listo.sort() listo.reverse() for name in listo: print(name) Error:
has comment: http://stackoverflow.com/comment/90946341
upvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/90946282
has comment: http://stackoverflow.com/comment/90946244
has comment: http://stackoverflow.com/comment/90946375
has comment: http://stackoverflow.com/comment/90946281
has comment: http://stackoverflow.com/comment/90946439
answer count: 1
downvote count: 0

http://stackoverflow.com/comment/90944547
score: 0
comment on: http://stackoverflow.com/a/51996920
type: Comment
has text: Thanks a lot @DYZ. After hours of testing, I couldn't find that case sensitive problem. Yes, I should have added a working example, my mistake.
type: AnswerComment

http://stackoverflow.com/a/52037518
type: Answer
accepted answer of: http://stackoverflow.com/q/52037328
upvote count: 5
downvote count: 0
has body: I looked at your output. Not gcc is missing but the header files for zbar. So add extra RUN apt-get -y update &amp;&amp; apt-get install -y libzbar-dev to the Dockerfile before running pip.
score: 5
has comment: http://stackoverflow.com/comment/91026959
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/52037328

http://stackoverflow.com/a/57221457
answers question: http://stackoverflow.com/q/52094821
score: 0
has body: models.py class User(AbstractUser): first_name = models.CharField(max_length=40, blank=False) image = models.ImageField(blank=False, null=False, upload_to='image/', default='img/user.jpg') def __str__(self): return self.username '''here you can add a model and their requirements too u can set path to remember one thing that image folder will create in media folder..so don't forget to add that folder there. like if you find it helpful''' forms.py class UserRegistrationForm(forms.ModelForm): confirm_password2 = forms.CharField(widget=forms.PasswordInput,required=False) class Meta: model = User fields = ['first_name','username','password','confirm_password2','image'] def clean(self): cleaned_data = super(UserRegistrationForm, self).clean() password = cleaned_data.get("password") confirm_password2 = cleaned_data.get("confirm_password2") if password != confirm_password2: self.add_error('confirm_password2', "Password does not match") return cleaned_data '''def clean for password validation and i directly added fields which field i want in it''' views.py def Register_view(request): form = UserRegistrationForm() if request.method == 'POST': form = UserRegistrationForm(request.POST, request.FILES) if form.is_valid(): user = form.save(commit=False) password = form.cleaned_data.get("password") user.set_password(password) user.save() return redirect('login') return render(request, 'register.html', {'form': form}) ''' use request.files to add imagein your form''' register.html {% csrf_token %} {{ form.as_p }} Sign me up I already have Account ''' user multipart to add image in it'''
type: Answer
has comment: http://stackoverflow.com/comment/100947588
has comment: http://stackoverflow.com/comment/100947651

http://stackoverflow.com/comment/91154448
score: 1
comment on: http://stackoverflow.com/q/52101456
type: Comment
type: QuestionComment
has text: Cannot reproduce - I don't get an error/exception with posted code. Python 3.4.4. It does print a series of `unordered results` - multiples of seven.

http://stackoverflow.com/comment/90963212
has text: You don't need it for this case. I feel it is generally a decent Idea to activate the `atomic_requests` setting for your database backend, so that all db changes during a request causing a server error are rolled back. As the other answer points out, atomicity of a code block does not avoid race conditions, but ensures that a series of db queries is never just partially executed.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52006446
type: AnswerComment

http://stackoverflow.com/comment/91047570
has text: can you share an actual sample of your data?
comment on: http://stackoverflow.com/a/52045016
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/91158706
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52103840
has text: Cool! I vaguely recall a function with an `equal_nan` argument but not off the top of my head.

http://stackoverflow.com/comment/91118820
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52084237
has text: Thanks for that! Ill get to work on creating something like you suggested

http://stackoverflow.com/a/52095972
answers question: http://stackoverflow.com/q/52077280
type: Answer
has body: I think the better way to do this is to have a JS fils separtely. Cause a Custom field is complex and take much time than a little script. But if you won't touch JS, you can do macro in jinja 2. Is complex too use but it work well to personalize your render field.
score: 0

http://stackoverflow.com/comment/91142688
score: 3
has text: You're not using `value`. Better using `d.keys()` and iterate only on it.
comment on: http://stackoverflow.com/a/52096316
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/90959268
has text: Windows or Linux? Also @JimStewart is right.
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/51994317

http://stackoverflow.com/comment/91126527
type: QuestionComment
score: 0
has text: i finally used the scipy.sparse.csr_matrix.dot to compute instead of using x*W directly, i am afraid that it will do the operation like todense() or toarray() in the precedure. And i also used other pressure test software(Jmeter), the problem disappeared.
comment on: http://stackoverflow.com/q/52073685
type: Comment

http://stackoverflow.com/comment/91041145
type: QuestionComment
has text: filename + type are not unique in either csv, perhaps you need to use row number as the key (I am uncertain if pandas has a builtin feature that does that or if you need to add a column for that)
score: 1
comment on: http://stackoverflow.com/q/52043742
type: Comment

http://stackoverflow.com/comment/90930626
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51990397
has text: list index out of range

http://stackoverflow.com/q/52007128
tagged with: python
accepted answer: http://stackoverflow.com/a/52009363
answer count: 3
possible better answer: http://stackoverflow.com/a/52007323
score: 2
has answer: http://stackoverflow.com/a/52007323
has body: My system pip is install in /opt/.../site-packages. It is versio 1.5.6. In a new virtualenv I run pip install -U pip. I see: ...Downloading pip-18.0-py2.py3-none-any.whl (1.3MB): 1.3MB downloaded Installing collected packages: pip Found existing installation: pip 1.5.6 Not uninstalling pip at /opt/site-packages, outside environment /home/venv Successfully installed pip Cleaning up... Removing temporary dir /home/venv/build... But pip -V now still says pip 1.5.6 from /opt/.../site-packages Both pip and pip2 present in the venv/bin dir show the same. which pip points to the pip in the venv/bin path, so it looks like that pip bin is just never being updated. How do I use the new pip I just installed in my virtual environment?
downvote count: 0
has title: virtualenv pip does not upgrade
type: AnsweredQuestion
tagged with: virtualenv
has answer: http://stackoverflow.com/a/52009363
favorite count: 0
has answer: http://stackoverflow.com/a/52009472
type: Question
upvote count: 2
tagged with: pip

http://stackoverflow.com/a/54233127
answers question: http://stackoverflow.com/q/51963377
type: Answer
has body: I ran into the same issue and it solved indeed by wrapping a Lambda layer around the tensor as @today proposed. Thanks for that hint, it pointed me in the right direction. I wanted to turn a vector into a diagonal matrix to I wanted to concatenate a vector with a square image and by turning the vector in a diag matrix. It worked with the following snippet: def diagonalize(vector): diagonalized = tf.matrix_diag(vector) # make diagonal matrix from vector out_singlechan = tf.expand_dims(diagonalized, -1) # append 1 channel to get compatible to the multichannel image dim return out_singlechan lstm_out = Lambda(diagonalize, output_shape=(self.img_shape[0],self.img_shape[1],1))(lstm_out)
score: 0

http://stackoverflow.com/comment/91099498
type: Comment
has text: What do you mean by non recursive? Only files from a directory or both files and directories but nothing under those directories?
comment on: http://stackoverflow.com/q/52074820
score: 0
type: QuestionComment

http://stackoverflow.com/comment/90922629
comment on: http://stackoverflow.com/a/51986526
has text: @MichaelKirsch No problem. In retrospect, sardok's context manager example may actually be more pythonic, even if it is slightly more complex. I forgot Python had that honestly.
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/a/52069862
answers question: http://stackoverflow.com/q/52056382
score: 0
has comment: http://stackoverflow.com/comment/91089603
type: Answer
has body: Unless you decide to go deep in the keras source code, I don't think you can do this easily. Before writing your own adversarial module, you should check the existing works carefully. As far as I know, keras-adversarial is still used by many people. Of course, it only supports old keras versions, e.g. 2.0.8. Several other things: be careful when you freeze your model weights. If you first compile a model and then freeze some weights, these weights are still trainable, because when the train function is generated during compiling. So you should freeze weights first then compile. keras-adversarial does this job in a more elegant way. Instead of making two models, shared weights but freeze some weights in different ways, it creates two train functions, one for each player.

http://stackoverflow.com/comment/90885465
has text: @MadPhysicist I think it is common https://stackoverflow.com/questions/12330522/reading-a-file-without-newlines I came to a cleaner solution with `splitlines()`
comment on: http://stackoverflow.com/a/51967008
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/91186757
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52111215
score: 0
has text: > GetActiveObject throws < it's CreateObject in the stack trace?

http://stackoverflow.com/comment/90932105
type: QuestionComment
has text: That's true, but you're not instructing your current process to do anything. So you just offload the work on to another process that runs exactly like the one you're already running (if it's CPU-bound). You said you don't want to use a Pool and I asked why; you haven't answered that.
comment on: http://stackoverflow.com/q/51990485
score: 0
type: Comment

http://stackoverflow.com/a/51999173
answers question: http://stackoverflow.com/q/51998466
type: Answer
score: 0
has body: You can't vectorize it (as you are populating lists iteratively and using them in the calculation), but you can do a lot of calculation vectorized up front. Maybe. def loop(array): loc_start = 100 A = np.cumsum(array[:, 0] * array[:, 1]) B = np.cumsum(array[:, 2]) a, b = A[loc_start], B[loc_start] idx = [] lst_a, lst_b = [a], [b] thr = np.abs(a)/ b for step in range(n_init + 1, array.shape[0]): _a = A[step] - a _b = B[step] - b if np.abs(_a) * _b &gt;= thr: loc_start = step a, b = a_, b_ lst_a.append(a) lst_b.append(b) thr = np.abs(np.mean(lst_a)) / np.mean(lst_b) idx.append(step) return idx As long as your cumsum arrays don't overflow (check the values of A[-1] and B[-1] to see), this should be a lot faster.

http://stackoverflow.com/comment/90938051
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51994112
has text: I don't understand your definition of a "concrete value"
score: 0

http://stackoverflow.com/a/52024399
has body: I can't believe it, my file was Vars.INI, windows would recognize it since it would take INI as extension but Ubuntu was looking for Vars.ini and it couldn't find it so I change the name from Vars.INI to Vars.ini.
answers question: http://stackoverflow.com/q/52024005
score: 0
type: Answer

http://stackoverflow.com/q/52025596
score: 1
upvote count: 1
has title: Python console does not show the output of the function
has body: a=b=range(3) In[1] = zip(a,b) I expect to see something like this: out[1] = [(0 0), (1 1), (2 2)] however, the output i get is: out[1] = &lt;zip at 0x26da8d2e9c8&gt; The same for other functions, f.i. range(20) out = range(0,20)) For these function this is not a problem, because I know how these work. But it makes it hard to play around with function and understand how they work because you can never see the output. Can someone explain to me why this console works like this and how I can change this?
type: Question
downvote count: 0
answer count: 1
has answer: http://stackoverflow.com/a/52025610
tagged with: console
favorite count: 0
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/q/51974760
tagged with: decorator
favorite count: 0
tagged with: self
tagged with: python
has answer: http://stackoverflow.com/a/51974858
type: AnsweredQuestion
score: 2
upvote count: 2
type: Question
has title: Change instance attributes inside decorator
accepted answer: http://stackoverflow.com/a/51974858
has body: I have searched for this problem, but I did not find an answer to what I'm exactly looking for. Basically, I want to wrap a class constructor in a try/except clause so it ignores specific types of errors inside the constructor (but logs and prints them anyway). The best way I have found to do this is to wrap my method with a decorator, since there are other classes in which I want to do the same, but I don't want to keep repeating the same try/except clauses. However, the object must remember whether an exception has happened in the constructor (save it in a boolean attribute from that object) so that I can use that information later when that object calls a specific method later. So, I tried doing something like in this snippet: def detectAndIgnoreErrors(fn): def wrappedFunc(*args, **kwargs): try: fn(*args, **kwargs) self.HasAnExceptionOccurredInInit = False except KeyError as e: self.HasAnExceptionOccurredInInit = True # Log and print exception except RuntimeError as e: self.HasAnExceptionOccurredInInit = True # Log and print exception return wrappedFunc class Foo(FooSuperclass): @detectAndIgnoreErrors def __init__(self): # Do stuff that may raise exceptions pass def doStuff(self): if self.HasAnExceptionOccurredInInit: # Do stuff pass else: # Do other stuff pass fooInstance = Foo() fooInstance.doStuff() The idea here would be for the object to ignore errors in the constructor, and later when the doStuff() method is called, the object remembers whether an exception occurred or not with HasAnExceptionOccurredInInit and adjusts its behavior accordingly. However, the interpreter says that the self name is not defined (which makes sense, as I was trying to access it outside the class scope). Then, I tried putting the decorator as a class member, and then later I tried putting it as a class member in Foo's parent class, but none of these alternatives worked. After some research, I realized that decorators are resolved at definition time, not during execution time, so th…
answer count: 1
downvote count: 0

http://stackoverflow.com/q/52106903
tagged with: jquery
score: 4
tagged with: ajax
has comment: http://stackoverflow.com/comment/91186942
answer count: 1
has comment: http://stackoverflow.com/comment/91185958
favorite count: 0
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/52120573
tagged with: python
upvote count: 4
tagged with: bottle
has comment: http://stackoverflow.com/comment/91165683
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52120573
downvote count: 0
has comment: http://stackoverflow.com/comment/91186034
type: Question
has title: Including a bottle template in an AJAX request
has body: Here is my scenario. I am trying to make a local web app to manipulate my movie files, both as a time saving tool and a python learning exercise. Here is my server script: from bottle import run, request, post, get, template, error, static_file from pathlib import Path import re # Show a list of files ready to be moved @get('/move_new_movies') def move_new_movies(): return template('move_new_movies') # Generate a list of files for move_new_movies page @post('/generate_movie_list') def generate_movie_list(): ... do some stuff ... return movie_list if __name__ == '__main__': run(debug=True, reloader=True) generate_movie_list() returns a JSON array in the form of { 'total_results': , 'results': [{'folder': , 'file_name': }] } move_new_movies.tpl: Move New Movies Enter path to new movies And finally, file_list.tpl Folder File Name % for movie in list: {{movie['folder']}} {{movie['file_name']}} % end Now here's my problem. When I browse to .../move_new_movies, I get an error Traceback (most recent call last): ... ... ... File "\path\to\move_new_movies.tpl", line 15, in <module> <% movie_list = response['results'] NameError: name 'response' is not defined Originally, generate_movie_list() would return template('file_list'). There was no python in ajax.success(), and it would just update the page with whatever HTML it received. This worked just as expected; I entered a path, hit submit and the desired table would appear. However, I thought it would be better practice for the server to serve only the JSON data and have the client inset it into the appropriate template file. I thought this because what if the list is not movies, but tv shows or music? I might want to use a different template and don't want to make a new rout for different media. I feel like I'm getting this error because the template is being rendered before ajax.success() can define the results variable. Any idea on how to make this work?

http://stackoverflow.com/a/52061613
answers question: http://stackoverflow.com/q/52061098
score: 0
type: Answer
has body: For first, maybe "php user" dont have permission for running? I meen php dont see global path variable. Also, you can use library for it Symfony\Proccess

http://stackoverflow.com/comment/90913484
has text: I tried both ...
comment on: http://stackoverflow.com/q/51981509
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91027601
comment on: http://stackoverflow.com/a/52037052
score: 0
type: AnswerComment
type: Comment
has text: @brunodesthuilliers I have updated my answer. You are partially right.

http://stackoverflow.com/q/52073018
has comment: http://stackoverflow.com/comment/91098937
has comment: http://stackoverflow.com/comment/91095996
favorite count: 0
has comment: http://stackoverflow.com/comment/91096275
tagged with: python
score: 2
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52084172
has comment: http://stackoverflow.com/comment/91098970
upvote count: 2
tagged with: loops
has title: Looping json data dynamically in Python
type: Question
tagged with: http://stackoverflow.com/tag/json
accepted answer: http://stackoverflow.com/a/52084172
has body: I have a two json file in a server. The first json file is a dataframe in json format where it is having 21 columns. The second json object is a collection of different filters to be applied on the first json(data file) &amp; I want to calculate the reduction in amount column dynamically after applying each filter. Both the jsons are in server. Sample of this is like below, [{ "criteria_no.": 1, "expression": "!=", "attributes": "Industry_name", "value": "Clasentrix" },{ "criteria_no.": 2, "expression": "=", "attributes": "currency", "value": ["EUR","GBP","INR"] },{ "criteria_no.": 3, "expression": "&gt;", "attributes": "Industry_Rating", "value": "A3" },{ "criteria_no.": 4, "expression": "&lt;", "attributes": "Due_date", "value": "01/01/2025" } ] When coded in python, it is like below, import urllib2, json url = urllib2.urlopen('http://.../server/criteria_sample.json') obj = json.load(url) print obj [{u'attributes': u'Industry_name', u'expression': u'!=', u'value': u'Clasentrix', u'criteria_no.': 1}, {u'attributes': u'currency', u'expression': u'=', u'value': [u'EUR', u'GBP', u'INR'], u'criteria_no.': 2}, {u'attributes': u'Industry_Rating', u'expression': u'&gt;', u'value': u'A3', u'criteria_no.': 3}, {u'attributes': u'Due_date', u'expression': u'&lt;', u'value': u'01/01/2025', u'criteria_no.': 4}] Now, in the sample json, we can see "attributes", which are nothing but the columns present in the first data file. I mentioned it has 21 columns, "Industry_name","currency","Industry_Rating","Due_date" are four of them. "Loan_amount" is another column present there in the data file along with all them. Now as this criteria list is only a sample, we are having n number of such criterion or filters. I want this filters to be applied dynamically on the data file &amp; I would like to calculate the reduction in loan amount. Let's consider the first filter, it is saying "Industry_name" column should not have "Clasentrix". So from the data file I want to filter "Industry_name…
downvote count: 0
answer count: 1

http://stackoverflow.com/a/53833564
type: Answer
answers question: http://stackoverflow.com/q/52034778
has comment: http://stackoverflow.com/comment/96427405
has comment: http://stackoverflow.com/comment/96427107
score: 0
has body: Although it is a bit hard to debug the issue without access to your code, what seems wrong to mee is the cluster connection initialization that you are using. I will make a guess and say that your "main" method is used more times than 96 and that leads to the exception you are getting. Try to establish your cluster connection only once for the entire app and pass it around with your app: from sanic import Sanic from aredis import StrictRedisCluster app = Sanic(__name__) @app.listener('before_server_start') def init(app, loop): app.redis_conn = StrictRedisCluster( startup_nodes=HOST, decode_responses=True, loop=loop, max_connections=96 ) @app.route("/") async def test(request): return json.loads(await app.redis_conn.get(cache_key)) app.run(host='0.0.0.0', port=port, after_start=after_start, workers=32) Essentially this is similar to my suggested solution here: How to use an aiohttp ClientSession with Sanic?

http://stackoverflow.com/q/51973246
tagged with: google-drive-api
upvote count: 2
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/51990354
score: 2
has title: Python Google API get() vs get_media()
has comment: http://stackoverflow.com/comment/90930076
type: Question
has comment: http://stackoverflow.com/comment/90940598
has body: I am attempting to use Python to access some files stored on a Google Team Drive. I have figured out the functionality to download files, but am running into a mysterious issue when attempting to get metadata If I execute the following: myfileid = 'thegooglefileid' self.service = build('drive', 'v3', http=creds.authorize(Http())) data = self.service.files().get_media(fileId=myfileid).execute() meta = self.service.files().get(fileId=myfileid,fields="*").execute() "data" returns as expected allowing me the info to download my files as I expect. "meta" returns with a HttpError 404 indicating it can not find the file (which it in fact found in the line above). I know this issue can occur with incorrectly set authorization, but my authorization is set such that I expect this to work SCOPES = ['https://www.googleapis.com/auth/drive.metadata.readonly', 'https://www.googleapis.com/auth/drive', 'https://www.googleapis.com/auth/drive.file'] Any ideas why the file is visible to one part of the API but not the other ?
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/107341644
favorite count: 0
has comment: http://stackoverflow.com/comment/90902554

http://stackoverflow.com/comment/101573232
has text: Not a good solution. For example for nested = {'asd': [{'a': 'hi'}, {'a': 'hi2'}]} you will lose the value 'hi'. And crash for lists of non-dicts for example: nested = {'asd' : ['a', 'b' ] }
type: AnswerComment
comment on: http://stackoverflow.com/a/52081812
score: 0
type: Comment

http://stackoverflow.com/a/51979220
has body: Alex Taylor's on the right track, but the any clause can be greatly simplified: &gt;&gt;&gt; mystring = "Drug CID006338583 AC1O3UYX Stitch 1.515E-3 1.000E0 4.989E-2 5.235E-1 4 63 PTGES,SLC15A1,KLK8,IL7R" &gt;&gt;&gt; check_if_in_mystring = ['Drug', 'Disease'] &gt;&gt;&gt; any(word in mystring for word in check_if_in_mystring) True &gt;&gt;&gt; mystring = "Poodle CID006338583 AC1O3UYX Stitch 1.515E-3 1.000E0 4.989E-2 5.235E-1 4 63 PTGES,SLC15A1,KLK8,IL7R" &gt;&gt;&gt; any(word in mystring for word in check_if_in_mystring) False These approaches loop across the list of words in check_if_in_mystring, and any(...) returns True as soon as the first word in mystring expression is True. If the for word in check_if_in_mystring loop finishes without finding a True value, then any(...) returns False.
score: 0
type: Answer
answers question: http://stackoverflow.com/q/51978494
has comment: http://stackoverflow.com/comment/90908821

http://stackoverflow.com/comment/90973684
type: AnswerComment
has text: am I inputting the filename, cutoff wrongly in the system argument?
type: Comment
comment on: http://stackoverflow.com/a/52010769
score: 0

http://stackoverflow.com/q/51999334
has comment: http://stackoverflow.com/comment/90950009
score: 0
answer count: 0
type: UnansweredQuestion
tagged with: conda
has comment: http://stackoverflow.com/comment/90947832
has comment: http://stackoverflow.com/comment/90947864
type: Question
has title: How to perform this conda operation on Windows
tagged with: python
has body: I am trying to create a conda environment based on a requirements.txt file. This file has been given to me and I may not change it or reproduce. I am trying to use this file to create the exact same environment. I have found a solution on this page: Just a little reminder: pip has this very useful option to install a bunch of packages from a single text file mostly called requirements.txt. Anaconda’s command line tool conda doesn’t support this option directly. It does support reading the package names from a file using the –yes and –file option conda install --yes --file requirements.txt but that does not automatically install all the dependencies. To do this, we need to iterate over the file and install each package in “single package mode”: while read requirement; do conda install --yes $requirement; done &lt; requirements.txt However I am unable to translate it into windows 10 bash code: for %%F IN requirements.txt DO conda install --yes also tried
tagged with: environment

http://stackoverflow.com/a/52055086
upvote count: 2
has comment: http://stackoverflow.com/comment/91066621
type: Answer
has comment: http://stackoverflow.com/comment/91069701
has comment: http://stackoverflow.com/comment/91060364
downvote count: 1
has comment: http://stackoverflow.com/comment/91060426
has body: find_all returns a list, so you need to select the first item. Then use the text property. Like this: # I want to extract 68 from 68 info = soup.find_all("span", class_="g47SY") print(info[0].text) (Why the downvote? I just tested it, works in bs4)
has comment: http://stackoverflow.com/comment/91063401
has comment: http://stackoverflow.com/comment/91063612
has comment: http://stackoverflow.com/comment/91060584
has comment: http://stackoverflow.com/comment/98639678
score: 1
answers question: http://stackoverflow.com/q/52054633

http://stackoverflow.com/comment/91263799
score: 0
type: AnswerComment
type: Comment
has text: This response, while correct, is not detailed enough to be actionable, and bypasses information in the OP.
comment on: http://stackoverflow.com/a/52107370

http://stackoverflow.com/q/52079229
tagged with: python-2.7
answer count: 1
downvote count: 0
favorite count: 0
has title: Best way to store dictionary items for later retrieval?
has answer: http://stackoverflow.com/a/52079361
type: UnansweredQuestion
tagged with: python
linked to: http://stackoverflow.com/q/23724136
score: 1
has body: I am doing a fairly complex task of reading in a python model and then performing various tasks on it, afterwards that gets written out as individual XML files. However along with this I need to provide various summary file depending on what the individual python model contains. In Ruby, I would simply store this data in a struct and then parse the array of data. In Python, the dictionary is equivalent to struct, but what's not obvious to me in my testing is how I can add to the values in a dictionary so that if I have: name: "John" place: "Atlanta" age: "18" All of this neatly fits into a dictionary. But what about the next record? When I use update, it replaces the dictionary items with the new data. So I thought, I would then use a list to simply append the list with my dictionary data. However, when I append my list (because I used update for the dictionary), my list now contains a list of all the same data. What is the proper Python way to store multiple dictionary items so they can be accessed later like they are a single record? I thought maybe a tuple but that didn't seem to get me very far either, so I'm obviously doing something very wrong.
has comment: http://stackoverflow.com/comment/91108683
duplicate of: http://stackoverflow.com/q/23724136
upvote count: 1
type: Question

http://stackoverflow.com/comment/91001828
score: 0
type: Comment
type: QuestionComment
has text: where should i add it , i normally add it sess but it wont work without feed_dict
comment on: http://stackoverflow.com/q/52024026

http://stackoverflow.com/comment/91114221
comment on: http://stackoverflow.com/q/52081675
score: 0
type: Comment
type: QuestionComment
has text: Can you show us the [relevant code](https://stackoverflow.com/help/how-to-ask) please?

http://stackoverflow.com/a/52030011
has comment: http://stackoverflow.com/comment/133711071
type: Answer
score: 3
upvote count: 3
answers question: http://stackoverflow.com/q/52030010
downvote count: 0
has body: I've found the problem. From some reason, python does not use the certificates in my key chain but the ones in the openssl under /Library/Frameworks/Python.framework/Versions/2.7/etc/openssl/cert.pem I've added the certificate at the bottom of file and the problem went away To find where the certificate is, start python and run the following: &gt;&gt;&gt; import certifi &gt;&gt;&gt; certifi.where()
accepted answer of: http://stackoverflow.com/q/52030010
type: AcceptedAnswer

http://stackoverflow.com/a/51981755
score: 0
has comment: http://stackoverflow.com/comment/90913407
type: Answer
has body: Have you include your external resource (like a image) in PyInstaller with the right path folder ? like in this link and have adapt your code ? https://pythonhosted.org/PyInstaller/spec-files.html#adding-data-files ?
answers question: http://stackoverflow.com/q/51981546

http://stackoverflow.com/comment/91172720
has text: Then try running this from x86 native tools command prompt
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/52110485
score: 0

http://stackoverflow.com/a/51998215
has body: Run the container in the background: docker run -dit abc-python-test somecommand You can then use docker wait abc-python-test This can get the container's return code if you are sure the container always exit after run, no matter test pass or failure. Detail refers to offical guide.
upvote count: 2
answers question: http://stackoverflow.com/q/51997932
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/121795992
type: Answer

http://stackoverflow.com/q/51969255
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90889100
type: Question
has answer: http://stackoverflow.com/a/51969804
has comment: http://stackoverflow.com/comment/90890028
answer count: 1
tagged with: string
linked to: http://stackoverflow.com/q/1009160
has comment: http://stackoverflow.com/comment/90889160
has comment: http://stackoverflow.com/comment/90889491
tagged with: in-place
tagged with: python
has title: Why this Python solution is not in-place solution?
accepted answer: http://stackoverflow.com/a/51969804
has body: I was asked this question in one of the interviews. I got feedback from the recruiter saying I didn't solve this problem in place. I was wondering why this solution is not in place? What did I miss here? Input is the character list like ['h','o','w',' ','a','r','e',' ','y','o','u','?']. The output should be a string like ?you are how. charArr = ['h','o','w',' ','a','r','e',' ','y','o','u','?'] #output = ?you are how class Solution(): def reverseStr(self,charArr): charArr = ''.join(charArr).split()[::-1] for i in range(len(charArr)): if not charArr[i][-1].isalnum(): charArr[i] = charArr[i][-1] + charArr[i][:-1] print ' '.join(charArr) s1 = Solution() s1.reverseStr(charArr)
has comment: http://stackoverflow.com/comment/90889267
score: 0
has comment: http://stackoverflow.com/comment/90889328

http://stackoverflow.com/comment/105271978
type: Comment
type: QuestionComment
has text: the code has been fixed here: https://stackoverflow.com/a/59551573/362754
comment on: http://stackoverflow.com/q/52033203
score: 0

http://stackoverflow.com/a/52090250
score: 0
answers question: http://stackoverflow.com/q/52090122
type: Answer
has body: First step: store your values in a list. Second step: just use random.choice() import random my_links = [ "https://www.youtube.com/watch?v=XErrOJGzKv8", "https://www.youtube.com/watch?v=hHW1oY26kxQ", "https://www.youtube.com/watch?v=RmHg6BP5D8g" ] def music(bot, update): update.message.reply_text(random.choice(my_links))

http://stackoverflow.com/q/52024261
has body: n = int(input("please type number of students and their grades&gt;&gt;&gt;")) grades = [] def solve_for(grades): for i in grades(4): if grades_item &gt;= 38: if grades_item % 5 == 3: grades_item += 2 elif grades_item % 5 == 4: grades_item += 1 else: print(grades_item) for i in range(n): grades_item = int(input()) grades.append(grades_item) result = solve_for(grades) am I doing something wrong? Trying to get user to input 4 numbers 73, 67, 38, 33 and produce a list that rounds those number based on the if function for-loop The rules include: If the difference between the grade and the next multiple of 5 is less than 3, round grade up to next multiple of 5 If the value of grade is less than 38, no rounding occurs as the result will still be a failing grade.
has comment: http://stackoverflow.com/comment/90998815
type: UnansweredQuestion
tagged with: python
type: Question
has comment: http://stackoverflow.com/comment/90999012
has comment: http://stackoverflow.com/comment/90998891
tagged with: for-loop
has comment: http://stackoverflow.com/comment/90999034
has comment: http://stackoverflow.com/comment/90998795
has answer: http://stackoverflow.com/a/52024589
has title: How can i display the list of grades of 4 students while rounding them up using Python 3.6
has comment: http://stackoverflow.com/comment/90998800
score: 0
has comment: http://stackoverflow.com/comment/90998783
answer count: 1
tagged with: variable-assignment

http://stackoverflow.com/comment/91149566
comment on: http://stackoverflow.com/q/52099286
type: QuestionComment
has text: Yes, this works if only I had the opinion "Cars", but in reality I have a file that has many opinions with your questions. My idea is to extract opinions and questions automatically.
type: Comment
score: 0

http://stackoverflow.com/comment/91107551
comment on: http://stackoverflow.com/q/52078607
has text: Any reason not to use pd.read_json()? https://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_json.html
type: Comment
type: QuestionComment
score: 1

http://stackoverflow.com/comment/90898500
score: 0
comment on: http://stackoverflow.com/a/51973160
type: AnswerComment
type: Comment
has text: @DSM: what would be faster?

http://stackoverflow.com/q/51959370
has comment: http://stackoverflow.com/comment/90869276
upvote count: 0
type: UnansweredQuestion
has body: I am trying to using the .score() method on a fitted Linear Regressor but I am getting an error. from sklearn.model_selection import train_test_split from sklearn.linear_model import LinearRegression from sklearn import metrics from sklearn.metrics import mean_squared_error X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.3, random_state = 104) reg = LinearRegression() reg.fit(X_train, y_train) y_pred = reg.predict(X_test) print("R^2: {}".format(reg.score(X_test, y_test))) rmse = np.sqrt(mean_squared_error(y_test, y_pred)) print("Root Mean Squared Error: {}".format(rmse)) reg.score(y_test.reshape(-1,1), y_pred.reshape(-1,1)) ValueError: shapes (10719,1) and (16,1) not aligned: 1 (dim 1) != 16 (dim 0) I should mention that I have already tried to reshape y_pred and y_test so that they match but it still does not work. I am not sure why the error says (16,1); what are these the dimensions for? I have tried searching for similar questions such as this one: Error using sklearn and linear regression: shapes (1,16) and (1,1) not aligned: 16 (dim 1) != 1 (dim 0) but I am still confused. Edit: Here is the output for the shapes: print(X_test.shape, y_test.shape, y_pred.shape) (10719, 16) (10719, 1) (10719, 1)
has title: Error using the .score() method: shapes (10719,1) and (16,1) not aligned: 1 (dim 1) != 16 (dim 0)
has comment: http://stackoverflow.com/comment/90869072
tagged with: scikit-learn
favorite count: 0
score: -1
type: Question
tagged with: machine-learning
has answer: http://stackoverflow.com/a/52049503
tagged with: python
linked to: http://stackoverflow.com/q/45911481
has comment: http://stackoverflow.com/comment/90869293
tagged with: linear-regression
has comment: http://stackoverflow.com/comment/90871522
has comment: http://stackoverflow.com/comment/90870110
tagged with: error-handling
answer count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/90869238

http://stackoverflow.com/q/51980033
has title: I'm working on some practice dataset in python
has comment: http://stackoverflow.com/comment/90909708
score: -6
favorite count: 0
type: UnansweredQuestion
tagged with: python
has body: What does this line of code mean? train_data.isnull().any() I don't get it
has answer: http://stackoverflow.com/a/51980389
upvote count: 1
downvote count: 7
type: Question
has answer: http://stackoverflow.com/a/51980117
answer count: 2
tagged with: pandas

http://stackoverflow.com/a/52038861
downvote count: 1
has comment: http://stackoverflow.com/comment/91047080
type: Answer
has comment: http://stackoverflow.com/comment/91029266
has comment: http://stackoverflow.com/comment/91036091
upvote count: 0
has body: Try it: import sys import threading from PyQt5.QtGui import * from PyQt5.QtCore import * from PyQt5.QtWidgets import * class WorkerThread(QThread): workSignal = pyqtSignal(str) def run(self): print("thread started from :" + str(threading.get_ident())) textLabel = "thread started from :" + str(threading.get_ident()) self.workSignal.emit(textLabel) self.work() def work(self): print("working from :" + str(threading.get_ident())) textLabel = "working from :" + str(threading.get_ident()) self.workSignal.emit(textLabel) class MyGui(QWidget): worker = WorkerThread() def __init__(self): super().__init__() self.initUi() print("Starting worker from :" + str(threading.get_ident())) self.lbl.setText("Starting worker from :" + str(threading.get_ident())) self.worker.workSignal.connect(self.showLabel) def initUi(self): self.setGeometry(700, 350, 300, 150) self.lcdTime = QLCDNumber(self) self.lcdTime.setSegmentStyle(QLCDNumber.Filled) # Outline Filled Flat self.lcdTime.setDigitCount(8) self.timer = QTimer(self) self.lbl = QLabel(self) self.pb = QPushButton("Button Close", self, clicked=self.close) vbox = QVBoxLayout() vbox.addWidget(self.lcdTime) vbox.addWidget(self.lbl) vbox.addWidget(self.pb) self.setLayout(vbox) self.timer.timeout.connect(self.showTime) self.timer.start(1000) self.numSec = 0 self.show() def showTime(self): time = QTime.currentTime() text = time.toString("hh:mm:ss") if ((time.second() % 2) == 0): text = text[0:2] + ' ' + text[3:5] + ' ' + text[6:] self.lcdTime.display(text) self.numSec += 1 if self.numSec == 5: self.worker.start() self.numSec = 0 def showLabel(self, textLabel): self.lbl.setText(textLabel) app = QApplication(sys.argv) gui = MyGui() app.exec_()
answers question: http://stackoverflow.com/q/52036021
has comment: http://stackoverflow.com/comment/91046972
has comment: http://stackoverflow.com/comment/91046554
score: -1
has comment: http://stackoverflow.com/comment/91046586

http://stackoverflow.com/a/52081267
score: 3
upvote count: 3
has comment: http://stackoverflow.com/comment/91113627
has comment: http://stackoverflow.com/comment/91113311
accepted answer of: http://stackoverflow.com/q/52081174
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/91113256
type: Answer
answers question: http://stackoverflow.com/q/52081174
has body: You can use the datetime module: import datetime def to_datetime(d): day, month, year = map(int, d.split('/')) return datetime.datetime(year, month, day, 0, 0, 0) a = '01/08/2017' b = '28/08/2017' _a = to_datetime(a) _b = to_datetime(b) c = ['01/08/2017', '20/08/2017', '21/08/2017', '22/08/2017', '23/08/2017', '24/08/2017', '25/08/2017', '26/08/2017', '27/08/2017', '28/08/2017'] for i in c: if _a &lt;= to_datetime(i) &lt;= _b: print(i) Output: 01/08/2017 20/08/2017 21/08/2017 22/08/2017 23/08/2017 24/08/2017 25/08/2017 26/08/2017 27/08/2017 28/08/2017

http://stackoverflow.com/q/52088709
downvote count: 0
linked to: http://stackoverflow.com/q/384759
tagged with: scipy
has answer: http://stackoverflow.com/a/52089176
type: Question
tagged with: numpy
has title: Reduce 3D volume mask by uniform margin in python
upvote count: 2
answer count: 1
favorite count: 0
has body: I'm working with 3D boolean arrays that mask a volume. My goal is to take a mask and reduce the area of the mask by some margin, m, in all dimensions. Is there an easy way to do this using some common libraries (numpy, scipy, pandas, etc..)? I found some code online that uses multiple for loops to expand a mask by one dimension. This works for the expansion case but I feel like there is a more compact way out there. Here is a minimum example of what I am looking for in 2D. Original array([[0., 0., 1., 0., 0.], [0., 1., 1., 1., 0.], [1., 1., 1., 1., 1.], [0., 1., 1., 1., 0.], [0., 0., 1., 0., 0.]]) Uniform reduction by 1 pixel array([[0., 0., 0., 0., 0.], [0., 0., 1., 0., 0.], [0., 1., 1., 1., 0.], [0., 0., 1., 0., 0.], [0., 0., 0., 0., 0.]]) But I want this to be in 3D space. Thank you for any input.
tagged with: python
linked to: http://stackoverflow.com/q/9506841
accepted answer: http://stackoverflow.com/a/52089176
type: AnsweredQuestion
score: 2

http://stackoverflow.com/q/52013610
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/90978084
score: 0
answer count: 1
has answer: http://stackoverflow.com/a/52013963
favorite count: 0
tagged with: beautifulsoup
has title: Python/Beautifulsoup - Missing first row of table
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/52013963
upvote count: 1
has body: Could someone please help me understand why the output for the below code is missing the first row of the table? I'm new to python, and not for lack of trying, I haven't been able to troubleshoot this myself. import requests import csv from collections import OrderedDict from bs4 import BeautifulSoup as soup from urllib.request import urlopen as uReq def printfunction(): with open("C:/Users/.../audusd.csv", 'a', newline='') as f: wr = csv.writer(f) wr.writerows([(data[0], data[1], data[2], data[3], data[4], data[5])]) url = requests.get("https://au.investing.com/currencies/aud-usd-historical-data/", headers={'User-Agent': 'Mozilla/5.0'}) od = OrderedDict() content_page = soup(url.content, 'html.parser') table = content_page.find('table', {'class': 'genTbl closedTbl historicalTbl'}) cols = [th.text for th in table.select("th")[1:]] for row in table.select("tr + tr"): data = [td.text for td in row.select("td")] printfunction() print(data) Output appears thus: ['Aug 23, 2018', '0.7246', '0.7349', '0.7355', '0.7240', '-1.37%'] ['Aug 22, 2018', '0.7347', '0.7370', '0.7371', '0.7332', '-0.33%'] ['Aug 21, 2018', '0.7371', '0.7341', '0.7383', '0.7332', '0.42%'] ['Aug 20, 2018', '0.7340', '0.7306', '0.7344', '0.7294', '0.44%'] ['Aug 19, 2018', '0.7308', '0.7316', '0.7317', '0.7308', '-0.05%'] ['Aug 17, 2018', '0.7312', '0.7261', '0.7321', '0.7253', '0.70%'] ['Aug 16, 2018', '0.7261', '0.7240', '0.7288', '0.7222', '0.30%'] ['Aug 15, 2018', '0.7239', '0.7247', '0.7249', '0.7202', '-0.08%'] ['Aug 14, 2018', '0.7245', '0.7270', '0.7284', '0.7222', '-0.33%'] ['Aug 13, 2018', '0.7269', '0.7289', '0.7300', '0.7248', '-0.25%'] ['Aug 12, 2018', '0.7287', '0.7278', '0.7300', '0.7273', '-0.21%'] ['Aug 10, 2018', '0.7302', '0.7372', '0.7381', '0.7279', '-0.95%'] ['Aug 09, 2018', '0.7372', '0.7435', '0.7456', '0.7371', '-0.81%'] ['Aug 08, 2018', '0.7432', '0.7420', '0.7440', '0.7382', '0.15%'] ['Aug 07, 2018', '0.7421', '0.7386', '0.7440', '0.7379', '0.46%'] ['Aug 06, 2018', '0.7387', '0…

http://stackoverflow.com/a/52604624
score: 0
accepted answer of: http://stackoverflow.com/q/52002684
type: Answer
answers question: http://stackoverflow.com/q/52002684
has body: My conclusion after investigating the hints in the comments is: Python conflicts with itself. Do not try to avoid this - cope with it. Use virtual environments to handle the unavoidable multiple Python versions consistently. pyenv seems to work best for my purposes. Use the following to install first pyenv (1), update it (2), install a Pythons version (for this example 3.5.6) with pyenv (3), set your user-global python to the installed version (4), upgrade the Python package mangement tools (5) and install anything inside the virtual Python enviroment (6). curl -L https://github.com/pyenv/pyenv-installer/raw/master/bin/pyenv-installer | bash pyenv update CONFIGURE_OPTS=--enable-shared pyenv install 3.5.6 pyenv global 3.5.6 pip install --upgrade pip setuptools wheel pip install ipython jupyter snowflake-connector-python seaborn CONFIGURE_OPTS=--enable-shared in (3) is needed for some python packages which depend on shared libraries. seaborn will not install without it. Note that the pyenvinstalled versions includes the package manager pip. Now every call python or pip everything references to the correct version. When referencing python in scripts in MacOS bash and other *NIXes use #!/usr/bin/env python. It is possible to install pyenv install 2.7.15 the latest python 2.7 and change to it whenever necessary. pyenv shell 2.7.15 switches to Python2.7 only for a particular shell session when needed to run an adhoc script. Since I use this flow I have no headaches anymore. The same setup works superfine so far both on a local MacOS and on a remote Ububtu based jupyter notebook server. Disclaimer: I am not a hardcore Python fullstack developer, but use Python whenever necessary in Data Science pipelines. So for application development in Python this might not be the best solution, but for consistent management of a Data Science environment it seems to work well. Hope this is helpful.
type: AcceptedAnswer

http://stackoverflow.com/q/52042605
linked to: http://stackoverflow.com/q/56011
has answer: http://stackoverflow.com/a/52042722
has answer: http://stackoverflow.com/a/52042670
tagged with: python
has comment: http://stackoverflow.com/comment/91036157
has body: I'm very new to python and was wondering what is wrong with this code: num1 = input("Please Eneter A Number") num2 = input("Please Enter Another Number") operation = input("Please Enter An Operation You Want To Do (example: +, -, *, /): ") if operation == +: print(num1 + num2) if operation == -: print(num1 - num2) if operation == /: print(num1 / num2) if operation == *: print(num1 * num2) this is the error I get when trying to run this code: if operation == +: ^ SyntaxError: invalid syntax I could not find any problem of this sort on this forum. Please forgive me if this is a dumb question.
has comment: http://stackoverflow.com/comment/91036042
type: UnansweredQuestion
downvote count: 2
type: Question
score: -2
answer count: 2
has title: Syntax Error in if statement with operators
upvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/91036252

http://stackoverflow.com/q/51969376
downvote count: 0
tagged with: dataframe
has title: Delete initial rows of a pandas dataframe that satisfy column value condition while keeping the sequence values in a column intact
tagged with: pandas
has answer: http://stackoverflow.com/a/51969468
favorite count: 0
has answer: http://stackoverflow.com/a/51969530
has body: dt = {'id': [120,120,120,120,121,121,121], 'day': [0, 1,2,3,0,1,2], 'value': [[0.5,3.4,2.7],[0.45,3.4,0.7],[0.25,0.4,0.7],[0.15,0.34,0.17],[0.35,3.4,2.7],[0.5,3.44,2.57],[0.5,0.34,0.37]]} df = pd.DataFrame(data=dt) day id value 0 0 120 [0.5, 3.4, 2.7] 1 1 120 [0.45, 3.4, 0.7] 2 2 120 [0.25, 0.4, 0.7] 3 3 120 [0.15, 0.34, 0.17] 4 0 121 [0.35, 3.4, 2.7] 5 1 121 [0.5, 3.44, 2.57] 6 2 121 [0.5, 0.34, 0.37] I have a pandas dataframe. I want the sequence column "day" to be of maximum value upto 1. For column day with value above 1 I want to delete it's initial rows, and then reset the sequence to [0-1] That is in this case, column"id"=120 has column "day" has two extra values 2 and 3. I want to delete their first two rows in this case and then replace the column values of day to (0,1). Result: day id value 0 0 120 [0.25, 0.4, 0.7] 1 1 120 [0.15, 0.34, 0.17] 2 0 121 [0.5, 3.44, 2.57] 3 1 121 [0.5, 0.34, 0.37]
possible better answer: http://stackoverflow.com/a/51969468
upvote count: 2
tagged with: python
score: 2
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51969530
type: Question
answer count: 2

http://stackoverflow.com/a/51980127
has body: try this df = df[df.loc[:, 'caseID'].isin(df[df['TransactionStatus'] == 'Open']['caseID'])]
type: Answer
score: 2
has comment: http://stackoverflow.com/comment/90910058
upvote count: 2
has comment: http://stackoverflow.com/comment/90910035
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51979976
answers question: http://stackoverflow.com/q/51979976

http://stackoverflow.com/a/51979843
upvote count: 2
answers question: http://stackoverflow.com/q/51978488
has body: It looks like keras is trying to treat a shape tensor as an iterable - which it can only do in eager mode. Assuming you know the static shape of ActorNetwork.k_list, you can convert this to a list by using k_list.shape.as_list(). I suspect its in the keys line, so try keys = Input(shape=ActorNetwork.k_list.shape.as_list()))
has comment: http://stackoverflow.com/comment/91082032
has comment: http://stackoverflow.com/comment/90909276
downvote count: 0
type: Answer
score: 2

http://stackoverflow.com/a/52079615
type: Answer
score: 1
upvote count: 1
downvote count: 0
has body: I usually do it this way: columnsWithNa = ['column1', 'column2'] for column in columnsWithNa : df[column].fillna(df[column].mean()[0], inplace = True)
answers question: http://stackoverflow.com/q/52079391

http://stackoverflow.com/q/52008774
has body: I'm learning Flask and I want to do a simple invoice app, but I don't have any idea of how to return back on post all data row from a table with four fields {code, description, price, quantity} to be inserted or updated as the details to my DB table. This is just a code example. # app.py from flask import Flask, request, redirect, url_for, render_template from flask_wtf import FlaskForm from wtforms import StringField, IntegerField, DecimalField app = Flask(__main__) def save_invoice_det(): # Here i'll iterate all rows got from the table pass class DetailForm(FlaskForm): item_code = IntegerField('Item Code') item_desc = StringField('Description') quantity = DecimalField('Qty') price = DecimalField('Price', places=2) total = DecimalField('Total', places=2) @app.route('/invoice', methods=['GET', 'POST']) def invoice(number): form = DetailForm() # This is just example models table query_det = Details_Inv.query.get(number) if request.method == 'POST': # Here i need to know how to get all row from the table if form.validate_on_submit(): save_invoice_det() return redirect(url_for('list_invoices')) return render_template('invoice.html', details=query_det) if name == '__main__': app.run(debug=True) # invoice.html Create / Edit Invoice Item Code Item Descripction Quantity Price Total {% for detail in details %} {{ detail.item_code }} {{ detail.item_desc }} {{ detail.quantity }} {{ detail.price }} {{ detail.total }} {% endfor %}
tagged with: http://stackoverflow.com/tag/html
tagged with: python
has title: Python Flask how to get all records from html table in a request post
type: UnansweredQuestion
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/90968823
type: Question
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/52013074
tagged with: flask
favorite count: 0

http://stackoverflow.com/comment/91154357
has text: I think the OP's issue is that the *JSON encoded data grows*, and as far as I can tell, this is impossible to prevent?
type: AnswerComment
type: Comment
score: 0
comment on: http://stackoverflow.com/a/52101247

http://stackoverflow.com/q/52110385
tagged with: python
type: AnsweredQuestion
upvote count: 3
has answer: http://stackoverflow.com/a/52110422
type: Question
has answer: http://stackoverflow.com/a/52110431
answer count: 2
tagged with: pandas
score: 3
possible better answer: http://stackoverflow.com/a/52110431
accepted answer: http://stackoverflow.com/a/52110422
downvote count: 0
has body: import pandas as pd df = pd.DataFrame({'x':[1,2,1,2,1,3,2],'y':[34,23,23,65,45,12,28],'z':['a','b','a','','a','c','b']}) df.groupby('x').z.count().reset_index() x z 0 1 3 1 2 3 2 3 1 But this is what I don't want, the empty string should not be in the count, so what I want is x z 0 1 3 1 2 2 2 3 1 what should I do?
favorite count: 0
has title: the count method in python can not ignore the empty string

http://stackoverflow.com/q/52080799
score: 7
upvote count: 7
has answer: http://stackoverflow.com/a/52080885
has body: I'm trying to get the first non null value from multiple pandas series in a dataframe. df = pd.DataFrame({'a':[2, np.nan, np.nan, np.nan], 'b':[np.nan, 5, np.nan, np.nan], 'c':[np.nan, 55, 13, 14], 'd':[np.nan, np.nan, np.nan, 4], 'e':[12, np.nan, np.nan, 22], }) a b c d e 0 2.0 NaN NaN NaN 12.0 1 NaN 5.0 55.0 NaN NaN 2 NaN NaN 13.0 NaN NaN 3 NaN NaN 14.0 4.0 22.0 in this df I want to create a new column 'f', and set it equal to 'a' if a is not null, 'b' if b is not null etc. down to e. I could do a bunch of np.where statements which is inefficient. df['f'] = np.where(df.a.notnull(), df.a, np.where(df.b.notnull(), df.b, etc.)) I looked into doing df.a or df.b or df.c etc. result should look like: a b c d e f 0 2.0 NaN NaN NaN 12.0 2 1 NaN 5.0 55.0 NaN NaN 5 2 NaN NaN 13.0 NaN NaN 13 3 NaN NaN 14.0 4.0 22.0 14
has answer: http://stackoverflow.com/a/52081591
type: Question
accepted answer: http://stackoverflow.com/a/52080885
tagged with: dataframe
possible better answer: http://stackoverflow.com/a/52081419
has answer: http://stackoverflow.com/a/52081419
answer count: 3
tagged with: pandas
has title: taking the first non null in python
downvote count: 0
favorite count: 0
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/comment/91151764
has text: Question has been updated.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52100386

http://stackoverflow.com/q/52067100
tagged with: tensorflow
type: Question
has title: Deep learning with data from simulations
has body: While reading the great book by F. Chollet, I'm experimenting with Keras / Tensorflow, on a simple Sequential model that I train on simulated images, which come from a physical analytical model. Having full control of the simulations, I wrote a generator which produces an infinite stream of data and label batches, which I use with fit_generator in Keras. The data so generated are never identical, plus I can add some random noise to each image. Now I'm wondering: is it a problem if the model never sees the same input data from one epoch to the next? Can I assume my problems in getting the loss down are not due to the fact that the data are "infinite" (so I only have to concentrate on hyper parameters tuning)? Please feel free if you have any advice for dealing with DL on simulated data.
upvote count: 0
answer count: 1
tagged with: keras
favorite count: 0
score: -3
has answer: http://stackoverflow.com/a/52067354
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/52067354
has comment: http://stackoverflow.com/comment/91084519
downvote count: 3
tagged with: machine-learning

http://stackoverflow.com/q/52049257
tagged with: url
has comment: http://stackoverflow.com/comment/91049560
has comment: http://stackoverflow.com/comment/91049793
has comment: http://stackoverflow.com/comment/91050182
favorite count: 0
tagged with: beautifulsoup
has comment: http://stackoverflow.com/comment/91049818
has body: I'm scraping through a list of urls using beautiful soup. say I got a list of urls in an array called satellites from bs4 import BeautifulSoup as bs import pandas as p import numpy as np import requests as r import json satellites = [ "https://solarsystem.nasa.gov/missions/insight/in-depth/", "https://solarsystem.nasa.gov/missions/mars-cube-one/in-depth/", "https://solarsystem.nasa.gov/missions/osiris-rex/in-depth/", "https://solarsystem.nasa.gov/missions/exomars-trace-gas-orbiter/in-depth/", "https://solarsystem.nasa.gov/missions/hayabusa-2/in-depth/"] # Then my code starts with: for sat in satellites: print(sat) page = r.get(sat) print("got page") soup = bs(page.content, "html.parser") print("got soup") getting the page content works for the first url, but the second returns None which gives me a traceback 'None' has no attribute 'content'. I switched the first and second urls around, and the result is the same. All the urls have been tested for being valid and they are. is there an issue with using requests on a loop over urls?
tagged with: python
has comment: http://stackoverflow.com/comment/91143753
has comment: http://stackoverflow.com/comment/91054558
type: UnansweredQuestion
upvote count: 1
tagged with: web-scraping
downvote count: 1
type: Question
has answer: http://stackoverflow.com/a/52105276
has title: Python: second url in list of urls returns None
has comment: http://stackoverflow.com/comment/91049523
has comment: http://stackoverflow.com/comment/91049278
score: 0
has comment: http://stackoverflow.com/comment/91049669
answer count: 1
has comment: http://stackoverflow.com/comment/91142750

http://stackoverflow.com/a/52110556
answers question: http://stackoverflow.com/q/52110530
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/91172611
accepted answer of: http://stackoverflow.com/q/52110530
type: Answer
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/91172500
has comment: http://stackoverflow.com/comment/91172623
has body: You forget assign output, but faster vectorized solution is convert column to string and add strings with no apply with f strings: def some_function(): df['important_column'] = [f'{x}' for x in df['important_column']] #alternative1 df['important_column'] = '' + df['important_column'].astype(str) + '' #alternative2 #df['important_column'] = df['important_column'].apply(lambda x: '' + str(x) + '') #alternative3, thanks @Jon Clements #df['important_column'] = df['important_column'].apply('{}?'.format) return df.to_html() EDIT: df['important_column'] = [f'{x}' for x in df['important_column']] print (df.to_html(escape=False)) important_column dummy_column 0 1 5 1 2 6 2 3 7 3 4 8 Timings: df = pd.DataFrame({'important_column': [1,2,3,4], 'dummy_column': [5,6,7,8]}) df = pd.concat([df] * 10000, ignore_index=True) In [213]: %timeit df['important_column'] = [f'{x}' for x in df['important_column']] 74 ms ± 22.2 ms per loop (mean ± std. dev. of 7 runs, 100 loops each) In [214]: %timeit df['important_column'] = df['important_column'].apply(lambda x: '' + str(x) + '') 150 ms ± 7.75 ms per loop (mean ± std. dev. of 7 runs, 10 loops each) In [216]: %timeit df['important_column'].apply('{}?'.format) 133 ms ± 238 µs per loop (mean ± std. dev. of 7 runs, 10 loops each) In [217]: %timeit '' + df['important_column'].astype(str) + '' 266 ms ± 1.21 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

http://stackoverflow.com/q/51962651
has comment: http://stackoverflow.com/comment/130177561
score: 2
type: AnsweredQuestion
downvote count: 0
possible better answer: http://stackoverflow.com/a/73719788
favorite count: 0
linked to: http://stackoverflow.com/q/21609380
has answer: http://stackoverflow.com/a/51969053
type: Question
has title: Validate protein sequence
tagged with: python
tagged with: biopython
accepted answer: http://stackoverflow.com/a/51969053
upvote count: 2
tagged with: bioinformatics
answer count: 2
has answer: http://stackoverflow.com/a/73719788
has comment: http://stackoverflow.com/comment/130176416
has body: In some cases, I have sequences with characters that do not corresponds to proteins. &gt;ISAnsp8_orf1 MRKSRFTEEQIAHALRQVDAGVPAAELCRKLGISEQTFYAWKKKYAGMGIAEMRRVKQLEDENRRLKTLVADLTLDKHMLQEVLRKKF &gt;IS3_orf1 UGAAGAGCUGGCUAUCCUCCAAAAGGCCGCGACAUACUUCGCGAAGCGCC &gt;IS3_orf2 ..............................(((((((((((......[[[ &gt;IS3_orf3 UGAAAUGAAGUAUGUCUUUAUUGAAAAACAUCAGGCUGAGUUCAGCAUCA &gt;IS3_orf4 [[[..)))))))))))..............]]]]]] &gt;IS3_orf5 AAGCAAUGUGCCGCGUGCUCCGGGUGGCCCGCA &gt;IS3_orf7 MTKTVSTSKKPRKQHSPEFRSEALKLAERIGVTAAARELSLYESQLYNWRSKQQNQQTSSERELEMSTEIARLKRQLAERDEELAILQKAATYFAKRLK Because I want to validate the sequences before to save in another file, I wrote this to test a validation method. That is rare because I used to different sequences, one including non-protein characters '(' but it still gives me the answer as True. Testing all the three possibilities to 'sequence'the answer is the same (False) import sys from Bio.Seq import Seq from Bio.Alphabet import IUPAC, ProteinAlphabet sequence = sys.argv[1] #sequence = '(((((((((((' #sequence = 'TGEKPYVCQECGKAFNCSSYLSKHQR' my_prot = Seq(sequence, alphabet=IUPAC.IUPACProtein) print isinstance(my_prot.alphabet, ProteinAlphabet) if isinstance(my_prot.alphabet, ProteinAlphabet) == True: print 'ok' , isinstance(my_prot.alphabet, ProteinAlphabet) else: print 'no'

http://stackoverflow.com/comment/91022921
score: 0
comment on: http://stackoverflow.com/q/51989415
has text: Usually you do want to use *pagination* for that.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91157022
score: 0
comment on: http://stackoverflow.com/q/52103070
type: Comment
type: QuestionComment
has text: Have you done anything to try to identify complex words? Do you have an example TXT file or sample code? What constitutes a complex word?

http://stackoverflow.com/a/51990801
type: Answer
score: 2
answers question: http://stackoverflow.com/q/51990132
upvote count: 2
has body: If I understood you correctly: df = pd.read_csv(your_file) l = [' '.join(df['col'])] Input: col 0 Hail Mary. 1 Hi Bob. 2 Hey Sue. Output: ['Hail Mary. Hi Bob. Hey Sue.']
has comment: http://stackoverflow.com/comment/90931838
accepted answer of: http://stackoverflow.com/q/51990132
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/52085394
downvote count: 0
tagged with: pandas
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/52085855
has body: I'm learning pandas.cut to put my data into different bins. I'm running the example code from the pandas documentation. But somehow the category shown in the outputs I generated are different. The first example: Tocut = np.array([1, 7, 5, 6, 4, 9]) pd.cut(Tocut, 3) The category output I get is "Categories (3, object): [(0.992, 3.667] &lt; (3.667, 6.333] &lt; (6.333, 9]]" while the documentation shows "Categories (3, interval[float64]):..." The second example: s = pd.Series(np.array([2, 4, 6, 8, 10]), index=['a', 'b', 'c', 'd', 'e']) pd.cut(s, 6) The category output I get is "Categories (6, object):" while the documentation still shows float64. I am just wondering what contributes to this. And is anything in Python not an object? Thanks.
tagged with: python
type: AnsweredQuestion
has title: Discrepancy between my pandas.cut output category and the ones shown in pandas documentation
score: 1
upvote count: 1
type: Question
accepted answer: http://stackoverflow.com/a/52085855

http://stackoverflow.com/q/52085323
tagged with: python
has title: (effeciently) Iterating recursively over multiple dataframes in pandas
type: AnsweredQuestion
tagged with: recursion
score: 2
tagged with: dataframe
type: Question
has comment: http://stackoverflow.com/comment/91122785
downvote count: 0
accepted answer: http://stackoverflow.com/a/52090091
tagged with: optimization
tagged with: pandas
answer count: 1
has answer: http://stackoverflow.com/a/52090091
favorite count: 0
has comment: http://stackoverflow.com/comment/91122217
upvote count: 2
has body: So basically I'm working with large datasets of market data (100,000 rows). A simplified version of the dataset columns look like this: [Timestamp] [Price] [Shares] [orders] [side] 111.239 $23.28 200 2 B 111.240 $23.59 200 1 S Etc etc. This data is what comes out of our market parsing software after feeding it a pcap file. Now I need to compare the output of the same market data from two different sources to make sure our market data parser is working correctly and not dropping orders or behaving inconsistently. The only problem is that the timestamps are slightly different because the data is from two different sources. So my current approach is to implement these datasets as lists of dictionaries, each dictionary representing one of these orders. I have dictionary A and dictionary B, each representing one of the two sources, and each ordered by timestamp. Then I choose a 'fuzz-factor' of time, in this example I will use 2 seconds. Here is how I do my comparison in pseduo-code: for item1 in dictionaryA: for item 2 in dictionaryB if the item2[timestamp] is over 2 seconds before item1[timestamp]: remove item from dictionaryB elif item2[timestamp] is over 2 seconds after item1[timestamp]: mark item1 as not matched break else: # We are in 2 second fuzz factor: compare the items, if a match is found: Mark item 1 in dictionaryA as matched Remove item2 from dictionary break So as you can see I speed up processing by constantly removing items from dictionary B as I cycle through dictionary A. Since most of the items match this speeds things up considerably. However I'm not sure how to do something like this in pandas. The apply() function seems to be the fastest way to iterate through a dataset, but it iterates the entire dataset, not until a certain condition is met like the timestamp fuzzing I do above. Furthermore I'm not sure how fast dropping rows is in pandas. Something to note: Timestamps are at nanosecond precision in floating point format, but several orders may h…

http://stackoverflow.com/q/52029918
type: Question
tagged with: python-2.7
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/52046271
has answer: http://stackoverflow.com/a/52047229
tagged with: singleton
tagged with: python
has title: Can not import a class from another file in the same directory in Python
type: UnansweredQuestion
has body: I am quite new to Python and I am still getting used to it. I have a project which was written by using a bunch of files containing only function definitions. I decided to remake it in OOP paradigm so this is what happens: Back then, I had these two files: Main | ---- loggingManager.py | ---- servoManager.py in the servoManager.py script I had: from loggingManager import * ... from time import sleep and it all works fine. I can use all of the functions defined in loggingManager.py without any issues. Now I have it like this: Main | ---- Logger.py | ---- ConfigurationWrapper.py The content of the ConfigurationWrapper is : import configparser class ConfigurationWrapper: default_path = '/home/pi/Desktop/Bree/config.ini' def __init__(self, path_to_file=None): if path_to_file is None: path_to_file = self.default_path ... and Logger looks like this: class Singleton(type): _instances = {} def __call__(cls, *args, **kwargs): if cls not in cls._instances: cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwarg$ else: cls._instances[cls].__init__(*args, **kwargs) return cls._instances[cls] class Logger(): __metaclass__ = Singleton My goal here is to import: import ConfigurationWrapper in Logger.py script file but every time I do that, I get an error (by typing 'python Logger' in the terminal on MacOS): Traceback (most recent call last): File "Logger", line 1, in &lt;module&gt; import ConfigurationWrapper ImportError: No module named ConfigurationWrapper I tried to add empty __ init __.py file in the same folder but still nothing happens.
tagged with: oop

http://stackoverflow.com/comment/90902447
score: 1
comment on: http://stackoverflow.com/q/51975792
has text: Show us a [mcve] so we can play with it. I'm guessing the easiest solution will be to make a function to convert from nested to sequential.
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52086852
has answer: http://stackoverflow.com/a/54225071
has answer: http://stackoverflow.com/a/52086909
favorite count: 0
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/91123993
upvote count: 0
has comment: http://stackoverflow.com/comment/91124641
has comment: http://stackoverflow.com/comment/91124020
has title: How to get info box text with Python
type: Question
score: -2
has body: Im sorry if this question sounds a bit vague, but I dont know the term for what I am looking for. If you place your mouse cursor over an item in Windows and leave it there for a second, a box pops up with some text. For example, if you have your cursor on the 'e' icon, a box will show up with the text "Microsoft Edge". Is there a method, using Python, to read what that text is? So for the example given, I would like to write or call a function that returns a string containing "Microsoft Edge". Thank you for any help you can offer.
answer count: 2
downvote count: 2

http://stackoverflow.com/comment/91154824
has text: You say you want to create four separate arrays "so I can add it to a pandas data frame", but if all you want is df, `pd.DataFrame(MasterList, columns=columns)` would have worked. Why do you need the separation, and why the reshape?
type: Comment
type: QuestionComment
score: 2
comment on: http://stackoverflow.com/q/52101988

file
type: Tag
tags question: http://stackoverflow.com/q/52088579
tags question: http://stackoverflow.com/q/51986961
tag name: file
tags question: http://stackoverflow.com/q/51986841
tags question: http://stackoverflow.com/q/52058768
tags question: http://stackoverflow.com/q/51989294
tags question: http://stackoverflow.com/q/51957849
tags question: http://stackoverflow.com/q/52029013
tags question: http://stackoverflow.com/q/52061214
tags question: http://stackoverflow.com/q/52110942
tags question: http://stackoverflow.com/q/52050755
tags question: http://stackoverflow.com/q/51971607
tags question: http://stackoverflow.com/q/52050346
tags question: http://stackoverflow.com/q/52000473
tags question: http://stackoverflow.com/q/51999007
tags question: http://stackoverflow.com/q/52001440
tags question: http://stackoverflow.com/q/52038865
tags question: http://stackoverflow.com/q/52087219
tags question: http://stackoverflow.com/q/52026789
tags question: http://stackoverflow.com/q/51979357
tags question: http://stackoverflow.com/q/51994575
tags question: http://stackoverflow.com/q/52094264
tags question: http://stackoverflow.com/q/52061872
tags question: http://stackoverflow.com/q/51972676
tags question: http://stackoverflow.com/q/52082925

http://stackoverflow.com/comment/90965352
comment on: http://stackoverflow.com/q/52007401
score: 0
has text: Possible duplicate of [Print series of prime numbers in python](https://stackoverflow.com/questions/11619942/print-series-of-prime-numbers-in-python)
type: Comment
type: QuestionComment

http://stackoverflow.com/a/52073318
type: AcceptedAnswer
type: Answer
answers question: http://stackoverflow.com/q/52072537
has body: Using .find and .text works as expected: from bs4 import BeautifulSoup string = ''' ... AccessibleComputing 0 10 <redirect title="Computer accessibility" /> 854851586 834079434 2018-08-14T06:47:24Z Godsy 23257138 remove from category for seeking instructions on rcats wikitext text/x-wiki #REDIRECT Computer accessibility {{R from move}} {{R from CamelCase}} {{R unprintworthy}} 42l0cvblwtb4nnupxm6wo000d27t6kf ... ''' soup = BeautifulSoup(string, 'html.parser') page_tag = soup.find('page') text_tag = page_tag.find('text') print(text_tag.text) # #REDIRECT Computer accessibility # {{R from move}} # {{R from CamelCase}} # {{R unprintworthy}}
accepted answer of: http://stackoverflow.com/q/52072537
score: 0

http://stackoverflow.com/comment/90897479
has text: @coldspeed done
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51973153

http://stackoverflow.com/q/51978160
score: 1
has body: I constructed such a regex following an instrucion #Create phone regex phoneRegex = re.compile(r'''( (\d{3}|\(\d{3}\))? # area code (\s|-|\.)? # separator (\d{3}) # first 3 digits (\s|-|\.) # separator (\d{4}) # last 4 digits (\s*(ext|x|ext.)\s*(\d{2,5}))? # extension )''', re.VERBOSE) I tested it In [91]: text Out[91]: '800-420-7240 415-863-9900 415-863-9950' In [92]: phoneRegex.findall(text) Out[92]: [('800-420-7240', '800', '-', '420', '-', '7240', '', '', ''), ('415-863-9900', '415', '-', '863', '-', '9900', '', '', ''), ('415-863-9950', '415', '-', '863', '-', '9950', '', '', '')] There are three None at the end of each groups, especially the last one of 415-863-9950 which has no spaces. How could the extra spaces are generated?
has comment: http://stackoverflow.com/comment/90906266
favorite count: 0
has comment: http://stackoverflow.com/comment/90906210
has comment: http://stackoverflow.com/comment/90906119
accepted answer: http://stackoverflow.com/a/51978834
type: Question
tagged with: python
has comment: http://stackoverflow.com/comment/90906411
tagged with: regex
has title: re.findall generate unexpected extra spaces
possible better answer: http://stackoverflow.com/a/51978748
upvote count: 1
has answer: http://stackoverflow.com/a/51978748
has answer: http://stackoverflow.com/a/51978834
answer count: 2
type: AnsweredQuestion
downvote count: 0

http://stackoverflow.com/comment/91132271
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52089796
has text: @e4c5 without IV specified, seems the ECB is used. Indeed the best practice is to explicitly specify the mode `Cipher.getInstance("AES/ECB/Pkcs5Padding");`

rstudio
tags question: http://stackoverflow.com/q/52048251
tags question: http://stackoverflow.com/q/51996273
tag name: rstudio
type: Tag
tags question: http://stackoverflow.com/q/51992770

http://stackoverflow.com/comment/91094626
has text: @Amfasis If a set an empty QHBoxLayout as the results pane, then it looks exactly as expected. Why is that?
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/52071203

http://stackoverflow.com/q/51985096
tagged with: python
has answer: http://stackoverflow.com/a/51985768
tagged with: indexing
score: 2
accepted answer: http://stackoverflow.com/a/51985768
type: AnsweredQuestion
has title: Querying Numpy Structured Array Based On Structured Array Within
type: Question
upvote count: 2
tagged with: numpy
has comment: http://stackoverflow.com/comment/90919647
has body: I've got a structure like the following one: product_type = np.dtype([('message_counter', np.int), ('alteration_time', 'U32'), ('area_states', status_type, (3,)), ]) with: status_type = np.dtype([('area', 'U32'), ('state', 'U32')]) furthermore I have an array of product_type like: products = np.array([product1, product2, ...], dtype=product_type) now I want to select products which only have a status_type equal to ('area1', 'active'). How would I achieve this. I've tried something like: mask = np.isin(products['area_states']'area', 'state', ('area1', 'active')) active_products = products[mask] Unfortunately this didn't work out the way I hoped. Of course I only received a mask for the subarray (status_type) but I rather like to get a mask on products so that I can filter for the products which only have a status_type with ('area1', 'active'). so all in all the code would be the following: status_type = np.dtype([('area', 'U32'), ('state', 'U32')]) product_type = np.dtype([('message_counter', np.int), ('alteration_time', 'U32'), ('area_states', status_type, (3,)), ]) products = np.array([(253, '12:00', [('area1', 'active'), ('area2', 'inactive'), ('area3', 'inactive')]), (254, '13:00', [('area1', 'inactive'), ('area2', 'inactive'), ('area3', 'inactive')])], dtype=product_type) active_products_in_area1 = '???'
downvote count: 0
answer count: 1
tagged with: data-science
favorite count: 0

http://stackoverflow.com/a/52037606
downvote count: 0
score: 1
upvote count: 1
has body: Instantiate the class first and then overwrite the method as such; my_obj = Class() #Instantiate the class my_obj.name = 'this is the string' This will replace the constructed name with your own string.
answers question: http://stackoverflow.com/q/52037519
type: Answer

http://stackoverflow.com/comment/91064000
type: AnswerComment
type: Comment
has text: Works! Thank you.
comment on: http://stackoverflow.com/a/52056085
score: 0

http://stackoverflow.com/q/52067481
upvote count: 1
has comment: http://stackoverflow.com/comment/91100945
tagged with: keras
favorite count: 0
has comment: http://stackoverflow.com/comment/91101429
type: UnansweredQuestion
tagged with: python
tagged with: conv-neural-network
answer count: 0
downvote count: 0
has body: I have run a code from this link: https://keras.io/getting-started/sequential-model-guide/ The code is given below: import keras from keras.models import Sequential from keras.layers import Dense, Dropout, Flatten from keras.layers import Conv2D, MaxPooling2D from keras.optimizers import SGD with tf.device('/gpu:0'): x_train = np.random.random((100, 100, 100, 3)) y_train = keras.utils.to_categorical(np.random.randint(10, size=(100, 1)), num_classes=10) x_test = np.random.random((20, 100, 100, 3)) y_test = keras.utils.to_categorical(np.random.randint(10, size=(20, 1)), num_classes=10) model = Sequential() model.add(Conv2D(32, (3, 3), activation='relu', input_shape=(100, 100, 3))) model.add(Conv2D(32, (3, 3), activation='relu')) model.add(MaxPooling2D(pool_size=(2, 2))) model.add(Dropout(0.25)) model.add(Conv2D(64, (3, 3), activation='relu')) model.add(Conv2D(64, (3, 3), activation='relu')) model.add(MaxPooling2D(pool_size=(2, 2))) model.add(Dropout(0.25)) model.add(Flatten()) model.add(Dense(256, activation='relu')) model.add(Dropout(0.5)) model.add(Dense(10, activation='softmax')) sgd = SGD(lr=0.01, decay=1e-6, momentum=0.9, nesterov=True) model.compile(loss='categorical_crossentropy', optimizer=sgd) model.fit(x_train, y_train, batch_size=32, epochs=10) score = model.evaluate(x_test, y_test, batch_size=32) When I run this code using CPU as with tf.device('/cpu:0'), the code runs fine completing all the epochs. Please note my laptop support NVIDIA GeForce GT 750M. I have installed tensorflow-gpu version 1.9.0',cuda9.2 along with NVIDIA cuDNN. When I run the same code with GPU using tf.device('/gpu:0') its breaks even in the first epoch generating error. Any comments are appreciate spent a lot of time but could not sort it out. The error is given below: InvalidArgumentError: Input to reshape is a tensor with 991232 values, but the requested shape requires a multiple of 1048701955 [[Node: flatten_3/Reshape = Reshape[T=DT_FLOAT, Tshape=DT_INT32, _class=["loc:@training_3…
has comment: http://stackoverflow.com/comment/91326371
tagged with: tensorflow
type: Question
has comment: http://stackoverflow.com/comment/91166026
score: 1
has comment: http://stackoverflow.com/comment/91086969
has title: TensorFlow Error on GPU:InvalidArgumentError: Input to reshape is a tensor with 991232 values
has comment: http://stackoverflow.com/comment/91093915

http://stackoverflow.com/comment/91262991
type: QuestionComment
comment on: http://stackoverflow.com/q/52063264
has text: @ImportanceOfBeingErnest I have edited the question and the code also.
score: 0
type: Comment

http://stackoverflow.com/comment/90896955
score: 2
type: Comment
type: QuestionComment
has text: Would be helpful to add the expected output as well.
comment on: http://stackoverflow.com/q/51973153

http://stackoverflow.com/a/52052524
has body: You can change your item relation to ForeignKey class Item(AppModel): title = models.CharField(max_length=255) units = models.ForeignKey(Unit, related_name="items") Update Set your invoice model between Unit and Item. class Item(AppModel): units = models.ManyToManyField(Unit, through='Invoice') class Unit(AppModel): ... class Invoice(AppModel): item = models.ForeignKey(Item, related_name='invoice') unit = models.ForeignKey(Unit, related_name='invoice')
has comment: http://stackoverflow.com/comment/91056029
has comment: http://stackoverflow.com/comment/91055729
has comment: http://stackoverflow.com/comment/91057576
has comment: http://stackoverflow.com/comment/91056861
has comment: http://stackoverflow.com/comment/91055287
answers question: http://stackoverflow.com/q/52051802
type: Answer
has comment: http://stackoverflow.com/comment/91056003
score: 0

http://stackoverflow.com/a/52072798
has body: Convert column to numeric by Series.astype: print(df[df['coln1'].astype(int)&gt;2]) More general solution if some non numeric values, which are converted to NaNs by to_numeric and parameter errors='coerce': print(df[pd.to_numeric(df['coln1'], errors='coerce')&gt;2])
type: Answer
upvote count: 2
accepted answer of: http://stackoverflow.com/q/52072787
score: 2
answers question: http://stackoverflow.com/q/52072787
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/52085573
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91133948
has body: I currently have a dictionary that has capital letters as the keys and a list as the values. The list has a description at [0] and a variable name which points to another dictionary at [1]. categories = {'A': ('Song Language', song_language), 'B': ('Rythm/Genre', rythm_genre), 'D': ('Atributes', atributes), 'E': ('Region', region) } song_language = { 'A1': 'Spanish', 'A2': 'English', 'A3': 'Spanglish', 'A4': 'Non S&amp;E', } In the case of categories['A'][1]['A2'] it equals English. Neither of these dictionaries are finalized, meaning I am constantly updating them to add entries. It gets very tedious having to: Create additional dictionaries Modify existing dictionaries The use for the dictionaries is to loop through them. First, Loop through the categories dictionary and in a nested manner, I loop through the dictionary contained in the [1] of the list. Each time, I collect input to determine if I am to add the key of the nested dictionary to a list. if user enters 'YL' or 'NL' the script will take some actions and then move on to the next dictionary. for category_key in categories: next_dict = categories[category_key][1] dict_desc = categories[category_key][0] print(dict_desc, ": ", next_dict) for attribute in next_dict: prompt = "\tIs this song == "+next_dict[attribute]+"("+attribute+"): " add_to_list = input(prompt).upper() while add_to_list not in ('Y', 'YL', 'NN','NL','N'): prompt = "Is this song == " + next_dict[attribute] + "(" + attribute + "): " add_to_list = input(prompt).upper() if add_to_list == 'Y': comment_list.append(attribute) elif add_to_list == 'YL': comment_list.append(attribute) break elif add_to_list == 'NN': continue elif add_to_list == 'NL': break elif add_to_list == 'N': this_prompt = '\t\tDo you want to set any more '+dict_desc+' attributes: ' any_more = input(this_prompt).upper() if any_more == 'Y': continue elif any_more == 'N': break Again, my aim is to move my dictionaries out of my program and finding a more efficient way to creating a…
has answer: http://stackoverflow.com/a/52104418
type: Question
has comment: http://stackoverflow.com/comment/91160002
has title: Simplifying dynamic dictionary creation and looping through it
has comment: http://stackoverflow.com/comment/91121570
score: 0
answer count: 1
accepted answer: http://stackoverflow.com/a/52104418
has comment: http://stackoverflow.com/comment/91121644
tagged with: python
tagged with: dictionary

http://stackoverflow.com/comment/90964275
type: Comment
type: QuestionComment
has text: @KlausD. is it possible that the process crashes and another process pick up the same pid?
comment on: http://stackoverflow.com/q/51996912
score: 0

http://stackoverflow.com/comment/91081452
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52011147
has text: Haha, yes it is. I will ask a separate question then. Thank you for leading me in the right direction!

http://stackoverflow.com/q/52040538
has body: I am creating a QListView and QStandardItemModel using this code: self.listView = QtWidgets.QListView(self.groupBox2) self.listView.setGeometry(QtCore.QRect(200, 20, 400, 220)) self.entry = QtGui.QStandardItemModel() I am adding items in a loop using something similar to: self.item1 = QtGui.QStandardItem("Itemname1") self.entry.appendRow(self.item1) self.item2 = QtGui.QStandardItem("Itemname2") self.entry.appendRow(self.item2) How can I assign those items to a list knowing 0 in the list stands for "Itemname1", 1 stands for "Itemname2" etc.? Also, how can I set an item in the QListView as selected? setSelected() doesn't seem to exist for QStandardItemModel
answer count: 2
has answer: http://stackoverflow.com/a/52043663
tagged with: pyqt
downvote count: 0
tagged with: qlistview
tagged with: qstandarditemmodel
favorite count: 0
type: UnansweredQuestion
has title: Get selected index in QListView using QStandardItemModel
tagged with: python
score: 2
upvote count: 2
tagged with: pyqt5
type: Question
has answer: http://stackoverflow.com/a/52044221

http://stackoverflow.com/q/52036195
accepted answer: http://stackoverflow.com/a/52036451
has comment: http://stackoverflow.com/comment/91023040
has comment: http://stackoverflow.com/comment/91022934
has comment: http://stackoverflow.com/comment/91022841
has body: Here is this block of code I'm trying to finish: elif parameter == 'statistics': outfile.write(stats(infile)) for line in infile: outfile.write(line) So essentially, I am trying to write the statistics of the file into the new file that is being copied. The statistics works and everything as when I open the file, the statistics are written in. However, I noticed because of the two outfile.write it seems to close after the first one, so only the statistics go in and not the rest of the content in the original file. The error that I am getting is this: ValueError: I/O operation on closed file. I am unsure why the file is closing. EDIT: Here is the whole code, as requested def copy_file(): infile_name = input("Please enter the name of the file to copy: ") infile = open(infile_name, 'r', encoding='utf8') parameter = input("Please enter a parameter(line numbers, Gutenberg trim, statistics, none): ") outfile_name = input("Please enter the name of the new copy: ") outfile = open(outfile_name, 'w', encoding='utf8') counter = 1 if parameter == 'line numbers': for line in infile: outfile.write(f' {counter:6}: {line}') counter += 1 elif parameter == 'Gutenberg trim': copyStart = False for line in infile: #print(line.strip()) if '*** START' in line.strip(): copyStart = True continue elif '*** END' in line.strip(): copyStart = False break if copyStart == True: outfile.write(line) elif parameter == 'statistics': outfile.write(stats(infile)) for line in infile: outfile.write(line) else: for line in infile: outfile.write(line) infile.close() outfile.close() copy_file() EDIT2: So sorry for not including it. Here is the stats function: def stats(text) -&gt; str: with text as infile: totallines = 0 emplines = 0 characters = 0 for line in infile: totallines += 1 characters += len(line) if len(line.strip()) == 0: emplines += 1 lines = totallines - emplines totalaveChars = characters/totallines nonempaveChars = characters/lines result = (f'{totallines:5} lines in list \n' f'{emplines:5} …
has title: My file keeps on being closed after .write()
has comment: http://stackoverflow.com/comment/91022605
tagged with: python
possible better answer: http://stackoverflow.com/a/52036352
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91022706
has answer: http://stackoverflow.com/a/52036352
has comment: http://stackoverflow.com/comment/91022491
has answer: http://stackoverflow.com/a/52037660
has comment: http://stackoverflow.com/comment/91022685
has comment: http://stackoverflow.com/comment/91022540
type: Question
has comment: http://stackoverflow.com/comment/91022716
has comment: http://stackoverflow.com/comment/91022838
has answer: http://stackoverflow.com/a/52036451
has comment: http://stackoverflow.com/comment/91022717
score: 0
answer count: 3

http://stackoverflow.com/comment/91080248
comment on: http://stackoverflow.com/q/52064521
score: 0
type: Comment
type: QuestionComment
has text: @Andrew, yes that is precisely what I'm asking for.

http://stackoverflow.com/comment/91048991
type: QuestionComment
comment on: http://stackoverflow.com/q/52049128
type: Comment
score: 1
has text: What do you mean doesn't work (Py3) - prints `0..9` for me, but this is an *awful* use of a generator and you shouldn't do it. If you are using Py2, then `from __future__ import print_function`

http://stackoverflow.com/comment/91122262
score: 0
has text: You can try using js2xml: https://github.com/scrapinghub/js2xml to parse the JS code for you.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52085907

http://stackoverflow.com/comment/91007571
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52028493
has text: Is that supposed to be your complete output? In which case it seems like you should be using a serializer on the User model, not on Following; you can restrict the users to those following the target in your `get_queryset` method.

http://stackoverflow.com/q/52087192
possible better answer: http://stackoverflow.com/a/52087221
type: Question
tagged with: numpy
has answer: http://stackoverflow.com/a/52087221
downvote count: 0
favorite count: 0
tagged with: type-conversion
has body: Starting from a list of floats, i.e. register = [11, 12, 13, 23, 24, 34] I would like to generate symmetric matrices where elements of the diagonal equal to zero, i.e. [[ 0. 11. 12. 13.] [ 11. 0. 23. 24.] [ 12. 23. 0. 34.] [ 13. 24. 34. 0.]] So I opted for creating a zero with dimension 4 x 4 then to be filled with the elements of my list. After setting a progress indicator and considering an offset to not overwrite the zeroes of the diagonal, I then would either move to east (or south) until the number of previously determined steps to reach the limit of the matrix were consumed. After incrementing of the progress and reset of the initial step counter, I could enter the next column (line) to proceed further. However, I erred in my present code (at least once -- it is my first contact with numpy) and harvest only [[ 0. 11. 12. 13.] [ 11. 0. 23. 0.] [ 12. 23. 0. 0.] [ 13. 0. 0. 0.]] My code: import numpy as np dimension = 4 # other matrices' dimensions will be larger matrix = np.zeros((dimension,dimension)) register = [11, 12, 13, 23, 24, 34] progress = 0 inner_step = 0 i = 0 for progress in range(0, (dimension + 1)): permitted_steps = dimension - progress for i in range(progress, permitted_steps-1): matrix[(progress, inner_step+1+offset)] = register[0] matrix[(inner_step+1+offset, progress)] = register[0] inner_step += 1 del register[0] progress += 1 inner_step = 0 offset += 1 The targeted environment used is Python 2.7 (Continuum Anaconda) for Windows.
has answer: http://stackoverflow.com/a/52087907
answer count: 4
upvote count: 2
tagged with: python
score: 2
type: AnsweredQuestion
has title: list to matrix conversion with numpy
has answer: http://stackoverflow.com/a/52087233
accepted answer: http://stackoverflow.com/a/52087907
has answer: http://stackoverflow.com/a/52087231

http://stackoverflow.com/q/52037323
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/75870059
linked to: http://stackoverflow.com/q/7922487
has answer: http://stackoverflow.com/a/55027168
has title: how to convert sparse matrix array to json python
tagged with: http://stackoverflow.com/tag/json
type: Question
upvote count: 2
answer count: 2
tagged with: sparse-matrix
has body: I'm trying to convert TF-IDF sparse matrix to json format. Converting it to pandas datafram (toarray() or todense()) causes memory error. So I would like to avoid those approaches. Is there other way to convert it to json ? Below is my appraoach to get sparse matrix, and my preferred json outcome Thanks for helping me out ... ! TF-IDF matrix pip = Pipeline([('hash', HashingVectorizer(ngram_range=(1, 1), non_negative=True)), ('tfidf', TfidfTransformer())]) result_uni_gram = pip.fit_transform(df_news_noun['content_nouns']) return matrix result_uni_gram &lt;112537x1048576 sparse matrix of type '&lt;class 'numpy.float64'&gt;' with 12605888 stored elements in Compressed Sparse Row format&gt; print(result_uni_gram) (0, 1041232) 0.03397010691200069 (0, 1035546) 0.042603425242006505 (0, 1031141) 0.05579563771771019 (0, 1029045) 0.03985981185871279 (0, 1028867) 0.14591155976555212 (0, 1017328) 0.03827279930970525 : : (112536, 9046) 0.04444360144902461 (112536, 4920) 0.07335227778871069 (112536, 4301) 0.06667794684006756 Expecting Outcome output_json = { 0: {1041232 : 0.03397, 1035546 : 0.04260, 1031141 : 0.055795 ... }, ... ... 112536: {9046 : 0.04444, 4920 : 0.07335, 112536 : 0.06667} } Thanks for helping me out ... !
tagged with: tf-idf
tagged with: matrix
tagged with: python
favorite count: 0
score: 2
downvote count: 0

http://stackoverflow.com/comment/90996523
comment on: http://stackoverflow.com/q/52023058
type: Comment
has text: @AChampion Judging by the choice of the example word "bookkeeper", the permutations are unique permutations.
type: QuestionComment
score: 0

http://stackoverflow.com/q/52071642
type: AnsweredQuestion
downvote count: 0
tagged with: shutil
favorite count: 0
tagged with: include
linked to: http://stackoverflow.com/q/18371768
type: Question
has answer: http://stackoverflow.com/a/52072685
linked to: http://stackoverflow.com/q/42487578
has comment: http://stackoverflow.com/comment/91093099
answer count: 2
has body: I need to copy the files with include pattern using python script. Since shutil supports ignore_patterns to ignore the file. Is there any method to include the pattern to copy the files. Otherwise do I have to write the code explicitly?. Thanks in advance EDIT from shutil import copytree, ignore_patterns source=r'SOURCE_PATH' destination=r'DESTINATION_PATH' copytree(source, destination, ignore=ignore_patterns('*.txt')) The above code copied the files from dir except specified format, But I need something like this below from shutil import copytree, include_patterns source=r'SOURCE_PATH' destination=r'DESTINATION_PATH' copytree(source, destination, ignore=include_patterns('*.txt'))
tagged with: python
tagged with: design-patterns
upvote count: 6
has comment: http://stackoverflow.com/comment/91093365
accepted answer: http://stackoverflow.com/a/52072685
has comment: http://stackoverflow.com/comment/91093256
possible better answer: http://stackoverflow.com/a/52071926
has answer: http://stackoverflow.com/a/52071926
tagged with: copy
score: 6
has title: python copying the files with include pattern

http://stackoverflow.com/a/52002828
type: Answer
answers question: http://stackoverflow.com/q/52002733
score: 0
has body: from matplotlib docs: add_subplot(*args, **kwargs)[source] Add a subplot. Call signatures: add_subplot(nrows, ncols, index, **kwargs) add_subplot(pos, **kwargs) As far as I can tell you are not providing the index argument to the function.

http://stackoverflow.com/a/51995217
answers question: http://stackoverflow.com/q/51995179
has comment: http://stackoverflow.com/comment/90940276
upvote count: 1
has body: You can zip those lists together so each pair (list1, list2) is treated as single row: import csv list1 = ['Steve', 'Mark', 'Jeff'] list2 = ['steve@mac.com', 'mark223@mac.com', 'jeffrey@mac.com'] with open('output.csv','w') as f: writer = csv.writer(f) writer.writerows(zip(list1,list2)) Sample output: $ cat output.csv Steve,steve@mac.com Mark,mark223@mac.com Jeff,jeffrey@mac.com If you need your output to be space or tab separated (instead of comma), you can specify it as a parameter to csv.writer. For example: import csv list1 = ['Steve', 'Mark', 'Jeff'] list2 = ['steve@mac.com', 'mark223@mac.com', 'jeffrey@mac.com'] with open('output.csv','w') as f: writer = csv.writer(f, delimiter='\t') writer.writerows(zip(list1,list2)) Produces: $ cat output.csv Steve steve@mac.com Mark mark223@mac.com Jeff jeffrey@mac.com
type: Answer
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/90940266
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/51995179

http://stackoverflow.com/comment/91015000
type: QuestionComment
comment on: http://stackoverflow.com/q/52032329
has text: I think the example answer does a decent job of illustrating the expected outcome
score: 0
type: Comment

http://stackoverflow.com/comment/91159650
has text: There are several unrelated questions here. Which type of similarity is appropriate; how to calculate something in pandas; and how to plot certain things. Please try to restrict questions to a single problem.
score: 0
comment on: http://stackoverflow.com/q/52102217
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91012733
type: AnswerComment
has text: @Divakar both are working! I'll do some more benchmarking and probably go with first one, since it's shorter and easier to understand.
type: Comment
comment on: http://stackoverflow.com/a/52030534
score: 1

http://stackoverflow.com/a/52014857
upvote count: 2
type: Answer
answers question: http://stackoverflow.com/q/52014741
score: 2
downvote count: 0
has body: If I understood you correctly, you can do this two ways: by using the re module here mystring = 'Hello,Joe' mystring = re.sub(",", "", mystring) 2 Or simply: mystring = 'Hello,Joe' mystring = mystring.replace(",", "") Welcome to Stack Overflow! Please be more clear in future with questions. I would suggest reading this to help you with understanding the process of creating a clear question.

http://stackoverflow.com/q/52022362
has comment: http://stackoverflow.com/comment/90995114
tagged with: python-3.x
tagged with: python
type: AnsweredQuestion
has body: When slicing a numpy array we obtain a view on the corresponding data. However that doesn't seem to be the case with sparse matrices from scipy.sparse. Although the docs briefly mention slicing for the lil_matrix class it's not clear how (or if) one can obtain views on the data. At least by using the following sample script I wasn't successful in obtaining views of sparse matrices: import numpy as np from scipy.sparse import lil_matrix def test(matrix): print('\n=== Testing {} ==='.format(type(matrix))) a = matrix[:, 0] b = matrix[0, :] a[0] = 100 M[0, 1] = 200 M[1, 0] = 200 print('a = '); print(a) print('b = '); print(b) M = np.arange(4).reshape(2, 2) + 1 S = lil_matrix(M) test(M) test(S) Which outputs: === Testing &lt;class 'numpy.ndarray'&gt; === a = [100 200] b = [100 200] === Testing &lt;class 'scipy.sparse.lil.lil_matrix'&gt; === a = (0, 0) 100 (1, 0) 3 b = (0, 0) 1 (0, 1) 2 Tested on Python 3.6.6, numpy==1.14.5, scipy==1.1.0.
tagged with: scipy
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/90995050
has comment: http://stackoverflow.com/comment/90995027
has answer: http://stackoverflow.com/a/52022423
accepted answer: http://stackoverflow.com/a/52022423
score: 0
has title: How to get views on sparse matrices?
answer count: 1

http://stackoverflow.com/q/52080024
tagged with: web-scraping
tagged with: scrapy
type: Question
tagged with: python-3.5
answer count: 1
downvote count: 0
has body: Hi I'm wondering how could I pass scraping result which is pandas file to module which created creating spider. import mySpider as mspider def main(): spider1 = mspider.MySpider() process = CrawlerProcess() process.crawl(spider1) process.start() print(len(spider1.result)) Spider: class MySpider(scrapy.Spider): name = 'MySpider' allowed_domains = config.ALLOWED_DOMAINS result = pd.DataFrame(columns=...) def start_requests(self): yield Request(url=...,headers=config.HEADERS, callback=self.parse) def parse(self, response): *...Some Code of adding values to result...* print("size: " + str(len(self.result))) Printed value in main method is 0 when in parse method is 1005. Could you tell me how should I pass value between. I would like to do that cause I'm running multiple spiders. After they finish scraping I'll merge and save to file. SOLUTION def spider_closed(spider, reason): print("Size" + str(len(spider.result))) def main(): now = datetime.now() spider1 = spider.MySpider() crawler_process = CrawlerProcess() crawler = crawler_process.create_crawler(spider1) crawler.signals.connect(spider_closed, signals.spider_closed) crawler_process.crawl(spider1) crawler_process.start()
favorite count: 0
has answer: http://stackoverflow.com/a/52080982
upvote count: 2
has title: Scrapy return/pass data to another module
tagged with: python
accepted answer: http://stackoverflow.com/a/52080982
score: 2
type: AnsweredQuestion

http://stackoverflow.com/a/52058548
has comment: http://stackoverflow.com/comment/91068752
upvote count: 1
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/52058437
type: Answer
has body: Replace n,q=(int(x) for x in input().split()) by print(list(int(x) for x in input().split())) to understand what you are unpacking here.

http://stackoverflow.com/comment/91164356
has text: Thank you, it seems that it can work but I am getting <KeyError: u"None of 'market', 'number_of_rooms' are in the [index]">. I tried .reset_index() at the drop_duplicates, but no success
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52106638

http://stackoverflow.com/a/51958422
answers question: http://stackoverflow.com/q/51958177
type: Answer
has body: Your figure has many subplots in it. You need to remove the ticks in each axis object of each subplot (or at least the ones you done want to appear). This can be done like this: import matplotlib.pyplot as plt ax1 = plt.subplot(321) # 1st subplot in 3-by-2 grid ax1.plot(...) # draw what you want ax1.set_xticks([], []) # note you need two lists one for the positions and one for the labels ax1.set_yticks([], []) # same for y ticks ax2 = plt.subplot(321) # 2nd subplot in the same grid # do the same thing for any subplot you want the ticks removed If you want the whole axis (borders, ticks and labels) removed you can just do this: ax1.axis('off') However I'd suggest typing plt.tight_layout(). It might fix your problem without requiring you to remove the ticks.
score: 5
upvote count: 5
has comment: http://stackoverflow.com/comment/90996502
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51958177

http://stackoverflow.com/comment/91020782
has text: Hi @JezreelMartin, It is static main function that starts the application loop. And same way kivy.base.stopTouchApp() will stop the current application by leaving the main loop.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52033491
type: Comment

http://stackoverflow.com/comment/90925486
type: Comment
has text: I use `assign` a lot because it creates a new copy of the dataframe. From what I've written, you can reassign to the name `df`... so `df = df.assign(New_Variable=df.Category.str.extract('(Bonds|Stocks)'))`
type: AnswerComment
comment on: http://stackoverflow.com/a/51987922
score: 0

http://stackoverflow.com/q/52084275
duplicate of: http://stackoverflow.com/q/45621722
has comment: http://stackoverflow.com/comment/91119037
linked to: http://stackoverflow.com/q/23294658
has comment: http://stackoverflow.com/comment/91118965
type: AnsweredQuestion
favorite count: 0
tagged with: python-3.x
type: Question
downvote count: 2
tagged with: input
tagged with: python
score: -2
has answer: http://stackoverflow.com/a/52084376
answer count: 1
duplicate of: http://stackoverflow.com/q/23294658
has body: im really new in Python 3.7 im testing some stuff out, and i try to understand how can i ask someone his age. but if he enter a letter or a negative number it say, only positive number please then it ask the question again, if the number is positive then the program continue. here is my code so far giving me an error: while true : age = input('Your age : ') try: age = int(age) except ValueError: print ('Numbers only') continue else: break giving me as error : , &gt; line 10 age = input() ^ SyntaxError: expected an indented block
has title: How to use input() to only accept positive numbers as int,
has comment: http://stackoverflow.com/comment/91119007
has comment: http://stackoverflow.com/comment/91119106
upvote count: 0
accepted answer: http://stackoverflow.com/a/52084376
has comment: http://stackoverflow.com/comment/91118995

http://stackoverflow.com/comment/91028385
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/52038317
has text: @roganjosh Basically if I put in my hostfiles 127.0.0.1 www.example.com everytime I connect to example.com it goes to localhost I only want it to go to localhost if I'm connecting on a certain port.

http://stackoverflow.com/q/52062896
has comment: http://stackoverflow.com/comment/91076633
tagged with: python
downvote count: 1
type: AnsweredQuestion
tagged with: list
has comment: http://stackoverflow.com/comment/91076670
has comment: http://stackoverflow.com/comment/91076148
has title: String in list into list, python
has comment: http://stackoverflow.com/comment/91076694
type: Question
has answer: http://stackoverflow.com/a/52063223
upvote count: 0
answer count: 1
has body: I know it's a pretty easy question, but I'm new in Python and need your help. I have a list: ['232','43','1, 2, 3','5'] And I need to get: ['232','43','1','2','3','5'] That string with commas could be in any position in the list and I don't know how many such strings are present (the number of such strings may be changed). But in the string with commas there will always be exactly a single space after the comma, and there will never be a comma at the end of the string. What is the easiest way to do that?
score: -1
has comment: http://stackoverflow.com/comment/91076805
has comment: http://stackoverflow.com/comment/91076480
has comment: http://stackoverflow.com/comment/91076104
has comment: http://stackoverflow.com/comment/91076155
tagged with: string
duplicate of: http://stackoverflow.com/q/45465661
has comment: http://stackoverflow.com/comment/91076594
favorite count: 0
accepted answer: http://stackoverflow.com/a/52063223
has comment: http://stackoverflow.com/comment/91076194
has comment: http://stackoverflow.com/comment/91076257
has comment: http://stackoverflow.com/comment/91076384
has comment: http://stackoverflow.com/comment/91076245

http://stackoverflow.com/comment/91124652
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52071283
type: AnswerComment
has text: @VivekKumar they coefficient and intercept are the same

http://stackoverflow.com/a/52101781
has body: I found out that the COS S3 client is either reading the HMAC credentials from the IBM Cloud config directory or you have to pass them under different name: cos = ibm_boto3.client('s3', myserviceapikey, endpoint_url=myendpointurl, aws_access_key_id=config["cos_hmac_keys"]["access_key_id"], aws_secret_access_key=config["cos_hmac_keys"]["secret_access_key"]) Basically, I have to map cos_hmac_keys.access_key_id to aws_access_key_id and cos_hmac_keys.secret_access_key to aws_secret_access_key. With that COS client initialized, then I can create the presigned URI: theURL=cos.generate_presigned_url('get_object', Params = {'Bucket': mybucket, 'Key': myobject}, ExpiresIn = 600)
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/91156606
answers question: http://stackoverflow.com/q/52100561
accepted answer of: http://stackoverflow.com/q/52100561
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/91156768
type: Answer

http://stackoverflow.com/comment/91010370
has text: Welcome on SO. Can you be more specific about the problem you have? What do you do (exact commands), what do you expect and what do you get (error messages, program output etc) instead?
comment on: http://stackoverflow.com/q/52029968
type: Comment
type: QuestionComment
score: 2

zlib
tags question: http://stackoverflow.com/q/52098208
tag name: zlib
type: Tag

http://stackoverflow.com/a/52096595
type: Answer
has body: Your document has namespaces on nodes school and student, you need to incorporate the namespaces in your search. Since you are looking for ca1, which is under student, you will need to specify the namespace that student node has: import xml.etree.ElementTree as ET tree = ET.parse('mca.xml') root = tree.getroot() def getElementsData(xpath, namespaces): elements = root.findall(xpath, namespaces) if elements == []: raise SystemExit("Invalid xpath provided") return elements namespaces = {'ns_school': 'loyo:22:2.2', 'ns_student': 'loyo:5:542'} elements = getElementsData('.//ns_student:ca1', namespaces) for element in elements: print(element) Notes Since your namespaces have no names, I gave them such names as ns_school, ns_student, but these name can be anything (e.g. ns1, mystudent, ...) In a more complex system, I recommend raising some other kinds of errors and let the caller decide whether or not to exit.
score: 1
upvote count: 1
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/52096071
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52096071

http://stackoverflow.com/q/52065865
has title: How to run git pull from subprocess
score: 0
has answer: http://stackoverflow.com/a/52066204
tagged with: python
has comment: http://stackoverflow.com/comment/91082658
linked to: http://stackoverflow.com/q/8475694
has comment: http://stackoverflow.com/comment/91082274
type: UnansweredQuestion
tagged with: git
has comment: http://stackoverflow.com/comment/91083454
has comment: http://stackoverflow.com/comment/91082277
type: Question
answer count: 1
has comment: http://stackoverflow.com/comment/91082695
has comment: http://stackoverflow.com/comment/91083488
has body: I am trying to run a subprocess command to do a git pull. The cwd of the Git repository is /home/ubuntu/Ingest. The id_rsa that I'm using with Github is located at /home/ubuntu/.ssh/id_rsa. How would I run a subprocess call to do the following? import shlex, subprocess subprocess.call(shlex.split('git pull origin master'), cwd='/home/ubuntu/Ingest') The log looks like: movies_ec2.py:43@__init__ [INFO] Version not up to date...Doing a git pull and exiting... Permission denied (publickey). fatal: Could not read from remote repository. Please make sure you have the correct access rights and the repository exists. The script is running from cron and is not picking up on the id_rsa. (Note: I am not looking to use GitPython). What do I need to change in my cron job or script so that this will work? My cron job is currently: # sudo crontab -e */1 * * * * STAGE=production /home/ubuntu/Ingest/ingest/movies_ec2.py &gt; /home/ubuntu/test.log 2&gt;&amp;1

machine-learning
tags question: http://stackoverflow.com/q/52067100
tags question: http://stackoverflow.com/q/52039141
tags question: http://stackoverflow.com/q/52015499
tags question: http://stackoverflow.com/q/51958745
tags question: http://stackoverflow.com/q/52106723
tags question: http://stackoverflow.com/q/52084911
tags question: http://stackoverflow.com/q/52072821
tags question: http://stackoverflow.com/q/51991569
tags question: http://stackoverflow.com/q/52018645
tags question: http://stackoverflow.com/q/52087578
tags question: http://stackoverflow.com/q/52075519
tags question: http://stackoverflow.com/q/51959370
tags question: http://stackoverflow.com/q/52076415
tags question: http://stackoverflow.com/q/52050990
tags question: http://stackoverflow.com/q/51963377
tags question: http://stackoverflow.com/q/52014867
tags question: http://stackoverflow.com/q/51972647
tags question: http://stackoverflow.com/q/51995977
tags question: http://stackoverflow.com/q/51998587
tags question: http://stackoverflow.com/q/52008294
tags question: http://stackoverflow.com/q/51994344
tags question: http://stackoverflow.com/q/51964385
tags question: http://stackoverflow.com/q/52068525
tags question: http://stackoverflow.com/q/51987877
tags question: http://stackoverflow.com/q/51986706
tags question: http://stackoverflow.com/q/52088807
tags question: http://stackoverflow.com/q/52059294
tags question: http://stackoverflow.com/q/52042439
tags question: http://stackoverflow.com/q/51968293
tags question: http://stackoverflow.com/q/52109730
tags question: http://stackoverflow.com/q/52012252
tags question: http://stackoverflow.com/q/52028149
tags question: http://stackoverflow.com/q/52063402
tags question: http://stackoverflow.com/q/52073964
tags question: http://stackoverflow.com/q/52020536
tags question: http://stackoverflow.com/q/52073938
tags question: http://stackoverflow.com/q/51960225
tags question: http://stackoverflow.com/q/52106298
tags question: http://stackoverflow.com/q/52032019
tags question: http://stackoverflow.com/q/52053691
tags question: http://stackoverflow.com/q/52009816
tags question: http://stackoverflow.com/q/52075125
tags question: http://stackoverflow.com/q/52093388
tags question: http://stackoverflow.com/q/52096970
tag name: machine-learning
tags question: http://stackoverflow.com/q/52109738
tags question: http://stackoverflow.com/q/52028474
tags question: http://stackoverflow.com/q/51973147
tags question: http://stackoverflow.com/q/52072522
tags question: http://stackoverflow.com/q/52051348
tags question: http://stackoverflow.com/q/52024917
tags question: http://stackoverflow.com/q/52008233
tags question: http://stackoverflow.com/q/52060483
tags question: http://stackoverflow.com/q/52063668
tags question: http://stackoverflow.com/q/51965203
tags question: http://stackoverflow.com/q/52083841
tags question: http://stackoverflow.com/q/51968669
tags question: http://stackoverflow.com/q/52048171
type: Tag
tags question: http://stackoverflow.com/q/52057836
tags question: http://stackoverflow.com/q/51982990
tags question: http://stackoverflow.com/q/52055072
tags question: http://stackoverflow.com/q/52019808
tags question: http://stackoverflow.com/q/51968894
tags question: http://stackoverflow.com/q/52012077
tags question: http://stackoverflow.com/q/52067784
tags question: http://stackoverflow.com/q/52066593
tags question: http://stackoverflow.com/q/51968769
tags question: http://stackoverflow.com/q/52093695
tags question: http://stackoverflow.com/q/52065812
tags question: http://stackoverflow.com/q/52033171
tags question: http://stackoverflow.com/q/52069367
tags question: http://stackoverflow.com/q/52063286
tags question: http://stackoverflow.com/q/52034983
tags question: http://stackoverflow.com/q/51966783
tags question: http://stackoverflow.com/q/52068364
tags question: http://stackoverflow.com/q/52044361
tags question: http://stackoverflow.com/q/51998226
tags question: http://stackoverflow.com/q/51992098
tags question: http://stackoverflow.com/q/52095862

http://stackoverflow.com/comment/91039908
has text: @KiruparanBalachandran I think you correctly got What I was looking for.. but le me do a test ..
type: Comment
comment on: http://stackoverflow.com/a/52044073
score: 0
type: AnswerComment

http://stackoverflow.com/comment/91162820
type: Comment
type: QuestionComment
has text: I think instead of `ax5.plot(..., ax=ax5)` you want to write `funnel.plot(..., ax=ax5)`.
comment on: http://stackoverflow.com/q/52105356
score: 0

http://stackoverflow.com/a/52066540
downvote count: 0
score: 1
accepted answer of: http://stackoverflow.com/q/52066502
answers question: http://stackoverflow.com/q/52066502
has body: Method 1: Generating desired array from file If you are starting from a csv, you might as well just use np.genfromtxt: If filename.csv looks like: 39, State-gov, 77516, Bachelors, 13, Never-married, Adm-clerical, Not-in-family, White, Male, 2174, 0, 40, United-States, &lt;=50K 50, Self-emp-not-inc, 83311, Bachelors, 13, Married-civ-spouse, Exec-managerial, Husband, White, Male, 0, 0, 13, United-States, &lt;=50K Then: new_arr = np.genfromtxt('filename.csv', dtype='str') &gt;&gt;&gt; new_arr array([['39,', 'State-gov,', '77516,', 'Bachelors,', '13,', 'Never-married,', 'Adm-clerical,', 'Not-in-family,', 'White,', 'Male,', '2174,', '0,', '40,', 'United-States,', '&lt;=50K'], ['50,', 'Self-emp-not-inc,', '83311,', 'Bachelors,', '13,', 'Married-civ-spouse,', 'Exec-managerial,', 'Husband,', 'White,', 'Male,', '0,', '0,', '13,', 'United-States,', '&lt;=50K']], dtype='&lt;U19') Method 2: Fixing your array: Otherwise, if you already have the array: &gt;&gt;&gt; arr array(['39, State-gov, 77516, Bachelors, 13, Never-married, Adm-clerical, Not-in-family, White, Male, 2174, 0, 40, United-States, &lt;=50K', '50, Self-emp-not-inc, 83311, Bachelors, 13, Married-civ-spouse, Exec-managerial, Husband, White, Male, 0, 0, 13, United-States, &lt;=50K'], dtype='&lt;U133') You can iterate through it and split each string to get the output you want: new_arr = np.array([i.split() for i in arr]) &gt;&gt;&gt; new_arr array([['39,', 'State-gov,', '77516,', 'Bachelors,', '13,', 'Never-married,', 'Adm-clerical,', 'Not-in-family,', 'White,', 'Male,', '2174,', '0,', '40,', 'United-States,', '&lt;=50K'], ['50,', 'Self-emp-not-inc,', '83311,', 'Bachelors,', '13,', 'Married-civ-spouse,', 'Exec-managerial,', 'Husband,', 'White,', 'Male,', '0,', '0,', '13,', 'United-States,', '&lt;=50K']], dtype='&lt;U19')
upvote count: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/91083737
type: Answer
has comment: http://stackoverflow.com/comment/91083728

http://stackoverflow.com/q/52074332
tagged with: pandas
score: 3
tagged with: python
type: AnsweredQuestion
tagged with: python-3.x
tagged with: list
upvote count: 3
type: Question
has comment: http://stackoverflow.com/comment/91098401
has answer: http://stackoverflow.com/a/52076467
has title: Group list of numpy arrays based on shape. Pandas?
tagged with: numpy
downvote count: 0
answer count: 1
has body: I have some instances of a class containing numpy arrays. import numpy as np import os.path as osp class Obj(): def_init__(self, file): self.file = file self.data = np.fromfile(file) self.basename = osp.basename(file) I have a list of such objects, which I want to group by shape. I can do that using sort: obj_list = [obj1, obj2, ..., objn] obj_list.sort(key=lambda obj: obj.data.shape) Now I have a second list, say obj_list_2: objects in obj_list_2 are initialized from different files but the resulting arrays have the same shape as in the first one (but not in the same order) and also the basenames are the same. To clarify these are files loaded from different folders. In every folder I have the same files to which I applied different preprocessing) If I sort them using the method shown above I can end up having I want the two lists sorted based on shape and also aligned according to their basename I though about doing first a sort based on the shape followed by one based on basename (of a function of it). Something like obj_list.sort(key=lambda obj: obj.data.shape) obj_list.sort(key=lambda obj: obj.basename) However the second sort might screw the first one. They should be done together, somehow. My final goal is to extract from the two lists the objects having the same shape and having the same basename I tried with pandas but I'm not that familiar with it. First I align them based on the basename, then I create a list of lists and pass it to pandas. import pandas as pd obj_list_of_list = [obj_list1, obj_list2] obj_df = pd.DataFrame.from_records(obj_list_of_list) What is missing is to group them by shape and extract the different groups.
favorite count: 0
accepted answer: http://stackoverflow.com/a/52076467

http://stackoverflow.com/comment/91165608
has text: Why not include your checkdir() listing? It makes a better example. Also, why does not checkdir take an arguement? Perhaps you can live with no mock at all and no hidden global state.
score: 0
type: Comment
comment on: http://stackoverflow.com/q/52085969
type: QuestionComment

http://stackoverflow.com/comment/91118243
type: AnswerComment
type: Comment
has text: Sorry, I thought it's obvious by the plot: the graphing code is the identical copy of the one posted in the question - except the last line which plots the vertical line. This one is replaced by the described version. In the general case additionally by the lambda definition.
comment on: http://stackoverflow.com/a/52059472
score: 0

http://stackoverflow.com/comment/90993283
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52021156
type: Comment
has text: You need to give the logs of the error for us to be able to help. Depending on your version of Django, maybe replace `form = super(ReportCreate, self).get_form(form_class)` by `form = super().get_form(form_class)`

http://stackoverflow.com/comment/91170777
score: 0
type: Comment
type: QuestionComment
has text: @jezrael columns in dataframe A are printing has `string` in the list, while it seems to be just numbers in dataframe B. How can I change the `dtype` of columns?
comment on: http://stackoverflow.com/q/52109791

http://stackoverflow.com/q/52087652
has comment: http://stackoverflow.com/comment/91133857
upvote count: 2
type: UnansweredQuestion
tagged with: python
answer count: 0
linked to: http://stackoverflow.com/q/12302155
has title: pyserial reading max 4096 bytes at time, why?
type: Question
downvote count: 0
has body: I have a USB driver on an embedded system and I am pushing into the port 32k of data. However, when I read the data using pyserial it splits the data into 4k packets. It is a usb 2.0 and I don't want to recompose the data. here's how I am reading the data: data = serial.read(1) data += serial.read(serial.inWaiting()) if (len(data) &gt; 32): header_size = int(32) data_header = data[:header_size] #just show the first 32 characters of the data print("Packet size = " + str(len(data)) + "\n") print(str(data_header) + "\n") output: Packet size = 4096 AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA Packet size = 4096 BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB Packet size = 4096 CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC Packet size = 4096 DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD Packet size = 4096 DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD Packet size = 4096 EEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE Packet size = 4096 FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF Packet size = 4096 GGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGG It is a driver limitation or pyserial is splitting the data? Can this be configured? thank you.
tagged with: pyserial
score: 2
favorite count: 0

http://stackoverflow.com/q/52026406
type: Question
downvote count: 2
answer count: 2
duplicate of: http://stackoverflow.com/q/16940293
has comment: http://stackoverflow.com/comment/91003735
linked to: http://stackoverflow.com/q/35033985
upvote count: 6
score: 4
linked to: http://stackoverflow.com/q/16940293
has title: Are Python3.5 tuple comprehension really this limited?
favorite count: 0
tagged with: tuples
tagged with: python
possible better answer: http://stackoverflow.com/a/52026512
has answer: http://stackoverflow.com/a/52026512
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/91003064
has comment: http://stackoverflow.com/comment/91003443
linked to: http://stackoverflow.com/q/1756096
has body: I've been loving the tuple comprehensions added to Python3.5: In [128]: *(x for x in range(5)), Out[128]: (0, 1, 2, 3, 4) However, when I try to return a tuple comprehension directly I get an error: In [133]: def testFunc(): ...: return *(x for x in range(5)), ...: File "&lt;ipython-input-133-e6dd0ba638b7&gt;", line 2 return *(x for x in range(5)), ^ SyntaxError: invalid syntax This is just a slight inconvenience since I can simply assign the tuple comprehension to a variable and return the variable. However, if I try and put a tuple comprehension inside a dictionary comprehension I get the same error: In [130]: {idx: *(x for x in range(5)), for idx in range(5)} File "&lt;ipython-input-130-3e9a3eee879c&gt;", line 1 {idx: *(x for x in range(5)), for idx in range(5)} ^ SyntaxError: invalid syntax I feel like this is a bit more of a problem since comprehsions can be important for performance in some situations. I have no problem using dictionary and list comprehensions in these situations. How many other situations is the tuple comprehension not going to work when others do? Or perhaps I'm using it wrong? It makes me wonder what the point was if it's use is so limited or perhaps I am doing something wrong? If I'm not doing something wrong then what is the fastest/most pythonic way to create a tuple that is versitile enough to be used in the same way as list and dictionary comprehensions?
has answer: http://stackoverflow.com/a/52026510
accepted answer: http://stackoverflow.com/a/52026510
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91002975

http://stackoverflow.com/a/52073824
has body: It looks like you're trying to construct a json-encoder manually, this is unecessary since there's a great json-encoder built into python. I'd recommend building up your dict using the native data structre and use the builtin json-utilites. This will both produce cleaner more maintainable code and is less error prone. Like this: import json # ... Other imports you may have such as pandas path = "somewhere\on\my\disk\file.csv" # Initialize dict data = {"mainkey": "val1", "key2": list()} # Parse CSV file df1 = pd.read_csv(path, header=None) # iterate through csv for row,s in df1.iterrows(): number = df1.loc[row,0] # I'm reading keyb and keyc values from CSV as well, # but for brevity my substitution below is not showing that.... data['key2'].append({ "keya":number, "keyb":"whatever", "keyc":"whatever", }) # Print json to stdout/terminal json_data = json.dumps(data) print(json.dumps(data, sort_keys=True)) # Save json to file (data.json) with open("data.json", "w") as output: json.dump(data, output, sort_keys=True)
score: 2
has comment: http://stackoverflow.com/comment/91108856
accepted answer of: http://stackoverflow.com/q/52073574
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/52073574
has comment: http://stackoverflow.com/comment/91140321
has comment: http://stackoverflow.com/comment/91119855
type: Answer
upvote count: 2
has comment: http://stackoverflow.com/comment/91120724
has comment: http://stackoverflow.com/comment/91120630

http://stackoverflow.com/comment/90890570
has text: looking at the link you posted and the docs, `pyplot.tricontourf` doesnt seem to accept `vmin` and `vmax`. The way it was used in the example you posted is by using the `norm` argument: `plt.tricontourf(x, y, z,norm=plt.Normalize(vmax=abs(zi).max(), vmin=-abs(zi).max()))`
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51962576

http://stackoverflow.com/comment/90983343
comment on: http://stackoverflow.com/a/52016647
type: AnswerComment
has text: @UnbearableLightness And...? Why shouldn't it? How do you know that every number would fit that format?
score: 0
type: Comment

http://stackoverflow.com/q/51958667
type: Question
has title: Python 2.7 and Pyo, Server must be booted before creating any audio project
has comment: http://stackoverflow.com/comment/90869669
score: 2
has comment: http://stackoverflow.com/comment/90867830
downvote count: 0
has body: I am using Pyo (http://ajaxsoundstudio.com/software/pyo/) in Python 2.7.14 and I an trying to play an audio file with this code from pyo import * s = Server() s.boot() s.start() sf = SfPlayer("C:\Users\name\Downloads\audio.mp3", speed=1, loop=True).out() but I get this message: Traceback (most recent call last): File "C:\Python27\pyotest.py", line 5, in &lt;module&gt; sf = SfPlayer("C:\Users\name\Downloads\audio.mp3", speed=1, loop=True).out() File "C:\Python27\lib\site-packages\pyolib\players.py", line 98, in __init__ PyoObject.__init__(self, mul, add) File "C:\Python27\lib\site-packages\pyolib\_core.py", line 967, in __init__ PyoObjectBase.__init__(self) File "C:\Python27\lib\site-packages\pyolib\_core.py", line 809, in __init__ raise PyoServerStateException("The Server must be booted before " PyoServerStateException: The Server must be booted before creating any audio object.
tagged with: pyo
linked to: http://stackoverflow.com/q/32445375
answer count: 1
has answer: http://stackoverflow.com/a/53022760
favorite count: 0
upvote count: 2
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/114846052
tagged with: audio

http://stackoverflow.com/q/52037563
has comment: http://stackoverflow.com/comment/91025859
has comment: http://stackoverflow.com/comment/91026110
has comment: http://stackoverflow.com/comment/91026101
has comment: http://stackoverflow.com/comment/91025920
has comment: http://stackoverflow.com/comment/91025659
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/91049467
has comment: http://stackoverflow.com/comment/91026167
has comment: http://stackoverflow.com/comment/91026135
has comment: http://stackoverflow.com/comment/91025697
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91025500
tagged with: python
answer count: 0
has comment: http://stackoverflow.com/comment/91026438
tagged with: amazon-s3
has comment: http://stackoverflow.com/comment/91026159
score: 0
has title: Unable to access credentials in awscli for boto3 - Window 7
type: Question
has comment: http://stackoverflow.com/comment/91026267
has comment: http://stackoverflow.com/comment/91094571
has comment: http://stackoverflow.com/comment/91025808
tagged with: boto3
tagged with: amazon-web-services
has comment: http://stackoverflow.com/comment/91026124
has comment: http://stackoverflow.com/comment/91025894
has body: I have credentials and config in my .aws (its in home directory )with contents inside it. Still facing below issue while running code translate = boto3.client(service_name='translate', region_name='us-east-1', use_ssl=True) When doing below its throwing error ... translate.translate_text() botocore.exceptions.NoCredentialsError: ('Unable to locate credentials', 'occurred at index Unnamed: 0') When hardcoding , its working translate = boto3.client( service_name='translate', aws_access_key_id='XXX', aws_secret_access_key='XXXXX', region_name='us-east-1', use_ssl=True ) When working on mac I am not facing any issue .Only in Window I got stuck..

http://stackoverflow.com/q/52000326
type: Question
has comment: http://stackoverflow.com/comment/90949892
score: 0
upvote count: 1
answer count: 1
downvote count: 1
accepted answer: http://stackoverflow.com/a/52000387
has body: show error with the following python codes Error: print driver.find_elements_by_xpath('.//*[@id="example"]/tbody/tr[1]/td[1]').text AttributeError: 'list' object has no attribute 'text' Python Code: from selenium import webdriver driver = webdriver.Firefox() driver.get("https://datatables.net/") print driver.find_elements_by_xpath('.//*[@id="example"]/tbody/tr[1]/td[1]').text Expected Result : Airi Satou
favorite count: 0
has answer: http://stackoverflow.com/a/52000387
has comment: http://stackoverflow.com/comment/90949801
tagged with: python
has title: show error with the following python codes
tagged with: xpath
type: AnsweredQuestion
tagged with: webdriver

http://stackoverflow.com/comment/109448852
comment on: http://stackoverflow.com/a/52100354
type: Comment
has text: is it better than glob? is it faster according to what the question said?
score: 0
type: AnswerComment

http://stackoverflow.com/q/52002037
accepted answer: http://stackoverflow.com/a/52015280
tagged with: python
type: AnsweredQuestion
has title: Consistency of ElementTree elements
type: Question
has answer: http://stackoverflow.com/a/52015280
score: 0
has body: I am using xml to describe bounding boxes and intend to filter out some elements of the xml files. A typical xml might look like: original2 beach146.jpg /home/train/original/beach146.jpg Unknown 800 533 3 0 person Unspecified 0 0 314 315 559 400 boat Unspecified 0 0 580 193 602 205 I am applying some checks on the bbox coordinates and if necessary remove the object containing the corresponding bbox. I was accessing the coordinates using something like: xmin = int(obj.find('bndbox').find('xmax').text) but it seems awkward and ugly so I switched to: xmin = int(obj[4][0].text) which seems a little better. obj came from objs = tree.findall('object') so it could be even optimized by applying the same indices to the the root, like: print(root[7][4][0].tag, root[7][4][0].text) xmin 580 My question is whether the indexing system is consistent and will work as expected in every xml file. Meaning that it will return the elements in the order they where written in file for example. My xml files is expected to have the same order of elements. In other case a check on obj[4][0].tag should be applied to verify I am working on the expected element.
answer count: 1
tagged with: elementtree

http://stackoverflow.com/q/52010551
has comment: http://stackoverflow.com/comment/90997078
has comment: http://stackoverflow.com/comment/91029036
tagged with: dataframe
has body: Lets say we have a pandas dataframe like bellow, import pandas as pd df = pd.DataFrame([{'col1':'a', 'col2':'b'}, {'col1':None, 'col2':'d'}, {'col1':'e', 'col2':'f'}, {'col1':None, 'col2':'1'}]) Is there any difference between this two code, df.loc[~df['col1'].isnull(), 'col1'] = df['col1'].str.upper() print(df) vs mask = ~df['col1'].isnull() df.loc[mask, 'col1'] = df[mask]['col1'].str.upper() print(df)
has comment: http://stackoverflow.com/comment/90982153
score: 0
tagged with: python
tagged with: masking
answer count: 0
has title: Python Pandas DataFrame Difference Between Masking Left side only and Both Side
type: UnansweredQuestion
type: Question

http://stackoverflow.com/q/52008437
tagged with: indexing
has comment: http://stackoverflow.com/comment/90967351
tagged with: dataframe
tagged with: pandas
accepted answer: http://stackoverflow.com/a/52008545
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/90967426
has body: I want to drop rows in my dataset using: totes = df3.loc[(df3['Reporting Date'] != '18/08/2017') &amp; (df3['Business Line'] != 'Bondy')] However it is not what I expect; I know that the number of rows I want ot drop is 496 after using: totes = df3.loc[(df3['Reporting Date'] == '18/08/2017') &amp; (df3['Business Line'] == 'Bondy')] When I run my drop function, it is giving back much less rows than my dataset minus 496. Does anyone know how to fix this?
tagged with: python
type: AnsweredQuestion
score: 1
upvote count: 3
downvote count: 2
has comment: http://stackoverflow.com/comment/90967400
has answer: http://stackoverflow.com/a/52008545
has title: Dropping rows in Python using != operator is not working
type: Question

http://stackoverflow.com/q/52056020
has title: How to log some messages to a log file and some messages to stdout using logging in Python
score: 1
has body: I have the below code base for logging: import logging logFormatter = logging.Formatter("%(asctime)s [%(threadName)-12.12s] [%(levelname)-5.5s] %(message)s") rootLogger = logging.getLogger() rootLogger.setLevel(logging.DEBUG) fileLogger = logging.getLogger() fileLogger.setLevel(logging.DEBUG) fileHandler = logging.FileHandler("new_log.log") fileHandler.setFormatter(logFormatter) fileLogger.addHandler(fileHandler) consoleHandler = logging.StreamHandler() consoleHandler.setFormatter(logFormatter) rootLogger.addHandler(consoleHandler) fileLogger.debug('debug message') rootLogger.debug('debug message') fileLogger.info('info message') fileLogger.warn('warn message') rootLogger.warn('warn message') fileLogger.error('error message') fileLogger.critical('critical message') rootLogger.critical('critical message') My main purpose is to use the rooLogger to log to the console and the fileLogger to log to a file . How can i achieve that here ? I am not sure if the above way is correct or not. Can someone please throw some light ? Many thanks in advance
downvote count: 0
favorite count: 0
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/91062198
answer count: 0
upvote count: 1
tagged with: logging
type: Question

http://stackoverflow.com/q/52077696
tagged with: python
has comment: http://stackoverflow.com/comment/93994965
has body: Python msrestazure(0.4.20V) is throwing below error: credentials = UserPassCredentials(userid, password) File "/data/tools/lib/python3.5/site-packages/msrestazure/azure_active_directory.py", line 367, in __init__ self.set_token() File "/data/tools/lib/python3.5/site-packages/msrestazure/azure_active_directory.py", line 404, in set_token raise_with_traceback(AuthenticationError, "", err) File "/data/tools/lib/python3.5/site-packages/msrest/exceptions.py", line 45, in raise_with_traceback raise error.with_traceback(exc_traceback) File "/data/tools/lib/python3.5/site-packages/msrestazure/azure_active_directory.py", line 402, in set_token **optional) File "/data/tools/lib/python3.5/site-packages/requests_oauthlib/oauth2_session.py", line 221, in fetch_token verify=verify, proxies=proxies) File "/data/tools/lib/python3.5/site-packages/requests/sessions.py", line 555, in post return self.request('POST', url, data=data, json=json, **kwargs) File "/data/tools/lib/python3.5/site-packages/requests_oauthlib/oauth2_session.py", line 360, in request headers=headers, data=data, **kwargs) File "/data/tools/lib/python3.5/site-packages/requests/sessions.py", line 508, in request resp = self.send(prep, **send_kwargs) File "/data/tools/lib/python3.5/site-packages/requests/sessions.py", line 618, in send r = adapter.send(request, **kwargs) File "/data/tools/lib/python3.5/site-packages/requests/adapters.py", line 502, in send raise ProxyError(e, request=request) msrest.exceptions.AuthenticationError: , ProxyError: HTTPSConnectionPool(host='login.microsoftonline.com', port=443): Max retries exceeded with url: /common/oauth2/token (Caused by ProxyError('Cannot connect to proxy.', OSError('Tunnel connection failed: 403 Forbidden',))) We used correct azure credentials, Any idea? Edit: This issue is coming up again, this time from different exception requests.exceptions.ProxyError: HTTPSConnectionPool(host='login.microsoftonline.com', port=443): Max retries exceeded with url: /common/UserRea…
answer count: 0
has comment: http://stackoverflow.com/comment/91350111
type: Question
has comment: http://stackoverflow.com/comment/91155946
has comment: http://stackoverflow.com/comment/91360679
has title: python msrestazure package throws Tunnel connection failed error
has comment: http://stackoverflow.com/comment/93655457
score: 0
tagged with: azure
type: UnansweredQuestion

http://stackoverflow.com/comment/91121429
score: 0
has text: I'm not really sure what you mean, but the error occurs before the `memmap` line anyway. And with the `memmap` I'm only trying to generate an array (that won't save in memory)
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52085413

http://stackoverflow.com/comment/90910206
score: 0
type: AnswerComment
has text: YYYYMMDD1 and YYYYMMDD2 in variables, not fixed strings.
type: Comment
comment on: http://stackoverflow.com/a/51979914

http://stackoverflow.com/comment/90937020
comment on: http://stackoverflow.com/q/51993553
score: 0
has text: I think you just need to change this one line of code: `img_orig = img_orig.astype(int)` and then you can probably get rid of the `dtype` conversion using `np.uint8` if you'd just like to view the image.
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52055722
downvote count: 1
has answer: http://stackoverflow.com/a/52055877
type: Question
score: 5
has body: I am dealing with a multi-class problem (4 classes) and I am trying to solve it with scikit-learn in Python. I saw that I have three options: I simply instantiate a classifier, then I fit with train and evaluate with test; classifier = sv.LinearSVC(random_state=123) classifier.fit(Xtrain, ytrain) classifier.score(Xtest, ytest) I "encapsulate" the instantiated classifier in a OneVsRest object, generating a new classifier that I use for train and test; classifier = OneVsRestClassifier(svm.LinearSVC(random_state=123)) classifier.fit(Xtrain, ytrain) classifier.score(Xtest, ytest) I "encapsulate" the instantiated classifier in a OneVsOne object, generating a new classifier that I use for train and test. classifier = OneVsOneClassifier(svm.LinearSVC(random_state=123)) classifier.fit(Xtrain, ytrain) classifier.score(Xtest, ytest) I understand the difference between OneVsRest and OneVsOne, but I cannot understand what I am doing in the first scenario where I do not explicitly pick up any of these two options. What does scikit-learn do in that case? Does it implicitly use OneVsRest? Any clarification on the matter would be highly appreciated. Best, MR Edit: Just to make things clear, I am not specifically interested in the case of SVMs. For example, what about RandomForest?
has comment: http://stackoverflow.com/comment/91061441
answer count: 1
tagged with: scikit-learn
accepted answer: http://stackoverflow.com/a/52055877
favorite count: 0
tagged with: multiclass-classification
has title: Does scikit-learn use One-Vs-Rest by default in multi-class classification?
tagged with: python
has comment: http://stackoverflow.com/comment/91062270
upvote count: 6
has comment: http://stackoverflow.com/comment/91066220
type: AnsweredQuestion
tagged with: machine-learning

http://stackoverflow.com/q/52045556
favorite count: 0
upvote count: 2
tagged with: python
score: 2
has title: Extract duplicates into new dataframe with Pandas
type: AnsweredQuestion
tagged with: duplicates
tagged with: dataframe
type: Question
has body: I have a large data frame with a many columns. One of these columns is what's supposed to be a Unique ID and the other is a Year. Unfortunately, there are duplicates in the Unique ID column. I know how to generate a list of all duplicates, but what I actually want to do is extract them out such that only the first entry (by year) remains. For example, the dataframe currently looks something like this (with a bunch of other columns): ID Year ---------- 123 1213 123 1314 123 1516 154 1415 154 1718 233 1314 233 1415 233 1516 And what I want to do is transform this dataframe into: ID Year ---------- 123 1213 154 1415 233 1314 While storing just the those duplicates in another dataframe: ID Year ---------- 123 1314 123 1516 154 1415 233 1415 233 1516 I could drop duplicates by year to keep the oldest entry, but I am not sure how to get just the duplicates into a list that I can store as another dataframe. How would I do this?
has answer: http://stackoverflow.com/a/52045624
tagged with: pandas
answer count: 1
accepted answer: http://stackoverflow.com/a/52045624
downvote count: 0

http://stackoverflow.com/q/51989660
has comment: http://stackoverflow.com/comment/90929189
has comment: http://stackoverflow.com/comment/90929590
type: Question
has answer: http://stackoverflow.com/a/51990035
has body: The following is my code where I try to check for the balanced parenthesis. def is_matched(expression): opening = tuple('({['); closing = tuple(')}]'); mapping = dict(zip(opening,closing)); queue = []; for letter in expression : if letter in opening : queue.append(mapping[letter]); elif letter in closing : if (not queue) or (letter != queue.pop()) : return False; return not queue; ip = input(); if is_matched(ip): print ("Valid"); else: print("Invalid"); My question is why the queue list is getting to [] state for every letter in the input parameter in the for loop? Should it not append every dictionary mapping in the loop?
tagged with: for-loop
upvote count: 0
score: -2
answer count: 1
tagged with: python
has title: Why is stack for pair-nesting analysis often empty?
has comment: http://stackoverflow.com/comment/90929024
favorite count: 0
has comment: http://stackoverflow.com/comment/90929126
downvote count: 2
has comment: http://stackoverflow.com/comment/90929544
has comment: http://stackoverflow.com/comment/90929139
has comment: http://stackoverflow.com/comment/90929479
has comment: http://stackoverflow.com/comment/90928968
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51990035
tagged with: list
has comment: http://stackoverflow.com/comment/90929042

http://stackoverflow.com/comment/91023695
type: Comment
score: 1
comment on: http://stackoverflow.com/q/52036709
has text: Count your parantheses.
type: QuestionComment

http://stackoverflow.com/a/51967402
has comment: http://stackoverflow.com/comment/90886566
score: 1
has comment: http://stackoverflow.com/comment/90888048
has comment: http://stackoverflow.com/comment/90884937
has body: My test data file blockMeshDict: vertices // comment 1 ( (1 2 3) // comment 2 /* :) */ (3 4 5) /* multi line... ...comment */ (65.71 72.8 2.0) ) Code: import re with open("blockMeshDict", "r") as f: s=f.read() # Remove comments like "//" until end of line s = re.sub(r'//.*', '', s) # Remove comments between /* and */ s = re.sub(r'/\*(.|\s)*?\*/', '', s, re.DOTALL) r1 = re.search(r'vertices\s*\(\s*(.*)\s*\)', s, re.DOTALL) vertices = [(float(v[0]),float(v[1]),float(v[2])) for v in re.findall(r'\(\s*([-0-9.]+)\s+([-0-9.]+)\s+([-0-9.]+)\s*\)', r1.group(1))] print(vertices) Output is the list of tuples (of float's): [(1.0, 2.0, 3.0), (3.0, 4.0, 5.0), (65.71, 72.8, 2.0)]
has comment: http://stackoverflow.com/comment/90885946
downvote count: 0
has comment: http://stackoverflow.com/comment/90885425
has comment: http://stackoverflow.com/comment/90885624
has comment: http://stackoverflow.com/comment/90885637
type: Answer
has comment: http://stackoverflow.com/comment/90885439
has comment: http://stackoverflow.com/comment/90885973
has comment: http://stackoverflow.com/comment/90887670
answers question: http://stackoverflow.com/q/51965798
upvote count: 1
has comment: http://stackoverflow.com/comment/90888739
has comment: http://stackoverflow.com/comment/90886099
has comment: http://stackoverflow.com/comment/90888949

http://stackoverflow.com/q/52079948
type: Question
has body: Having a dataframe consisting of a person and the order... person order elements Alice [drink, snack, salad, fish, dessert] 5 Tom [drink, snack] 2 John [drink, snack, soup, chicken] 4 Mila [drink, snack, soup] 3 I want to known what customers had as a main meal. Thus, I want to add another column [main_meal] so that would be my df. person order elements main_meal Alice [drink, snack, salad, fish, dessert] 5 fish Tom [drink, snack] 2 none John [drink, snack, soup, chicken] 4 chicken Mila [drink, snack, soup] 3 none The rule is that if a customer ordered 4 or more meals, it means the 4th element is always the main dish, so I want to extract the 4th element from the list on the order column. If it contains less than 4 elements, then assign 'main_meal' to none. My code: df['main_meal'] = '' if df['elements'] &gt;= 4: df['main_meal'] = df.order[3] else: df['main_meal'] = 'none' It doesn't work: ValueError Traceback (most recent call last) &lt;ipython-input-100-39b7809cc669&gt; in &lt;module&gt;() 1 df['main_meal'] = '' 2 df.head(5) ----&gt; 3 if df['elements'] &gt;= 4: 4 df['main_meal'] = df.order[3] 5 else: ~\Anaconda\lib\site-packages\pandas\core\generic.py in __nonzero__(self) 1571 raise ValueError("The truth value of a {0} is ambiguous. " 1572 "Use a.empty, a.bool(), a.item(), a.any() or a.all()." -&gt; 1573 .format(self.__class__.__name__)) 1574 1575 __bool__ = __nonzero__ ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all(). What is wrong with my code?
has comment: http://stackoverflow.com/comment/91109932
linked to: http://stackoverflow.com/q/30944577
has answer: http://stackoverflow.com/a/52080062
answer count: 3
tagged with: pandas
has answer: http://stackoverflow.com/a/52080405
downvote count: 0
favorite count: 0
has title: How to fill in empty column in a dataframe with a particular element from the list of another column?
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91109996
has comment: http://stackoverflow.com/comment/91110001
tagged with: python
has comment: http://stackoverflow.com/comment/91110134
score: 2
upvote count: 2
has answer: http://stackoverflow.com/a/52081070

http://stackoverflow.com/q/52091824
has comment: http://stackoverflow.com/comment/91133659
has comment: http://stackoverflow.com/comment/91242272
has comment: http://stackoverflow.com/comment/91133819
tagged with: python
tagged with: discord
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/91136761
answer count: 0
type: UnansweredQuestion
has title: Python add weights to random sample
has comment: http://stackoverflow.com/comment/91136112
has comment: http://stackoverflow.com/comment/91148479
has comment: http://stackoverflow.com/comment/91136341
type: Question
tagged with: discord.py
has body: How to add weights to below code. example: if i want to add x2 for red and x5 for black so finally all colours will be x1 except red and black. colours = {'red', 'blue', 'green', 'yellow', 'black', 'purple', 'Brown', 'Orange', 'violet', 'gray'} @bot.command(pass_context=True) async def pick(ctx): colours_copy = colours.copy() for n in [1, 2, 3]: cs = random.sample(colours_copy , k=n) colours_copy -= set(cs) await bot.send_message(ctx.message.channel, "{}\n".format(", ".join(cs)))
linked to: http://stackoverflow.com/q/3679694
score: 0
has comment: http://stackoverflow.com/comment/91241879

http://stackoverflow.com/q/52029797
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/91010136
tagged with: plot
has body: I'm trying to draw two rows with three columns of pcolormesh plots and a combined colorbar for all plots. So far it seems to work. However, I'm sure I'm not using the most elegant way... The only problem I have, is that I can't decrease the horizontal spacing any further. The following line should set the horizontal spacing to zero: fig.subplots_adjust(left=0.05, right=0.98, top=0.93, bottom=0.00, wspace=0, hspace=0.03) But this does not work in conjunction with ax.set_aspect('equal') I've attached a small code snippet that creates the following figure: Example figure import numpy as np import matplotlib.pyplot as plt import matplotlib.gridspec as gridspec rows = 2 columns = 3 fig = plt.figure() gs = gridspec.GridSpec(rows+1, columns) lines = [] x = np.linspace(1,10,100) y = x X, Y = np.meshgrid(x,y) Z = np.random.rand(100,100) lines = [] for i in range(rows): lines.append([]) for j in range(columns): ax = fig.add_subplot(gs[i, j]) line = ax.pcolormesh(X, Y, Z, cmap=plt.cm.Reds) lines[i].append(line) ax.set_aspect('equal') for tick in ax.get_xticklabels(): tick.set_rotation(45) if i!=rows-1: ax.set_xticklabels([]) if j!=0: ax.set_yticklabels([]) #title props = dict(boxstyle='round', facecolor='white', alpha=0.7) ax.text(0.05, 0.95, "plot (%i, %i)" % (i,j), transform=ax.transAxes, fontsize=5, verticalalignment='top', bbox=props) ax.tick_params(labelsize=7) cb_ax = fig.add_subplot(gs[-1,:]) cb_ax.set_aspect(0.05) cbar = fig.colorbar(lines[0][0], cax=cb_ax, orientation='horizontal') cb_ax.tick_params(labelsize=7) fig.subplots_adjust(left=0.05, right=0.98, top=0.93, bottom=0.00, wspace=0, hspace=0.03) #fig.tight_layout() fig.text(0.5, 0.2, "x axis", ha='center', va='center') fig.text(0.5, 0.97, "overall title", ha='center', va='center') fig.text(0.02, 0.5, "y axis", ha='center', va='center', rotation='vertical') fig.text(0.5, 0.02, "quantity [unit]", ha='center', va='center',) plt.savefig("test.png", dpi=600)
answer count: 0
has comment: http://stackoverflow.com/comment/91010928
has comment: http://stackoverflow.com/comment/91010764
type: Question
has comment: http://stackoverflow.com/comment/91011050
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/91010339
score: 0
has comment: http://stackoverflow.com/comment/91010571
has title: horizontal spacing of subplots with equal aspect ratio

http://stackoverflow.com/a/52040435
accepted answer of: http://stackoverflow.com/q/52008176
score: 1
upvote count: 1
type: AcceptedAnswer
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/52008176
has body: I'm actually surprised that your regex even worked! The sep parameter is for identifying where to split, not what tokens to recognize. What you really want (actually, an equivalent for what you want) is a regex that can: Split on every space. Split on : , unless the next 2 characters are digits followed by another :. That can be achieved using some advanced regex matching, specifically "lookahead". See this page for a detailed explanation of that. This should work for your example: pd.read_csv(path_to_csv, sep=' |:(?!\d{2}:)', header=None, engine='python')

http://stackoverflow.com/a/52069546
has comment: http://stackoverflow.com/comment/91111335
has comment: http://stackoverflow.com/comment/91096588
score: 6
accepted answer of: http://stackoverflow.com/q/52053491
has comment: http://stackoverflow.com/comment/91089658
has comment: http://stackoverflow.com/comment/137133807
has comment: http://stackoverflow.com/comment/139111973
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/52053491
has comment: http://stackoverflow.com/comment/137128636
has comment: http://stackoverflow.com/comment/91091718
type: Answer
upvote count: 6
has body: Your scheme has some challenges because of the ambiguity introduce with the default command. Regardless, here is one way that can be achieved with click. As shown in the test results, the generated help with be less than ideal, but likely OK. Custom Class: import click class DefaultCommandGroup(click.Group): """allow a default command for a group""" def command(self, *args, **kwargs): default_command = kwargs.pop('default_command', False) if default_command and not args: kwargs['name'] = kwargs.get('name', '&lt;&gt;') decorator = super( DefaultCommandGroup, self).command(*args, **kwargs) if default_command: def new_decorator(f): cmd = decorator(f) self.default_command = cmd.name return cmd return new_decorator return decorator def resolve_command(self, ctx, args): try: # test if the command parses return super( DefaultCommandGroup, self).resolve_command(ctx, args) except click.UsageError: # command did not parse, assume it is the default command args.insert(0, self.default_command) return super( DefaultCommandGroup, self).resolve_command(ctx, args) Using the Custom Class To use the custom class, pass the cls parameter to the click.group() decorator. Then pass default_command=True for the command which will be the default. @click.group(cls=DefaultCommandGroup) def a_group(): """My Amazing Group""" @a_group.command(default_command=True) def a_command(): """a command under the group""" How does this work? This works because click is a well designed OO framework. The @click.group() decorator usually instantiates a click.Group object but allows this behavior to be over ridden with the cls parameter. So it is a relatively easy matter to inherit from click.Group in our own class and over ride desired methods. In this case we over ride click.Group.command() so that when a command is added we find the default command. In addition we override click.Group.resolve_command() so that we can insert the default command name if the first resolution is unsuccessful. Test Code: @click…
has comment: http://stackoverflow.com/comment/137140189

http://stackoverflow.com/comment/90900147
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51974634
has text: Wow! That's amazing!! I thought the solution would look totally different. There are probably a few different ways to do this, but all I need is one. Thanks so much!! Just one more thing. How does the final_names variable get populated? Can you add some comments around that? Also, how does this line work? list(filter(lambda x:x != '\n'
type: AnswerComment

http://stackoverflow.com/comment/93331245
comment on: http://stackoverflow.com/a/52166410
score: 0
type: AnswerComment
type: Comment
has text: Indeed if the steps are implemented under the shared folder from test suite, but if you have an page object architecture and the folder steps is implemented where pages are implemented under Global scripts than you cannot pass collectStepDefinitions('./steps', '../lib/panels/steps')

http://stackoverflow.com/a/51983709
type: Answer
accepted answer of: http://stackoverflow.com/q/51982876
answers question: http://stackoverflow.com/q/51982876
has body: No. As with other text files, you need to read the file to memory, modify and then write the modified file to disk.
score: 0
upvote count: 1
type: AcceptedAnswer
downvote count: 1

http://stackoverflow.com/q/52001152
type: Question
has comment: http://stackoverflow.com/comment/90951682
has title: how python display list of all attribute and method using dir(object)?
has answer: http://stackoverflow.com/a/52001311
has comment: http://stackoverflow.com/comment/90951599
upvote count: 2
has comment: http://stackoverflow.com/comment/90951764
answer count: 3
has comment: http://stackoverflow.com/comment/90951830
has comment: http://stackoverflow.com/comment/90951627
has comment: http://stackoverflow.com/comment/140134978
has answer: http://stackoverflow.com/a/52001363
favorite count: 0
has comment: http://stackoverflow.com/comment/90951901
has comment: http://stackoverflow.com/comment/90951567
possible better answer: http://stackoverflow.com/a/52001311
linked to: http://stackoverflow.com/q/26818007
tagged with: python
type: AnsweredQuestion
has body: I was reading python dunder method and came across that the we can have our own definition for built-in method like len(object) So I created a class otherclass which has definition &gt;&gt;&gt; class otherclass: def __len__(self): return 0 &gt;&gt;&gt; len(otherclass()) 0 &gt;&gt;&gt; dir(otherclass) ['__doc__', '__len__', '__module__'] And it does print len of the object and further inspecting I also found len dunder method is available in otherclass object using dir I am wondering how python display the value for dir(object) as there is no dir dunder method in the result of dir(otherclass)
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/90951885
has answer: http://stackoverflow.com/a/52001314
accepted answer: http://stackoverflow.com/a/52001314

http://stackoverflow.com/a/52011235
downvote count: 0
has comment: http://stackoverflow.com/comment/90974042
accepted answer of: http://stackoverflow.com/q/52011190
type: Answer
has comment: http://stackoverflow.com/comment/90973694
score: 9
answers question: http://stackoverflow.com/q/52011190
upvote count: 9
has comment: http://stackoverflow.com/comment/90973854
has comment: http://stackoverflow.com/comment/90973664
has body: This is almost certainly a variation on "Unix time": instead of seconds since the 1 Jan 1970 epoch, it's milliseconds since the 1 Jan 1970 epoch: &gt;&gt;&gt; datetime.datetime.utcfromtimestamp(int('1522454400000') / 1000) datetime.datetime(2018, 3, 31, 0, 0) That certainly looks like a reasonable date. And it even looks like it probably is UTC, not local time (unless you happen to be in England, or weren't expecting it to be exactly at midnight). I don't think any of Pandas' built-in formats (which are actually just wrappers around formats from datetime and/or dateutil) exactly matches this, so you'll probably need to either do what I did about (convert to int and treat it as a number) or do the stringy equivalent (chop off the last 3 characters and then treat as a string of a UNIX timestamp). The first one seems simpler: &gt;&gt;&gt; pd.to_datetime(int('1522454400000'), unit='ms') Timestamp('2018-03-31 00:00:00') In fact, it'll even work directly on strings, doing the conversion implicitly: &gt;&gt;&gt; pd.to_datetime('1522454400000', unit='ms') Timestamp('2018-03-31 00:00:00')
has comment: http://stackoverflow.com/comment/91190950
type: AcceptedAnswer

http://stackoverflow.com/a/63471342
has body: If you just want to open an Excel program using Pywinauto, you can use this snippet codes as followed: from pywinauto import Application app = Application(backend="uia") app.start(r"C:/Program Files/Microsoft Office/root/Office16/EXCEL.exe")
type: Answer
score: 2
answers question: http://stackoverflow.com/q/51996308
downvote count: 0
upvote count: 2

http://stackoverflow.com/comment/91175039
type: AnswerComment
has text: Try using https://www.jsonschemavalidator.net to validate your schema. Please modify your question to include a complete and valid schema, otherwise it's really difficult for me to guess what the issues are. Currently that schema you've provided does nothing, because you have no validation key words at the root level.
type: Comment
comment on: http://stackoverflow.com/a/52112063
score: 0

http://stackoverflow.com/q/51989918
tagged with: python
has body: I have created a QComboBox (let's call it QC1) which populates another QComboBox (QC2) which in-turn creates a groupbox. I want to activate the slot for default items of both QC1 and QC2 initially and that of QC2 when QC1 is changed. I have tried searching throughout the web and here to no avail. import sys from PyQt5 import QtCore, QtWidgets, QtGui from PyQt5.QtWidgets import QMainWindow, QLabel, QGridLayout, QWidget class Window(QMainWindow): def __init__(self): super(Window,self).__init__() centralWidget = QtWidgets.QWidget(self) self.setCentralWidget(centralWidget) self.vBox = QtWidgets.QVBoxLayout() self.QC1 = QtWidgets.QComboBox(self) self.QC1.addItems(['C1-Op1','C1-Op2']) self.vBox.addWidget(self.QC1) self.QC2 = QtWidgets.QComboBox(self) self.QC2.addItem('') self.vBox.addWidget(self.QC2) self.QC1.activated[str].connect(self.QC1_activate) self.gBox = QtWidgets.QGroupBox() self.vBox_gB = QtWidgets.QVBoxLayout() self.vBox.addWidget(self.gBox) centralWidget.setLayout(self.vBox) def QC1_activate(self,text): self.QC2.clear() dic={'C1-Op1':'C2-Op1','C1-Op2':'C2-Op2'} self.QC2.addItem(dic[text]) self.QC2.activated[str].connect(self.QC2_activate) def QC2_activate(self,text): self.clearLayout(self,self.vBox_gB) lbl = QLabel(text) self.vBox_gB.addWidget(lbl) self.gBox.setLayout(self.vBox_gB) @staticmethod def clearLayout(self, layout): if layout is not None: while layout.count(): item = layout.takeAt(0) widget = item.widget() if widget is not None: widget.deleteLater() else: self.clearLayout(item.layout()) if __name__ == '__main__': app = QtWidgets.QApplication(sys.argv) GUI = Window() GUI.show() sys.exit(app.exec_()) Above is literally the most minimal working example I could come up with
has answer: http://stackoverflow.com/a/52009042
tagged with: pyqt5
type: Question
answer count: 2
tagged with: pyqt
score: 0
has title: PyQt5 run the slot for default combobox selection
tagged with: python-3.x
tagged with: qcombobox
has answer: http://stackoverflow.com/a/51996426
type: UnansweredQuestion

http://stackoverflow.com/q/52078009
duplicate of: http://stackoverflow.com/q/23026530
has body: PLEASE READ BEFORE MARKING AS DUPLICATE I have a a directory configured as such: app.py Modules/ __init__.py a.py b.py Where _init_.py contains: import a import b and a.py contains: import b Class A(): b_instance = b.B()` and b.py contains: import a Class B(): a_instance = a.A()` This entire /Modules folder is imported from the main app.py. It is my understanding that the execution will go as follows: app.py import Modules /Modules/_init_.py import a /Modules/a.py import b /Modules/b.py import a (sees that a is already in sys.modules and continues) /Modules/b.py executes Class B() and fails when trying to do: a_instance = a.A() because while a.py is in sys.modules, it has not yet executed class A and thus b.py cannot access Class A How then, can I have two classes which depend on each other and that dependency is linked at the highest scope of the class (i.e. not within a class method)? The solutions given online assume that the class dependency occurs within some sub method which fixes the issue because the actual class is not needed until that specific function is executed. The difference of my issue is that the class dependency is directly in the Class, not within some method, so the actual class is needed immediately.
has comment: http://stackoverflow.com/comment/91110123
has title: How to avoid circular imports for dependent classes in python?
has comment: http://stackoverflow.com/comment/91112405
has comment: http://stackoverflow.com/comment/91112347
tagged with: python
has comment: http://stackoverflow.com/comment/91107074
favorite count: 0
linked to: http://stackoverflow.com/q/22187279
answer count: 0
type: UnansweredQuestion
downvote count: 1
tagged with: circular-dependency
score: 3
linked to: http://stackoverflow.com/q/23026530
type: Question
upvote count: 4
tagged with: python-import

http://stackoverflow.com/a/52029877
answers question: http://stackoverflow.com/q/52029013
score: 0
has comment: http://stackoverflow.com/comment/91010238
type: Answer
has body: Interesting challenge you were given, i made a proposition for question 3, how many times a word occurs inside the string. This code is not optimal at all, but it does work. also i used the file text.txt edit: noticed i forgot to create wordlist as it was saved in my ram memory with open('text.txt', 'r') as doc: print('opened txt') for words in doc: wordlist = words.split() for numbers in range(len(wordlist)): for inner_numbers in range(len(wordlist)): if inner_numbers != numbers: if wordlist[numbers] == wordlist[inner_numbers]: print('word: %s == %s' %(wordlist[numbers], wordlist[inner_numbers])) Answer to question four: This one wasn't really hard after you have created a list with all the words since strings can be treated like a list and you can easily get the first letter of the string by simply doing string[0] and if its a list with strings stringList[position of word][0] for numbers in range(len(wordlist)): if wordlist[numbers][0] == 'a': print(wordlist[numbers])

http://stackoverflow.com/a/52070962
accepted answer of: http://stackoverflow.com/q/52068920
answers question: http://stackoverflow.com/q/52068920
upvote count: 3
has comment: http://stackoverflow.com/comment/91091911
has comment: http://stackoverflow.com/comment/91093184
score: 3
has comment: http://stackoverflow.com/comment/91093306
has body: As some of the comments already suggested, if you need to somehow interact with Javascript on a page, it is better to use selenium. However, regarding your first approach using a header: import requests from bs4 import BeautifulSoup url = "http://www.amazon.com/dp/" + 'B004CNH98C' headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36'} response = requests.get(url, headers=headers) soup = BeautifulSoup(response.text,"html.parser") These headers are a bit old, but should still work. By using them you are pretending that your request is coming from a normal webbrowser. If you use requests without such a header your code is basically telling the server that the request is coming from python, which most of the servers are rejecting right away. Another alternative for you could also be fake-useragent maybe you can also have a try with this.
type: AcceptedAnswer
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/91091834

http://stackoverflow.com/q/52053415
type: Question
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91057038
has answer: http://stackoverflow.com/a/52053461
score: 0
has answer: http://stackoverflow.com/a/52053552
answer count: 2
tagged with: pandas
has body: No amount of googling seems to make this any simpler for me and most of the results I get are about different conversions, so here goes. Given a dataframe column with values like [{'id': 5, 'value': 'string1'},{'id': 3, 'value': 'string3'},{'id': 35, 'value': 'string2'}] How do I convert this to a list of stings such as ['string1','string2','string3'] I attempted to use two for loops such as, for x in df: for y in x: y = y['value'] And this seems to work when i add in a print(y) after the operation, but the change doesn't seem to stick.
has title: Convert a list of dictionaries within a dataframe to a list of strings - pandas
possible better answer: http://stackoverflow.com/a/52053552
tagged with: python
accepted answer: http://stackoverflow.com/a/52053461

http://stackoverflow.com/q/51969634
tagged with: python
tagged with: append
downvote count: 0
has body: I have two data frames that I want to append together. Below are samples. df_1: Code Title 103 general checks 107 limits 421 horseshoe 319 scheduled 501 zonal df_2 Code Title 103 hello 108 lucky eight 421 little toe 319 scheduled cat 503 new item I want to append df_2 to df_1 ONLY IF the code number in df_2 does not exist already in df_1. Below is the dataframe I want: Code Title 103 general checks 107 limits 421 horseshoe 319 scheduled 501 zonal 108 lucky eight 503 new item I have searched through Google and Stackoverflow but couldn't find anything on this specific case.
type: Question
has answer: http://stackoverflow.com/a/51970500
tagged with: conditional-statements
has title: Python Pandas: Append Dataframe To Another Dataframe Only If Column Value is Unique
has answer: http://stackoverflow.com/a/51969807
has answer: http://stackoverflow.com/a/51969683
answer count: 3
score: 5
tagged with: pandas
favorite count: 0
upvote count: 5
type: UnansweredQuestion

http://stackoverflow.com/a/52070665
answers question: http://stackoverflow.com/q/52070462
has comment: http://stackoverflow.com/comment/106107058
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52070462
has comment: http://stackoverflow.com/comment/91091144
has comment: http://stackoverflow.com/comment/91092415
score: 9
has comment: http://stackoverflow.com/comment/91091174
has comment: http://stackoverflow.com/comment/132605796
has comment: http://stackoverflow.com/comment/106178173
has body: The AutoField field is a kind of IntegerField field, so you can't use PKs as A00001 . So, the possible way to achieve the requirement is to change the AutoField to CharField. Technically you can use "String PK Field" But, you should be aware of the problems/performance issues if you are going to use that. Here I found one nice SO post that explains the same - Strings as Primary Keys in SQL Database ======================================================================== If you still really wish to migrate to String PKs, read the following First you need to use the CharField instead of AutoField and override the save() method of model from django.db.models import Max class Custom(models.Model): id = models.CharField(primary_key=True, editable=False, max_length=10) name = models.CharField(max_length=100) def save(self, **kwargs): if not self.id: max = Custom.objects.aggregate(id_max=Max('id'))['id_max'] self.id = "{}{:05d}".format('A', max if max is not None else 1) super().save(*kwargs)
type: AcceptedAnswer
upvote count: 9
has comment: http://stackoverflow.com/comment/91091478
has comment: http://stackoverflow.com/comment/106085759
type: Answer

http://stackoverflow.com/a/51976610
upvote count: 3
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/51976580
type: Answer
accepted answer of: http://stackoverflow.com/q/51976580
has body: Can't you just write a function mapping to each? In fact, a dictionary will do. def convert_monthname(monthname): table = {"January": datetime.datetime(month=1, day=1, year=2018), "February": datetime.datetime(month=2, day=1, year=2018), ...} return table.get(monthname, monthname) f['Month'] = f['Month'].apply(convert_monthname)
score: 3
downvote count: 0

http://stackoverflow.com/comment/91054194
type: QuestionComment
comment on: http://stackoverflow.com/q/52051760
has text: @Longshort that is not the content of the directory. Is there anythin still in the directory?
score: 0
type: Comment

http://stackoverflow.com/comment/91169261
comment on: http://stackoverflow.com/q/52109221
score: 0
type: QuestionComment
type: Comment
has text: will add an example

http://stackoverflow.com/comment/90997089
score: 0
type: Comment
has text: The code snippet I posted is meant to replace the OP's code's loop only; otherwise I would've also included the code to open the file.
type: AnswerComment
comment on: http://stackoverflow.com/a/52022106

http://stackoverflow.com/a/52064154
score: 1
has body: After some searching, Cross-Validated provided the correct answer to my question. Although it already exists on Cross-Validated, I wanted to provide this answer on Stack Overflow as well. Simply put, Scikit-Learn automatically adds a regularization penalty to the logistic model that shrinks the coefficients. Statsmodels does not add this penalty. There is apparently no way to turn this off so one has to set the C= parameter within the LogisticRegression instantiation to some arbitrarily high value like C=1e9. After trying this and comparing the Scikit-Learn predict_proba() to the sigmoidal graph produced by regplot (which uses statsmodels for its calculation), the probability estimates align. Link to full post: https://stats.stackexchange.com/questions/203740/logistic-regression-scikit-learn-vs-statsmodels
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52048631
type: Answer
upvote count: 1
answers question: http://stackoverflow.com/q/52048631

http://stackoverflow.com/q/51970072
has body: I've searched a function in OpenCV (cv::videostab), that would allow me to do video stabilization in Real-Time. But as I understand in OpenCV this is not yet available. So TwoPassStabilizer(OnePassStabilizer) require a whole video at once and not two consecutive frames. Ptr&lt;VideoFileSource&gt; source = makePtr&lt;VideoFileSource&gt;(inputPath); //it's whole video TwoPassStabilizer *twopassStabilizer = new TwoPassStabilizer(); twoPassStabilizer-&gt;setFrameSource(source); So I have to do this without the OpenCV video stabilization class. This is true?
type: Question
has title: Real-Time video stabilization OpenCV
score: 5
upvote count: 5
has answer: http://stackoverflow.com/a/57205570
answer count: 2
downvote count: 0
favorite count: 0
type: UnansweredQuestion
tagged with: python
tagged with: opencv
has answer: http://stackoverflow.com/a/63470746
tagged with: image-stabilization
tagged with: video-processing

http://stackoverflow.com/comment/132242666
type: QuestionComment
has text: Another option that may fit your case could be using 'dirsync'
type: Comment
comment on: http://stackoverflow.com/q/52098163
score: 0

http://stackoverflow.com/a/52043377
has comment: http://stackoverflow.com/comment/108759855
has comment: http://stackoverflow.com/comment/108944851
accepted answer of: http://stackoverflow.com/q/51997048
has comment: http://stackoverflow.com/comment/108762378
upvote count: 2
type: Answer
score: 2
has comment: http://stackoverflow.com/comment/108757734
has comment: http://stackoverflow.com/comment/108793558
has body: I'm the pathos author. Working with distributed resources isn't as straightforward as you might want. You are correct (in your comments) that pathos uses RPC-based (wrapped in SSH) connections. You are also correct in that you have to set up a ppserver on the remote host. If you need to make a ssh connection, then you can do that with the pathos_connect script (see associated documentation), or directly with code in the pathos.secure module. Note that you'll also need to make sure that you have a working ssh-agent and have set up ssh key-pair authentication (i.e. uses no passphrase after the initial connection). Having said that, it's pretty difficult to specifically get 4 remote workers and 4 local workers -- as the ParallelPool is dynamically load balanced. Thus, if you have "quick" tasks to run, the vast majority, if not all, of the tasks will run locally as spinning up the connection and shipping the tasks and retrieving the results will take more time than just running the jobs locally. You can force tasks to run remotely by zeroing out (or seriously limiting) the ncpus locally available for the pool, but how many jobs run where will depend on an automated load balance of the number of locally available tasks, and some measure of the time it takes for an individual job to complete versus the time it takes to connect and run the jobs remotely.
has comment: http://stackoverflow.com/comment/108747109
has comment: http://stackoverflow.com/comment/108775713
has comment: http://stackoverflow.com/comment/108897728
has comment: http://stackoverflow.com/comment/108762289
answers question: http://stackoverflow.com/q/51997048
has comment: http://stackoverflow.com/comment/108917654
has comment: http://stackoverflow.com/comment/91037610
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/a/52043516
answers question: http://stackoverflow.com/q/52043459
upvote count: 1
downvote count: 0
type: Answer
score: 1
has body: The sintax is simple def your_function_name(parameters): and tabulate your code properly inside. Also notice that functions can return values so your case is convenient: def word_freq(file_path) word_freq_dict = {} with open(file_path, 'r') as f: word_list = f.read().split() for word in word_list: word_freq_dict.setdefault(word, 0) word_freq_dict[word] += 1 return word_freq_dict print(word_freq("partA")) Check that we use a parameter file_path to take the non-common part of the code, and instead of printing the values, we return them from the function so that way we can use them outside of it too, if you want to print them, you can just print them outside.

http://stackoverflow.com/q/51967698
has body: I'm trying to pass a row from a dataframe in a loop. I want to use each element in the dataframe as a set of parameters for a SQL call. df = [1,2,3]#this would actually be a table with several rows import as a dataframe for row in df.itertuples: sql = 'Select * from table where a = ? and b = ? and c = ?' ds = pd.read_sql(sql, db_conn, params={row[1], row[2], row[3]}) clf = LogisticRegression(ds) This is the basic framework that I thought would work. The idea is that I have a table that holds all the combinations that I need to create a logistic regression model. I need a subset of a larger dataset based on several columns. I'm trying to cut down on bringing the whole dataset in at once.
tagged with: python
has comment: http://stackoverflow.com/comment/90885599
has title: Python - Loop Over rows in a table and pass SQL parameters
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90886932
tagged with: parameters
has comment: http://stackoverflow.com/comment/90886222
has comment: http://stackoverflow.com/comment/90886449
type: Question
score: 0
has comment: http://stackoverflow.com/comment/90887020
tagged with: sql
has comment: http://stackoverflow.com/comment/90886613

http://stackoverflow.com/q/52021003
type: AnsweredQuestion
has body: EDIT: The general idea is to store all the variables in my Jupyter Notebook using %store magic in order to use %store -r to get them all back to the next session. I am trying to use: % store and I need to store variables. With: dir() I obtain a list of strings with all the variables' names I created until that line like: ['a','b','c'] Is there a way to perform a: %store a %store b %store c Knowing the strings of the variables? I tried with this: for i in dir(): %store eval(i) but it gives: UsageError: Unknown variable 'eval(i)' How can I deal with that? Is there a way to save all the local environment in Jupyter Notebook for a next use? EDIT: for i in dir(): %store locals()[i] Gives: UsageError: Unknown variable 'locals()[i]'
tagged with: variables
tagged with: string
has title: Python target a variable given the string
type: Question
tagged with: python
has comment: http://stackoverflow.com/comment/90992402
tagged with: jupyter-notebook
has answer: http://stackoverflow.com/a/52021413
score: 0
tagged with: store
accepted answer: http://stackoverflow.com/a/52021413
answer count: 1
has comment: http://stackoverflow.com/comment/90992469

http://stackoverflow.com/q/51959321
type: AnsweredQuestion
score: 0
type: Question
tagged with: grid-search
accepted answer: http://stackoverflow.com/a/51966217
tagged with: cloudera
answer count: 1
tagged with: scikit-learn
has title: Too many lines output from gridsearch when njobs large than 1
tagged with: python
has answer: http://stackoverflow.com/a/51966217
has body: I use the following code to do the gridsearch, set the njobs=crossvalidation fold, but I got many lines likes the below: GridSearchCV(estimator = est, cv = crossval_n, n_jobs = crossval_n, param_grid = param_grid, scoring = grid_score, verbose = 1000) the info is like this: Pickling array (shape=(2,), dtype=object). Pickling array (shape=(7,), dtype=object). Pickling array (shape=(5,), dtype=object). Pickling array (shape=(5,), dtype=object). Pickling array (shape=(2,), dtype=object). Memmaping (shape=(300000,), dtype=float64) to old file /dev/shm/joblib_memmaping_pool_31858_140577309572624/31858-140577424627920-252eb20f1c96190cb0ef65643005ff1e.pkl Memmaping (shape=(199999,), dtype=int64) to old file /dev/shm/joblib_memmaping_pool_31858_140577309572624/31858-140577424627920-e2ad805d63b492d1bda22f6ecd785fa9.pkl Pickling array (shape=(100001,), dtype=int64). [CV] n_estimators=25, loss=deviance, learning_rate=0.05, max_depth=3, score=0.663848252373, total= 4.5min [CV] n_estimators=100, loss=deviance, learning_rate=0.05, max_depth=3 [Parallel(n_jobs=3)]: Done 1 tasks | elapsed: 4.9min Pickling array (shape=(3376,), dtype=object). Memmaping (shape=(73, 300000), dtype=float64) to old file /dev/shm/joblib_memmaping_pool_31858_140577309572624/31858-140577424627920-2a1a398dde29f0da54a999a91072b77b.pkl Memmaping (shape=(1, 300000), dtype=int64) to old file /dev/shm/joblib_memmaping_pool_31858_140577309572624/31858-140577424627920-108448b3fbe2af627fc26e0b965874b9.pkl Memmaping (shape=(62, 300000), dtype=float64) to old file /dev/shm/joblib_memmaping_pool_31858_140577309572624/31858-140577424627920-32d40c577c413ff0ea04ade1cc62a62e.pkl Not sure 1) what's the info about? 2) is there any error if I got this information? 3) if it is not error message, how to disable print it out?

http://stackoverflow.com/comment/90974517
has text: Okay, so the surface plot doesn't plot on the correct domain like I said. I found the reason: `scipy.interpolate.griddata` interpolates inside a convex hull. So it interpolates between your lobes too. Perhaps you need a different approach to make it work. I'll see if I can find anything.
comment on: http://stackoverflow.com/q/52008009
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/q/51974256
favorite count: 0
tagged with: pandas
accepted answer: http://stackoverflow.com/a/51974539
upvote count: 6
tagged with: python-3.x
possible better answer: http://stackoverflow.com/a/51974747
score: 6
has answer: http://stackoverflow.com/a/51974539
tagged with: python
has title: Adding a Dictionary as a new row in a data frame
tagged with: dictionary
type: AnsweredQuestion
has body: I have a function that returns a dictionary of keys and results. I'd like to create a new function that loops through different values. Each value would produce a new dictionary of different result but with the same keys. I'd like to have this function create a dataframe and with each iteration through the loop, the index (or first column) is set to the i value of my loop and the row would be the resulting dictionary. . the dictionary would look like {key1: 46, key2:100,key3:200} start = 10 stop = 100 step = 10 the final result would look something like: key1 key2 key3 10 46 100 200 20 50 75 60 30 80 2 10 40 100 50 6 50 10 8 33 etc...
tagged with: dataframe
type: Question
has answer: http://stackoverflow.com/a/51974747
answer count: 2
downvote count: 0

http://stackoverflow.com/comment/90974507
type: Comment
comment on: http://stackoverflow.com/q/52009769
type: QuestionComment
has text: improve language
score: 0

http://stackoverflow.com/comment/91090171
type: Comment
has text: Use `df.dropna(inplace=True)` and perform your operation.
comment on: http://stackoverflow.com/q/52070056
score: 0
type: QuestionComment

http://stackoverflow.com/comment/91099242
type: QuestionComment
has text: Thanks, that works. That is the desired output. Any idea on how to go about it?
comment on: http://stackoverflow.com/q/52074701
score: 0
type: Comment

http://stackoverflow.com/q/52026789
has comment: http://stackoverflow.com/comment/91003843
has comment: http://stackoverflow.com/comment/91003942
has comment: http://stackoverflow.com/comment/91003884
tagged with: file
upvote count: 1
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/91003855
has title: Python when splitting line in file it leaves newline in the end
has comment: http://stackoverflow.com/comment/91003866
has body: I'm trying to make a simple question/answer program, where the questions are written in a normal text file like this Problem is when i split the code (at the #) it also leaves the newline, meaning anyone using the program would have to add the newline to the answer. Any way to remove that newline so only the answer is required? Code: file1 = open("file1.txt", "r") p = 0 for line in file: list = line.split("#") answer = input(list[0]) if answer == list[1]: p = p + 1 print("points:",p)
has comment: http://stackoverflow.com/comment/91003903
score: 0
answer count: 2
linked to: http://stackoverflow.com/q/12330522
has answer: http://stackoverflow.com/a/52026855
has comment: http://stackoverflow.com/comment/91004192
favorite count: 0
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/52026859

http://stackoverflow.com/a/52061825
upvote count: 2
type: Answer
accepted answer of: http://stackoverflow.com/q/52061688
score: 2
has body: I think all you need to do is replace the 2nd for loop: for path in pathList: if not any(name in path for name in vendMastList): print(path) This checks if any of the words in the list appear in the path: and if none do, then print it out
answers question: http://stackoverflow.com/q/52061688
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/109255594
comment on: http://stackoverflow.com/a/61085582
score: 0
type: AnswerComment
has text: when I tried printing `os.environ` I got this response from the glue job, `environ({ "PATH": "<VALUE>", "HOSTNAME": "<VALUE>", "USE_PROXY": "<VALUE>", "AWS_DEFAULT_REGION": "us-east-1", "GLUE_PYTHON_VERSION": "3", "ERROR_FILE_NAME_LOCATION": "<VALUE>", "LANG": "<VALUE>", "GPG_KEY": "<VALUE>", "PYTHON_VERSION": "<VALUE>", "PYTHON_PIP_VERSION": "<VALUE>", "PYTHON_GET_PIP_URL": "<VALUE>", "PYTHON_GET_PIP_SHA256": "<VALUE>", "PYTHONPATH": ":<VALUE>", "GLUE_INSTALLATION": "<VALUE>", "HOME": "/" })`
type: Comment

http://stackoverflow.com/comment/91892086
score: 0
comment on: http://stackoverflow.com/q/52075480
type: Comment
type: QuestionComment
has text: Please show us your CAPL function and tell us where do you use it. You can directly use the return value of the `CAPLFunction.Call` method for some cases.

http://stackoverflow.com/a/52001018
has comment: http://stackoverflow.com/comment/90961249
type: Answer
has body: Since Rahul already solved your problem of time. I think the problem you are facing now is because of input type. You need to convert your input to integer. Try the following code. import time import androidhelper droid = androidhelper.Android() droid.ttsSpeak("System Stopped!!!") time.sleep(int(float(droid.ttsSpeak)))
has comment: http://stackoverflow.com/comment/90981606
answers question: http://stackoverflow.com/q/51999235
score: 0

http://stackoverflow.com/a/60739303
upvote count: 1
answers question: http://stackoverflow.com/q/52031044
score: 1
has body: If your are using service account which represent a service then: enable domain wide delegation for the service account. steps are and additional info here. After enabling domain wide delegation ,share the desired folders which you want to list using your service/webapp with service account's email address Service account link, it would be something like "XXX...XXX.iam.gserviceaccount.com".
has comment: http://stackoverflow.com/comment/122759937
downvote count: 0
type: Answer

http://stackoverflow.com/comment/91162662
type: Comment
score: 0
type: AnswerComment
has text: [It's fixed in master](https://github.com/twisted/twisted/blob/ee535041258e7ef0b3223d2e12cd9aaa0bc2289f/src/twisted/conch/manhole.py#L156), so now we're waiting for a release.
comment on: http://stackoverflow.com/a/52105818

http://stackoverflow.com/comment/91044788
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52044113
has text: @wwii the examples are for the creation of sliding windows, which I already have. I'm looking for ways to stitch the overlapping windows together again.
score: 0

dask
tags question: http://stackoverflow.com/q/51981737
type: Tag
tag name: dask
tags question: http://stackoverflow.com/q/52112137
tags question: http://stackoverflow.com/q/52086462
tags question: http://stackoverflow.com/q/52022211
tags question: http://stackoverflow.com/q/52039697
tags question: http://stackoverflow.com/q/51985180
tags question: http://stackoverflow.com/q/52094320

http://stackoverflow.com/comment/120700733
type: Comment
has text: Is this only for Python 3.0 and later? This doesn't work for Python 2.7
score: 2
type: AnswerComment
comment on: http://stackoverflow.com/a/52097312

http://stackoverflow.com/q/52095871
tagged with: c#
score: 0
has comment: http://stackoverflow.com/comment/91141879
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91142077
tagged with: python
has body: I would like to be able to access public voids from a C# code within python. The c# code was made in visual studio and required a reference in the form of a specific .dll file. I tried ironpython, pynet, but could not seem to get it to work. Following is the code in C# where the Dlubal.RFEM5 is the part that comes from the .dll file. using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.Runtime.InteropServices; using Dlubal.RFEM5; namespace WindowsFormsApp4 { public partial class Form1 : Form { private void Form1_Load(object sender, EventArgs e) { } public void CreateNewApplication() { // creates a hidden RFEM instance and gets it's interface IApplication app = new Dlubal.RFEM5.Application(); // checks RF-COM license and locks the application for using by COM app.LockLicense(); //... // here you can write your code //... // shows RFEM window app.Show(); // unlocks the application and releases RF-COM license app.UnlockLicense(); // releases COM object app = null; // cleans Garbage Collector for releasing all COM interfaces and objects. System.GC.Collect(); System.GC.WaitForPendingFinalizers(); } public void GetActiveApplication() { // gets interface to a running RFEM IApplication app = Marshal.GetActiveObject("RFEM5.Application") as IApplication; // checks RF-COM license and locks the application for using by COM app.LockLicense(); //... // here you can write your code //... // unlocks the application and releases RF-COM license app.UnlockLicense(); // releases COM object app = null; // cleans Garbage Collector for releasing all COM interfaces and objects System.GC.Collect(); System.GC.WaitForPendingFinalizers(); } public void CreateNewStructure() { // creates a hidden RFEM instance and gets it's interface IModel model = new Model(); // checks RF-COM license and locks the application for using by …
answer count: 0
type: Question
has title: Calling C# public voids using a reference as functions in python

http://stackoverflow.com/a/52051265
score: 0
answers question: http://stackoverflow.com/q/52051033
type: Answer
has body: In your case, d2 - d1 is a timedelta object which has an integer property days. So you need to write days = (d2 - d1).days in your python code, and you will get an int which you can subtract from whatever you need.
has comment: http://stackoverflow.com/comment/91053035

http://stackoverflow.com/q/52088612
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91128091
type: Question
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/91127681
has comment: http://stackoverflow.com/comment/91129633
score: 0
has comment: http://stackoverflow.com/comment/91128080
tagged with: python
has body: I am trying to plot a histogram in a jupyter notebook using matplot, where I am trying to put 2 data sets on the same axis in order to compare them and I keep reciveing the deprecation warning and I cant seem to figure out why. What exactly is causing this problem? ax3 = fig2.add_subplot(331) ax3.set_xlabel("Danceability") ax3.set_ylabel('Count') ax3.set_title('Danceability Distribution') pos_dance.hist(alpha = 0.5, bins = 30) ax4 = fig2.add_subplot(331) neg_dance.hist(alpha = 0.5, bins = 30)
has comment: http://stackoverflow.com/comment/91130845
has comment: http://stackoverflow.com/comment/91127437
has title: Matplotlib Deprecation Warning

http://stackoverflow.com/comment/91084626
type: QuestionComment
has text: I would say no, when iterating over a dictionary it is not sure that the order will be always the same, so in the code here, the information about the concatenation order of the arrays is lost... You could use [OrderedDict](https://docs.python.org/3/library/collections.html#collections.OrderedDict), but I think there is a better way to do this, could you give more detail about what you are trying to do?
comment on: http://stackoverflow.com/q/52067064
score: 0
type: Comment

http://stackoverflow.com/a/53894286
type: Answer
has body: n_nodes = 5 d = nx.gnp_random_graph(n_nodes, 0.5, directed=True) degree_prestige = dict((v,len(d.in_edges(v))/(n_nodes-1)) for v in d.nodes()) print("DEGREE PRESTIGE :\n") for i in degree_prestige: print(i, " : ", degree_prestige[i]) distance = [] temp_dis = 0 n = 0 for dest in d.nodes: temp_dis = 0 n = 0 for src in d.nodes: if (nx.has_path(d,src,dest) == True): temp_dis = temp_dis + nx.shortest_path_length(d,source = src,target = dest) n = n + 1 if temp_dis == 0: distance.append([dest, 0]) else: distance.append([dest, temp_dis/(n - 1)]) print("\nPROXIMITY PRESTIGE :\n") for i in distance: print(str(i[0]) + " : " + str(i[1])) prominance = np.random.randint(1, 4, size=n_nodes) print("\nASSUME PROMINANCE :\n") print(prominance) rank_prestige = np.zeros([n_nodes], dtype = int) path_matrix = np.zeros([n_nodes, n_nodes], dtype = int) i = 0 j = 0 for src in d.nodes: for dest in d.nodes: if d.has_edge(dest, src): path_matrix[i][j] = 1 j = j+1 j = 0 i = i+1 for i in range(n_nodes): pr_i = 0 for j in range(n_nodes): pr_i = pr_i + path_matrix[i][j] * prominance[j] rank_prestige[i] = pr_i print("\nRANK PRESTIGE :\n") print(rank_prestige)
answers question: http://stackoverflow.com/q/52057984
score: 0

http://stackoverflow.com/comment/90956749
type: AnswerComment
has text: And, here I tried to modify the original version to 10^7 which finished in about 1800 - 1900 ms. For the C-array version, I add one 0 for three number but somehow it core dumped and .. I have nothing to do with that. So, nice work @schorsch312.
type: Comment
comment on: http://stackoverflow.com/a/52002134
score: 0

http://stackoverflow.com/q/51980471
type: Question
accepted answer: http://stackoverflow.com/a/51981373
answer count: 2
has answer: http://stackoverflow.com/a/59767182
favorite count: 0
score: 6
possible better answer: http://stackoverflow.com/a/59767182
tagged with: python
upvote count: 7
has body: I would like to read/write files in Google Cloud Storage bucket with Python. Suppose I have a folder in gs://my_project/data. How to list the folders and files in the above folder? How to read and write files?
has title: How to read, write and list folders and files in google bucket?
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51981373
tagged with: google-cloud-storage
downvote count: 1

http://stackoverflow.com/q/51961696
has comment: http://stackoverflow.com/comment/90874077
accepted answer: http://stackoverflow.com/a/51961954
upvote count: 0
answer count: 1
favorite count: 0
tagged with: python-3.x
tagged with: python
has comment: http://stackoverflow.com/comment/90873756
type: AnsweredQuestion
downvote count: 2
has title: Absolute import error
type: Question
has body: Here is my project structure: /project_dir /src __init__.py index.py /handler __init__.py base_handler.py in index.py I import base_handler.BaseHandler like this: from src.handler.base_handler import BaseHandler and an error occurs: ModuleNotFoundError: No module named 'src' The strange thing is, when I move index.py out of src folder, this error will disappear: /project_dir index.py /src __init__.py /handler __init__.py base_handler.py Now in index.py I can import BaseHandler like this: from src.handler.base_handler import BaseHandler Can anyone tell me why this happens?
score: -2
has answer: http://stackoverflow.com/a/51961954

variables
tag name: variables
tags question: http://stackoverflow.com/q/52067118
tags question: http://stackoverflow.com/q/52038755
tags question: http://stackoverflow.com/q/52018736
tags question: http://stackoverflow.com/q/52081551
type: Tag
tags question: http://stackoverflow.com/q/52047091
tags question: http://stackoverflow.com/q/52089186
tags question: http://stackoverflow.com/q/52066815
tags question: http://stackoverflow.com/q/52035338
tags question: http://stackoverflow.com/q/52112118
tags question: http://stackoverflow.com/q/52047314
tags question: http://stackoverflow.com/q/52021003
tags question: http://stackoverflow.com/q/52015279
tags question: http://stackoverflow.com/q/52087812

http://stackoverflow.com/comment/91121022
score: 0
comment on: http://stackoverflow.com/q/52083522
type: Comment
type: QuestionComment
has text: How about [this trick](https://www.tenforums.com/tutorials/46038-turn-off-download-save-prompt-microsoft-edge.html) (ask me what to do with each download)

http://stackoverflow.com/comment/91065143
has text: @HiteshAggarwal You need to use a kernel based on the correct environment. Currently you are not doing that, otherwise you could import any packages installed in said environment.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52053383

http://stackoverflow.com/comment/90887020
has text: I was trying to just give the jist of the code. The actual code is: for row in split_type.itertuples(): where split_type is all the different rows in the dataframe. I think I'll just have to try a different way. Thanks
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51967698

http://stackoverflow.com/comment/91167620
type: Comment
comment on: http://stackoverflow.com/a/52108443
has text: Sorry for the messy code in the first comment. I didn't really know how to format it within the comments. And the second comment is the question he is asking us.
type: AnswerComment
score: 0

http://stackoverflow.com/q/51996087
has answer: http://stackoverflow.com/a/51996148
type: AnsweredQuestion
upvote count: 1
type: Question
score: 1
has title: How to handle Python exceptions when dealing with errors from packages/modules
possible better answer: http://stackoverflow.com/a/51996147
answer count: 2
downvote count: 0
accepted answer: http://stackoverflow.com/a/51996148
favorite count: 0
tagged with: python-3.x
tagged with: exception
has body: I am using an astropy package called WCS.all_world2pix in order to convert many coordinates in degrees to pixel coordinates on an image. While running this on many pairs of coordinates, I eventually came across an error which stopped my program from running. Here is the code leading up the error, and the error itself: import glob import numpy as np import re from astropy.io import fits from astropy.wcs import WCS initial_data, centroid_coords = [], [] image_files = glob.glob('/home/username/Desktop/myfolder/*.fits') for image in image_files: img_data = np.nan_to_num(fits.getdata(image)) obj_num = int(re.search('2\d{6}', image).group(0)) count_num = int(re.search('_(\d+)_', image).group(1)) obj_index = int(np.where(good_data == obj_num)[0]) count_index = int(np.where(np.array(all_counters[obj_index]) == count_num)[0]) ra, dec = pos_match[obj_index][count_index] w = WCS(image) x, y = w.all_world2pix(ra, dec, 0) initial_data.append(img_data) centroid_coords.append((float(x), float(y))) The error: x, y = w.all_world2pix(ra, dec, 0) File "/usr/local/anaconda3/lib/python3.6/site-packages/astropy/wcs/wcs.py", line 1827, in all_world2pix 'input', *args, **kwargs File "/usr/local/anaconda3/lib/python3.6/site-packages/astropy/wcs/wcs.py", line 1269, in _array_converter return _return_list_of_arrays(axes, origin) File "/usr/local/anaconda3/lib/python3.6/site-packages/astropy/wcs/wcs.py", line 1225, in _return_list_of_arrays output = func(xy, origin) File "/usr/local/anaconda3/lib/python3.6/site-packages/astropy/wcs/wcs.py", line 1826, in &lt;lambda&gt; quiet=quiet), File "/usr/local/anaconda3/lib/python3.6/site-packages/astropy/wcs/wcs.py", line 1812, in _all_world2pix slow_conv=ind, divergent=inddiv) astropy.wcs.wcs.NoConvergence: 'WCS.all_world2pix' failed to converge to the requested accuracy. After 2 iterations, the solution is diverging at least for one input point. I would just like to be able to skip over those images that cause this error. But I'm unsure how to handle …
has answer: http://stackoverflow.com/a/51996147
tagged with: python

http://stackoverflow.com/q/52102921
answer count: 1
tagged with: url
downvote count: 0
has comment: http://stackoverflow.com/comment/91156730
tagged with: django-rest-framework
favorite count: 0
has answer: http://stackoverflow.com/a/52103069
has comment: http://stackoverflow.com/comment/91156687
tagged with: python
tagged with: regex
has body: I have: urlpatterns = [ url(r'^tools(?:/tool_one=(?P&lt;tool_one&gt;\w+))?/?$', views.ToolsViews.as_view(), name='tools'), ] the print of url like this: tools/tool_one=bags I want to add a question mark to the url like this: tools/?tool_one=bags I was try to write: urlpatterns = [ url(r'^tools(?:/\?tool_one=(?P&lt;tool_one&gt;\w+))?/?$', views.ToolsViews.as_view(), name='tools'), ] but the question mark didn't exists, the print of url: tools/%3Ftool_one=bags Can anyone give me some hint? What is the problem?
type: UnansweredQuestion
tagged with: django
upvote count: 1
has title: How to add question mark to the url using django?
score: 1
type: Question

http://stackoverflow.com/comment/91122936
type: QuestionComment
comment on: http://stackoverflow.com/q/52086185
has text: Underscores don't normally need to be escaped. In what context do you need to escape them?
type: Comment
score: 1

http://stackoverflow.com/a/51978559
type: AcceptedAnswer
downvote count: 0
type: Answer
score: 3
upvote count: 3
accepted answer of: http://stackoverflow.com/q/51978540
answers question: http://stackoverflow.com/q/51978540
has body: d['vals'] = [x[i] for i in d['inds']] Better yet, do both at once: vals = [] inds = [] for i,v in enumerate(x): if v!=0: vals.append(v) inds.append(i) d['vals']=vals d['inds']=inds or import numpy as np d['inds'],d['vals'] = np.array([(i,v) for i,v in enumerate(x) if v!=0]).T

http://stackoverflow.com/comment/90917812
has text: You need to show the code you tried.
score: 1
comment on: http://stackoverflow.com/q/51984121
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52063337
has comment: http://stackoverflow.com/comment/91078374
possible better answer: http://stackoverflow.com/a/68556908
tagged with: django
tagged with: python
has answer: http://stackoverflow.com/a/68556908
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91078166
has body: I try to setup some periodic tasks with Celery beat on Django. I'm using next setup: python3.6 django==1.11.10 celery==4.2.1 kombu==4.2.1 My schedule worker runs in Docker container via docker-compose and starts with next command: celery -A proj beat --loglevel=debug -s /src/celerybeat-schedule Without periodic tasks added everything is ok and I get these lines in console: [2018-08-28 17:06:05,261: DEBUG/MainProcess] Setting default socket timeout to 30 [2018-08-28 17:06:05,267: INFO/MainProcess] beat: Starting... [2018-08-28 17:06:05,298: DEBUG/MainProcess] Current schedule: [2018-08-28 17:06:05,298: DEBUG/MainProcess] beat: Ticking with max interval-&gt;5.00 minutes [2018-08-28 17:06:05,299: DEBUG/MainProcess] beat: Waking up in 5.00 minutes. But when I try to add periodic task (right after Celery setup): @app.on_after_configure.connect def setup_periodic_tasks(sender): sender.add_periodic_task(10.0, test.s('hello'), name='add every 10') @app.task() def test(arg): print(arg) I get KeyError with this lines: [2018-08-28 17:11:56,666: WARNING/MainProcess] Traceback (most recent call last): [2018-08-28 17:11:56,666: WARNING/MainProcess] File "/usr/local/lib/python3.6/site-packages/kombu/utils/objects.py", line 42, in __get__ [2018-08-28 17:11:56,666: WARNING/MainProcess] return obj.__dict__[self.__name__] [2018-08-28 17:11:56,666: WARNING/MainProcess] KeyError [2018-08-28 17:11:56,666: WARNING/MainProcess] : [2018-08-28 17:11:56,667: WARNING/MainProcess] 'tz' then same errors with 'timezone' and 'data' and then A LOT OF THIS (RecursionError): [2018-08-28 17:11:57,050: WARNING/MainProcess] File "/usr/local/lib/python3.6/collections/__init__.py", line 987, in __getitem__ [2018-08-28 17:11:57,050: WARNING/MainProcess] if key in self.data: [2018-08-28 17:11:57,051: WARNING/MainProcess] File "/usr/local/lib/python3.6/site-packages/celery/utils/collections.py", line 126, in __getattr__ [2018-08-28 17:11:57,051: WARNING/MainProcess] return self[k] [2018-08-28 17:11:57,051: W…
score: 1
has comment: http://stackoverflow.com/comment/91078225
upvote count: 1
has comment: http://stackoverflow.com/comment/91077187
accepted answer: http://stackoverflow.com/a/52083754
tagged with: celery
type: Question
has comment: http://stackoverflow.com/comment/91078348
has comment: http://stackoverflow.com/comment/91078330
answer count: 2
has title: Get RecursionError / KeyError trying to add Periodic Task in Celery beat
downvote count: 0
tagged with: kombu
has comment: http://stackoverflow.com/comment/91077369
favorite count: 0
has comment: http://stackoverflow.com/comment/91077391
has answer: http://stackoverflow.com/a/52083754
has comment: http://stackoverflow.com/comment/91077143
tagged with: celerybeat
has comment: http://stackoverflow.com/comment/91078059
has comment: http://stackoverflow.com/comment/91077420

http://stackoverflow.com/comment/91102416
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52076204
has text: Oh wow, I actually didn't know that. So I could potentially in main just do `if __name__==...`, the run some function from other imported file, and that's how I actually gain some time, right?
type: AnswerComment

http://stackoverflow.com/q/52093555
has comment: http://stackoverflow.com/comment/91214093
tagged with: python
has comment: http://stackoverflow.com/comment/91138408
has comment: http://stackoverflow.com/comment/91138052
tagged with: regex
has answer: http://stackoverflow.com/a/52095284
has comment: http://stackoverflow.com/comment/91138869
type: AnsweredQuestion
has title: Python regular expression for phone numbers
has comment: http://stackoverflow.com/comment/91209564
has comment: http://stackoverflow.com/comment/91138511
score: 1
has comment: http://stackoverflow.com/comment/91137228
upvote count: 1
linked to: http://stackoverflow.com/q/22937618
type: Question
has comment: http://stackoverflow.com/comment/91139701
accepted answer: http://stackoverflow.com/a/52095284
has comment: http://stackoverflow.com/comment/91137172
has comment: http://stackoverflow.com/comment/91137094
has comment: http://stackoverflow.com/comment/91139129
tagged with: regex-greedy
linked to: http://stackoverflow.com/q/123559
has body: I am very new to regular expression &amp; seeking help to parse out phone numbers from HTML text At source site, the html tags are very distorted &amp; does not have any unique selectors that i can use . Below if the list of possibilities i am looking to parse. raw = """+49 39291 55-217 02102 7007064 0152 01680970 +49 39291 55-216 02102 3802 22 0800 333004 451-100 +49 221 9937 26950 02151-47974510 +49(0)6105 937 -539 0211/409 2268 +49(0)6105 937 -539 +49211/584-623 0211 58422 2012 +49 (9131) 7-35335 +49 521 9488 2470 + 49-40-70 70 84 - 0 0211 17 95 99 04 02151-47974327 +49 203 28900 1121 0211 9449-2555 +49 (5 41) 9 98 -2268""" I tried this pattern but could not make out more from it import re, requests Phones = re.findall(re.compile(r'.*?(\(?\d{3}\D{0,3}\d{3}\D{0,3}\d{4}).*?'),raw) phones ['102 7007064', '152 0168097', '151-4797451', '937 -539\n0211', '937 -539\n+4921', '584-623\n0211', '151-4797432'] Any advise or help is highly appreciated. Thank you
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/91139747
has comment: http://stackoverflow.com/comment/91137299
has comment: http://stackoverflow.com/comment/91140401
has comment: http://stackoverflow.com/comment/91139149
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/91137248
has comment: http://stackoverflow.com/comment/91137369

http://stackoverflow.com/comment/90945522
type: QuestionComment
has text: Have you looked into Maya? https://github.com/kennethreitz/maya
type: Comment
comment on: http://stackoverflow.com/q/51997469
score: 0

pip
tags question: http://stackoverflow.com/q/52052645
tags question: http://stackoverflow.com/q/51985203
tags question: http://stackoverflow.com/q/52002684
tags question: http://stackoverflow.com/q/52030010
tags question: http://stackoverflow.com/q/52007436
tags question: http://stackoverflow.com/q/52066829
tags question: http://stackoverflow.com/q/51979903
tags question: http://stackoverflow.com/q/52066156
tags question: http://stackoverflow.com/q/51960985
tags question: http://stackoverflow.com/q/52060533
tags question: http://stackoverflow.com/q/52063082
tags question: http://stackoverflow.com/q/51967191
tags question: http://stackoverflow.com/q/52002400
tags question: http://stackoverflow.com/q/52099487
tags question: http://stackoverflow.com/q/52007128
tags question: http://stackoverflow.com/q/51968505
tags question: http://stackoverflow.com/q/52078733
tags question: http://stackoverflow.com/q/51964106
tags question: http://stackoverflow.com/q/52103780
tags question: http://stackoverflow.com/q/52094131
tags question: http://stackoverflow.com/q/51997619
tags question: http://stackoverflow.com/q/52005509
tags question: http://stackoverflow.com/q/51970789
tag name: pip
tags question: http://stackoverflow.com/q/52092668
tags question: http://stackoverflow.com/q/52008622
tags question: http://stackoverflow.com/q/52042226
tags question: http://stackoverflow.com/q/52066816
tags question: http://stackoverflow.com/q/52009844
tags question: http://stackoverflow.com/q/52102025
tags question: http://stackoverflow.com/q/52038190
tags question: http://stackoverflow.com/q/52076287
tags question: http://stackoverflow.com/q/52082906
tags question: http://stackoverflow.com/q/52029253
tags question: http://stackoverflow.com/q/52029037
tags question: http://stackoverflow.com/q/52015451
tags question: http://stackoverflow.com/q/52011463
tags question: http://stackoverflow.com/q/52027359
tags question: http://stackoverflow.com/q/52036374
tags question: http://stackoverflow.com/q/52041810
tags question: http://stackoverflow.com/q/52060867
type: Tag
tags question: http://stackoverflow.com/q/51992375
tags question: http://stackoverflow.com/q/52063199
tags question: http://stackoverflow.com/q/51996547
tags question: http://stackoverflow.com/q/52012667
tags question: http://stackoverflow.com/q/52012055
tags question: http://stackoverflow.com/q/52053742
tags question: http://stackoverflow.com/q/51963961
tags question: http://stackoverflow.com/q/51998889
tags question: http://stackoverflow.com/q/51988848
tags question: http://stackoverflow.com/q/51991069

http://stackoverflow.com/comment/91077002
has text: compiler @FlyingTeller as it is the name of the compiler within spyder
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52060436

http://stackoverflow.com/comment/91105760
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/52066381
has text: @gasman Possibly of note: running migrations in either of the downgraded versions triggered this error: `django.db.migrations.exceptions.NodeNotFoundError: Migration homecoming_umn_edu.0005_auto_20180825_1456 dependencies reference nonexistent parent node ('wagtailimages', '0021_image_file_hash')`
score: 0

http://stackoverflow.com/q/52023180
has title: ValueError: Data must be 1-dimensional (NeuralNetwork)?
has body: I am making a prediction and implementing a neural network, is currently working with the numpy library and I am adapting the code to the data that I have. I leave the current progress of the neural network, I have an error at the end of the code and I do not understand it well. Anyone who can help me please? import numpy as np from sklearn.cross_validation import train_test_split class LinearLayer: def __init__(self, n_input, n_output): self.n = n_input self.m = n_output self.W = (1/np.sqrt(n_input))*np.random.rand(n_input+1, n_output) def forward(self, X): self.input = np.zeros((X.shape[0],self.n+1)) # if only one feature, the input should always be a batch, at least if len(X.shape) == 1: # of one element self.input[:-1,:] = X.reshape(-1,self.n) else: self.input[:,:-1] = X self.input[:,-1] = 1 self.output = self.input.dot(self.W) # xW + b return self.output def backward(self, d_out): self.gradients = self.W.dot(d_out)[:-1] self.dW = np.einsum("ij,ki", self.input, d_out) return self.gradients def updateWeights(self, lr=0.1): self.W = self.W - lr*self.dW class Sigmoid: def __init__(self, n_input): self.output = np.zeros(n_input) self.gradients = np.zeros(n_input) def forward(self, X): self.output = 1/(np.exp(-X)+1) return self.output def backward(self, d_out): ds = self.output.T*(1 - self.output).T self.gradients = ds*d_out return self.gradients print("Training a multilayer perceptron\n") import pandas as pd data = pd.read_csv('Data_Balanceada.csv') #Data (74,11) X = data.iloc[:,0:11] y = data.iloc[:,-1] X_train, X_test, y_train, y_test = train_test_split(X,y, test_size=0.25, random_state=1) h1 = LinearLayer(11,1) #stack some layers s1 = Sigmoid(7) h2 = LinearLayer(7,1) s2 = Sigmoid(1) def loss(pred, target): return np.mean(np.power(pred-target,2)) predict = lambda x: s2.forward(h2.forward(s1.forward(h1.forward(x)))) backpropagate = lambda d: h1.backward(s1.backward(h2.backward(s2.backward(d)))) lr = 0.005 n = 0 # patience max_epochs = 1500 valid = loss(predict(X_te…
upvote count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/91014523
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91014219
tagged with: python
tagged with: jupyter-notebook
answer count: 0
score: 1
type: Question
tagged with: neural-network

http://stackoverflow.com/q/51970065
score: 0
tagged with: styleframe
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/90897832
tagged with: excel
has comment: http://stackoverflow.com/comment/90894274
tagged with: indexing
has body: I am writing a script in which I want the output to be an Excel sheet with auto-fitted column width's. Further, I want the index column's title to appear. Right now, I run the script and the Excel sheet populates with auto-fitted column width's, but the index column's title does not appear. Is there a quick fix for this? for type in tickers: df5 = pd.DataFrame(df4.diff(periods=1, axis=0)) frames = [df4.iloc[-2,:],df4.iloc[-1,:],df5.iloc[-1,:]] df6 = pd.concat(frames, axis=1, ignore_index=True) df6 = round(df6, 2) df6.columns = ["Last Week ($mm/bp)", "This Week ($mm/bp)", "Change ($mm/bp)"] df6.index.name = "{}".format(type) df6 = df6.reindex(index = ["ED1 Comdty", "TU1 Comdty", "FV1 Comdty", "TY1 Comdty", "UXY1 Comdty", "US1 Comdty", "WN1 Comdty", "Total"]) sf = StyleFrame(df6) sf.to_excel(writer, sheet_name=type, index=True) writer.save()
answer count: 0
type: Question
has title: Why does the index column's title not show when using StyleFrame sf.to_excel()?
tagged with: dataframe

http://stackoverflow.com/a/52112468
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/91175598
has comment: http://stackoverflow.com/comment/91177710
has comment: http://stackoverflow.com/comment/91178478
score: 0
has comment: http://stackoverflow.com/comment/91176040
has comment: http://stackoverflow.com/comment/91178539
type: Answer
has comment: http://stackoverflow.com/comment/91176108
upvote count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/91176276
accepted answer of: http://stackoverflow.com/q/52112188
answers question: http://stackoverflow.com/q/52112188
has comment: http://stackoverflow.com/comment/91176087
has comment: http://stackoverflow.com/comment/91175704
has comment: http://stackoverflow.com/comment/91175909
has comment: http://stackoverflow.com/comment/91178767
has comment: http://stackoverflow.com/comment/91176182
has body: Thumb rule A common cause for Chrome to crash during startup is running Chrome as root user (administrator) on Linux. While it is possible to work around this issue by passing --no-sandbox flag when creating your WebDriver session, such a configuration is unsupported and highly discouraged. You need to configure your environment to run Chrome as a regular user instead. As per your code trials seems you are trying to access a Chrome Profile so you can use the following solution: Code Block: from selenium import webdriver from selenium.webdriver.chrome.options import Options options = Options() options.add_argument("user-data-dir=C:\\path\\to\\your\\profile\\Google\\Chrome\\User Data\\Profile 2") driver = webdriver.Chrome(executable_path=r'C:\path\to\chromedriver.exe', chrome_options=options) driver.get("https://www.google.co.in") Here you can find a detailed discussion in How to open a Chrome Profile through Python

http://stackoverflow.com/comment/91057808
type: QuestionComment
comment on: http://stackoverflow.com/q/52053685
score: 0
has text: But then I have to give f2 the same arguments as f. And I may have already written f, and want to leave it unchanged. I just want to add something that performs the last line of f2.
type: Comment

http://stackoverflow.com/comment/90977712
score: 2
has text: Note: Many `float` operations that, with real numbers, would result in an integer value will not do so with `float`s. `1.1 * 3 - 0.3` is, to any fifth grader, supposed to result in `3`. But in `float` math, it comes out to `3.0000000000000004` (on my machine anyway), and `is_integer()` on the result returns `False`. If you need decimal precision, I'd recommend using `decimal.Decimal`, not `float`.
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52013419

http://stackoverflow.com/comment/90935070
comment on: http://stackoverflow.com/a/51992497
score: 1
type: AnswerComment
has text: @KevinM1990112qwq If you're using Anaconda, why did you `pip install pyaudio` instead of `conda install pyaudio`?
type: Comment

http://stackoverflow.com/q/52057540
has answer: http://stackoverflow.com/a/68575456
has title: Redirecting Python's console output to Dash
upvote count: 10
tagged with: plotly-dash
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52071560
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/52064336
linked to: http://stackoverflow.com/q/3118059
type: Question
accepted answer: http://stackoverflow.com/a/52071560
has body: How can I redirect/show the console output (including outputs I print inside the program) so it would appear inside a Dash app (On the screen the user sees)?
tagged with: python
score: 10
tagged with: plotly
answer count: 3
possible better answer: http://stackoverflow.com/a/68575456

http://stackoverflow.com/comment/91144630
type: Comment
comment on: http://stackoverflow.com/a/52096924
has text: @Vetos I would be interested to know if you ever found a way to customise the rest.
type: AnswerComment
score: 0

http://stackoverflow.com/q/52043231
favorite count: 0
has answer: http://stackoverflow.com/a/52044768
tagged with: django
tagged with: python
type: AnsweredQuestion
has title: Using a different Manager with refresh_from_db()
score: 1
tagged with: orm
upvote count: 1
type: Question
has body: I have model set up in a way that it never gets deleted, instead a status is updated to status 'DELETED'. To achieve this I have overridden the delete() method as following def delete(self, using=None, keep_parents=False): self.status = Booking.DELETED self.save() And added two custom managers to track deleted an non deleted bookings, the standard manager is swapped with on that only returns non deleted objects. class BookingManager(models.Manager): def get_queryset(self): return super().get_queryset().exclude(status=Booking.DELETED) class BookingDeletedManager(models.Manager): def get_queryset(self): return super().get_queryset().filter(status=Booking.DELETED) class Booking(models.Model): PAYED = 0 PENDING = 1 OPEN = 2 CANCELLED = 3 DELETED = 4 objects = BookingManager() deleted_objects = BookingDeletedManager() ... Now when i have a booking object and delete it like this booking.delete() And refresh it like this booking.refresh_from_db() I get the error .models.DoesNotExist: Booking matching query does not exist If i use the correct manager Booking.deleted_objects.get(pk=booking.id) I get the booking correctly presented to me, I am assuming the refresh_from_db method used the standard objects manager which does not find the correct Booking. is there a way to get around this or am i approaching this problem wrong?
accepted answer: http://stackoverflow.com/a/52044768
downvote count: 0
answer count: 1

http://stackoverflow.com/q/52050732
has body: I would like to know whether a function could return a loop? My code is as follow: def looping(): a = [25,50,75,100, 200, 300] for x in a: return x print(looping()) When I print it it returned: Output: [25] Expected output: 25 50 75 100 200 300 Is this possible?
has comment: http://stackoverflow.com/comment/91051653
has comment: http://stackoverflow.com/comment/91051667
has answer: http://stackoverflow.com/a/52050961
accepted answer: http://stackoverflow.com/a/52050961
type: AnsweredQuestion
has title: How to write a function that return a loop?
tagged with: loops
type: Question
score: 0
has answer: http://stackoverflow.com/a/52050810
has answer: http://stackoverflow.com/a/52050971
answer count: 3
has comment: http://stackoverflow.com/comment/91051706
possible better answer: http://stackoverflow.com/a/52050810
tagged with: python

http://stackoverflow.com/comment/91020992
type: Comment
comment on: http://stackoverflow.com/a/52026439
score: 0
has text: I dont know , where did you saw this snipp ? I guessed its like (etc ...) :D
type: AnswerComment

http://stackoverflow.com/comment/90891584
comment on: http://stackoverflow.com/q/51970555
has text: The whole point of a CAPTCHA is to prevent the kind of thing you're doing (software pretending to be a human). I don't think this is going to be easy to bypass, and looping through 30 pages of results is probably against their terms of use.
type: QuestionComment
type: Comment
score: 2

http://stackoverflow.com/a/61309708
has body: Why do you want to convert it to a list first? The DataFrame() method accepts data which can be iterable. Sets are iterable. dataFrame = pandas.DataFrame(yourSet) This will create a column header: "0" which you can rename it like so: dataFrame.columns = ['columnName']
answers question: http://stackoverflow.com/q/52082100
type: Answer
score: 4
upvote count: 4
downvote count: 0

http://stackoverflow.com/a/52039414
type: Answer
answers question: http://stackoverflow.com/q/52038163
has comment: http://stackoverflow.com/comment/91036215
has body: As described in the docs, you can change the fields to display, filters, ordering, etc. Example: from django.contrib.auth.models import User class SiteMemberAdmin(UserAdmin): model = SiteMember add_form = SiteMemberCreationForm form = SiteMemberChangeForm # The fields to be used in displaying the User model. # These override the definitions on the base UserAdmin # that reference specific fields on auth.User. list_display = ('email', 'date_of_birth', 'is_admin') list_filter = ('is_admin',) fieldsets = ( (None, {'fields': ('email', 'password')}), ('Personal info', {'fields': ('date_of_birth',)}), ('Permissions', {'fields': ('is_admin',)}), ) # add_fieldsets is not a standard ModelAdmin attribute. UserAdmin # overrides get_fieldsets to use this attribute when creating a user. add_fieldsets = ( (None, { 'classes': ('wide',), 'fields': ('email', 'date_of_birth', 'password1', 'password2')} ), ) search_fields = ('email',) ordering = ('email',) filter_horizontal = () admin.site.register(SiteMember, SiteMemberAdmin)
score: 0

http://stackoverflow.com/q/52112142
type: Question
has comment: http://stackoverflow.com/comment/91175014
has body: I am trying to web scrape a website but I keep getting this "Browser not supported" error. Does anyone know how to fix this? Thanks. import bs4 import requests headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) ' 'Chrome/39.0.2171.95 Safari/537.36'} session = requests.get("https://revengeofficial.com/webstore", headers=headers) page = bs4.BeautifulSoup(session.text, "html.parser") print(page.title.text) Output: http://prntscr.com/kozv1x Edit: After multiple attempts I still cannot find a solution, can anyone else help?
answer count: 2
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/91174827
favorite count: 0
tagged with: beautifulsoup
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/52112349
tagged with: python
has comment: http://stackoverflow.com/comment/91175260
has comment: http://stackoverflow.com/comment/91174875
has answer: http://stackoverflow.com/a/52112319
has title: "Browser Not Supported" Error When Web Scraping With BeautifulSoup
upvote count: 1
tagged with: web-scraping

http://stackoverflow.com/comment/90902525
has text: What do you mean by nested exactly? What's the kind of nesting that you don't want to eliminate unless there's absolutely no other way?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51975792

http://stackoverflow.com/q/52032189
has comment: http://stackoverflow.com/comment/91045436
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/52045542
possible better answer: http://stackoverflow.com/a/52032290
accepted answer: http://stackoverflow.com/a/52045542
has comment: http://stackoverflow.com/comment/91015206
has comment: http://stackoverflow.com/comment/91040342
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/91015484
has comment: http://stackoverflow.com/comment/91041938
tagged with: python
has comment: http://stackoverflow.com/comment/91015544
has comment: http://stackoverflow.com/comment/91014742
type: AnsweredQuestion
has body: I wrote some code to parse XML and output the parsed information to two files. I then read those files and submit to a site with requests POST module. When I try to append the response from said POST to a file, I've been receiving PermissionError, [Errno 13] Permission Denied error (from line 112, submittoSite function in the code posted below). The section it's happening is thus: with open(xmfp + "nsresponse.csv", "a") as responsefile: responsefile.write(r.text + ", %d" % r.status_code + "\n") Why is the file giving me a permission denied error, when I'm only writing it directly in line with the function? I write to the files that I'm parsing the XML out to fine, and this doesn't happen. It's at the end of a function. It's not trying to do more than one at a time, like threading, and doesn't a 'with' statement close the file once it's done? Before saying something like 'write it to an array and then write it all to a file at once', I'm specifically not doing that because I'm doing 250k'ish POST calls (one of the reasons I wanted to multithread it) and I'm trying to keep RAM down. Here's the full code (slightly edited due to work things) NOTE: If you've read the code and are wondering about the threading stuff, I realize the multithreading stuff in there is extraneous now, but I'm still hoping that at some point I'll figure out how to get that to run without them interfering with each other, even if I have to rewrite stuff, so I'm just leaving it in there while I work on this.
has answer: http://stackoverflow.com/a/52032290
has title: Permission denied error on filewrite function
upvote count: 1
downvote count: 1
type: Question
tagged with: permission-denied
has comment: http://stackoverflow.com/comment/91015622

http://stackoverflow.com/a/52010283
has body: You need to explicitly take all the arguments you need in the subclass initialiser, and pass them through to the superclass, by using args and kwargs: class indentity_resolve_delta(indentity_resolve): def __init__(self, resolved_pii_location_block, *args, **kwargs): super().__init__(*args, **kwargs) self.resolved_pii_location_block = resolved_pii_location_block For more info about args and kwargs: *args **kwargs
answers question: http://stackoverflow.com/q/52008482
score: 0
type: Answer

http://stackoverflow.com/comment/134866309
type: Comment
score: 2
comment on: http://stackoverflow.com/a/74415667
has text: pyenv 2.3.20-3-g38ac7472 says no such command `pip`.
type: AnswerComment

http://stackoverflow.com/q/51963260
has comment: http://stackoverflow.com/comment/90876659
has body: I tried to extract the hour of day from a series column. My data looks like this: Unique Key Created Date 32305299 2016-01-01 00:00:09 Which 'Created date' being series: type(df['Created Date']) pandas.core.series.Series I tried below but didn't work: df['Created Date'].dt.hour Error message: AttributeError: Can only use .dt accessor with datetimelike values How can I extract the hour of day in this case? Thanks!
tagged with: pandas
has comment: http://stackoverflow.com/comment/90877500
favorite count: 0
linked to: http://stackoverflow.com/q/17134716
has comment: http://stackoverflow.com/comment/90877337
tagged with: python-3.x
type: UnansweredQuestion
tagged with: python
answer count: 0
has comment: http://stackoverflow.com/comment/90877307
score: 1
has comment: http://stackoverflow.com/comment/90880724
upvote count: 1
type: Question
duplicate of: http://stackoverflow.com/q/17134716
downvote count: 0
has title: How to extract hour from a series

http://stackoverflow.com/comment/91048340
has text: Incorrect, otherwise tk continues to call the function callback specified in .after()
type: AnswerComment
comment on: http://stackoverflow.com/a/52031651
score: 0
type: Comment

http://stackoverflow.com/comment/91113044
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52081009
has text: @FHTMitchell oh yeh possibly (certainly that is more readalble) but i'd have to `timeit` to be sure

http://stackoverflow.com/q/52010637
has comment: http://stackoverflow.com/comment/90972340
type: Question
has title: Handling trailing newlines with Python str.splitlines()
accepted answer: http://stackoverflow.com/a/52010724
has body: I'm implementing text drawing on an image, and am trying to handle newlines by implementing a "text cursor" that advances appropriately. I have a solution for handling trailing newlines, but it's ugly and un-Pythonic. What would be the Pythonic way? Here's what I'm doing now (simplified code for example purposes): # string may contain zero or more newlines, may or may not terminate in a newline def text(string): for line in string.splitlines(): global x_cursor, y_cursor # pixel location of cursor in image x_size_of_text = draw_one_line_of_text(line) old_x_cursor = x_cursor x_cursor = 0 y_cursor += 20 # lines are 20 pixels high if string[-1] != '\n': # if no trailing newline, undo final newline x_cursor = old_x_cursor + x_size_of_text y_cursor -= 20 I do a newline after every line returned by string.splitline(), and then undo the newline if the original string didn't terminate in a newline. This works, but it's ugly. What's the right way to do it?
downvote count: 0
answer count: 1
tagged with: string
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/90972344
tagged with: python
score: 2
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52010724
upvote count: 2

http://stackoverflow.com/comment/91061431
type: Comment
type: QuestionComment
has text: @JoachimMorken Have you tried the piece of code I gave? If it doesn't perform what you're looking for, it means that I'm missing something. But IIUC it should.
comment on: http://stackoverflow.com/q/52053698
score: 0

http://stackoverflow.com/a/52026106
has body: Lists are not like arrays in other languages; they do not have a predetermined size and are not sparse. Hence, assigning to a specific index when the list has length 0 throws an IndexError because you are saying "re-assign the i-th element to be this" when there is no i-th element". Instead, you want to append elements to the end of the list. Also, your code has many other confusing parts to it, so rather than trying to muddle through it, the following code will simply produce a list of strings of the contents of each file in the current working directory (note that this will include the Python script itself, so you may want to filter out the name of the script). import os file_data = [] files_in_cwd = os.listdir() for file_name in files_in_cwd: with open(file_name) as file_handler: file_data.append(file_handler.read()) print(file_data) Note that you should always use a with statement when opening files and that mode='r' is the default, also the usual way of creating an empty list is with [].
score: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/52025887
answers question: http://stackoverflow.com/q/52025887
has comment: http://stackoverflow.com/comment/91003060
type: AcceptedAnswer

http://stackoverflow.com/q/52012071
has title: Tensorflow Model Add issue for text generation
type: Question
downvote count: 0
answer count: 1
favorite count: 0
tagged with: python
type: UnansweredQuestion
upvote count: 1
has answer: http://stackoverflow.com/a/52014850
has body: I'm following along this model, Text Generators, and I'm stuck. This is my first tensorflow attempt so I'm not sure what the issue is but, since it worked in the tutorial and it isn't working for me, seems like there was maybe an update. Has model.add's format changed? I'm not sure how to troubleshoot this issue since I'm so new to the library. model = Sequential() model.add(LSTM(400, input_shape=(X_modified.shape[1], X_modified.shape[2]), return_sequences=True)) model.add(Dropout(0.2)) model.add(LSTM(400)) model.add(Dropout(0.2)) model.add(Dense(Y_modified.shape[1], activation='softmax')) model.compile(loss='categorical_crossentropy', optimizer='adam') Throws the error --------------------------------------------------------------------------- TypeError Traceback (most recent call last) &lt;ipython-input-75-5a0fde131e03&gt; in &lt;module&gt;() 1 model = Sequential() ----&gt; 2 model.add(LSTM(400, input_shape=(X_modified.shape[1], X_modified.shape[2]), return_sequences=True)) 3 model.add(Dropout(0.2)) 4 model.add(LSTM(400)) 5 model.add(Dropout(0.2)) ~/anaconda/envs/dataweekends/lib/python3.7/site-packages/keras/engine/sequential.py in add(self, layer) 162 # and create the node connecting the current layer 163 # to the input layer we just created. --&gt; 164 layer(x) 165 set_inputs = True 166 else: ~/anaconda/envs/dataweekends/lib/python3.7/site-packages/keras/layers/recurrent.py in __call__(self, inputs, initial_state, constants, **kwargs) 498 499 if initial_state is None and constants is None: --&gt; 500 return super(RNN, self).__call__(inputs, **kwargs) 501 502 # If any of `initial_state` or `constants` are specified and are Keras ~/anaconda/envs/dataweekends/lib/python3.7/site-packages/keras/engine/base_layer.py in __call__(self, inputs, **kwargs) 429 'You can build it manually via: ' 430 '`layer.build(batch_input_shape)`') --&gt; 431 self.build(unpack_singleton(input_shapes)) 432 self.built = True 433 ~/anaconda/envs/dataweekends/lib/python3.7/site-packages/kera…
tagged with: tensorflow
score: 1

folium
tags question: http://stackoverflow.com/q/52014444
tags question: http://stackoverflow.com/q/51961848
tags question: http://stackoverflow.com/q/51989253
tag name: folium
type: Tag

http://stackoverflow.com/a/52064785
downvote count: 0
score: 4
accepted answer of: http://stackoverflow.com/q/52064478
type: AcceptedAnswer
has body: You need to make a slight change to the CreateForm class in your forms.py: class CreateForm(forms.ModelForm): def __init__(self,*args,**kwargs): user = kwargs.pop('user') super(CreateForm,self).__init__(*args,**kwargs) self.fields['universe'].queryset = Universe.objects.filter(user=user) class Meta: model = Character fields = ('universe','name') That will then pull through the returned Universe objects into the universe field, but only for the currently logged in user.
answers question: http://stackoverflow.com/q/52064478
has comment: http://stackoverflow.com/comment/91080282
type: Answer
upvote count: 4

http://stackoverflow.com/comment/109049217
has text: Yes - if python was installed using Anaconda, conda install awscli will work.
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/55397285

http://stackoverflow.com/q/52073960
answer count: 2
accepted answer: http://stackoverflow.com/a/52074307
tagged with: numpy
upvote count: 5
tagged with: arrays
has title: str() method on numpy array and back
linked to: http://stackoverflow.com/q/51144127
type: AnsweredQuestion
has body: Is there any built-in method to get back numpy array after applying str() method, for example, import numpy as np a = np.array([[1.1, 2.2, 3.3], [4.4, 5.5, 6.6]]) a_str = str(a) #to get back a? a = some_method(a_str). Following two methods don't work: from ast import literal_eval a = literal_eval(a_str) # Error import numpy as np a = np.fromstring(a_str) # Error Update 1: Unfortunatelly i have very big data already converted with str() method so I connot reconvert it with some other method.
has comment: http://stackoverflow.com/comment/91115208
downvote count: 0
tagged with: string
possible better answer: http://stackoverflow.com/a/52074324
favorite count: 0
tagged with: string-literals
has answer: http://stackoverflow.com/a/52074307
has answer: http://stackoverflow.com/a/52074324
type: Question
score: 5
has comment: http://stackoverflow.com/comment/91099339
tagged with: python

http://stackoverflow.com/comment/90950952
score: 0
type: Comment
type: QuestionComment
has text: @Aran-Fey I see now thank you mate
comment on: http://stackoverflow.com/q/52000635

http://stackoverflow.com/a/52043225
type: Answer
has body: It is a problem with the stack during recursion. Python has a low recursion limit issue even if you stated this limit explicitly. This problem is mentioned in this codeforces blog: https://codeforces.com/blog/entry/45135/ One solution is to implement function topo using an iterative approach rather than the recursive approach. The changed code can be: import sys flag=True sys.setrecursionlimit(2000000000) c=[];st=[]; cur_adj=[] def topo(s):#Traversing the array and storing the vertices global c,st,flag; stack = [s] while(stack): s = stack[-1] c[s]=1; #Being Visited if(cur_adj[s] &lt; len(adjli[s])): cur = adjli[s][cur_adj[s]] if(c[cur]==0): stack.append(cur) if(c[cur]==1): flag=False# If Back Edge , Then Not Possible cur_adj[s]+=1 else: c[s]=2 st.append(str(s)) del stack[-1] try: n,k=map(int,input().split(' ')) main=list(map(int,input().split(' '))) depen=[] for i in range(n): depen.append(list(map(int,input().split(' ')))[1:]);c.append(0) cur_adj.append(0) c.append(0) cur_adj.append(0) adjli=[] adjli.append(main)#Assuming Main Course at index 0 with dependencies as Main Dependency(main) for i in range(len(depen)): adjli.append(depen[i])#Appending Other Dependencies topo(0)#TopoLogical Sort Order st.pop(-1)#popping the assumed Main Couse if flag:# IF possible then print print(len(st)) print(' '.join(st)) else: print(-1) except Exception as e: print(e,"error") This code implements what the stack does during recursion. cur_adj is a list where cur_adj[i] holds the index of i's adjacent node to visit next. Once all i's adjacent nodes are visited, i is popped from stack (stack is a normal list which imitates the recursion stack).
has comment: http://stackoverflow.com/comment/91046702
accepted answer of: http://stackoverflow.com/q/52035315
score: 0
answers question: http://stackoverflow.com/q/52035315
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/91047541

http://stackoverflow.com/comment/91109420
type: QuestionComment
has text: If this is of some help, I want to clarify that I am running the ipython script on a new window created through tmux, so maybe that could be the root of the problem
comment on: http://stackoverflow.com/q/52079637
score: 0
type: Comment

http://stackoverflow.com/a/52087221
downvote count: 0
has comment: http://stackoverflow.com/comment/91297737
answers question: http://stackoverflow.com/q/52087192
score: 5
has comment: http://stackoverflow.com/comment/91133902
has comment: http://stackoverflow.com/comment/91133455
upvote count: 5
has body: Here's one vectorized approach leveraging broadcasting and masking/boolean-indexing - r = np.arange(dimension) mask = r[:,None] &lt; r # Or in one step : ~np.tri(dimension,dtype=bool) matrix[mask] = register matrix.T[mask] = register If you need to compute dimension from the given register, we could use : dimension = int(np.ceil(np.sqrt(2*len(register)))) And to assert for length, given dimension, we could have : assert dimension*(dimension-1)//2 == len(register) Also, for performance do consider feeding in the array version of register. Sample run - In [43]: import numpy as np ...: dimension = 4 # other matrices' dimensions will be larger ...: matrix = np.zeros((dimension,dimension)) ...: ...: register = [11, 12, 13, 23, 24, 34] In [44]: r = np.arange(dimension) ...: mask = r[:,None] &lt; r ...: matrix[mask] = register ...: matrix.T[mask] = register In [45]: matrix Out[45]: array([[ 0., 11., 12., 13.], [11., 0., 23., 24.], [12., 23., 0., 34.], [13., 24., 34., 0.]]) How masking could be better than generating all triangular indices Generating the indices would occupy more memory than creating a boolean array which by its very nature would be memory efficient and hence translates to better performance, especially on large arrays. Timings on this would try to prove it - In [3]: import numpy as np ...: dimension = 5000 # other matrices' dimensions will be larger ...: register = np.random.randint(0,10,dimension*(dimension-1)//2) # With masking and boolean-indexing In [4]: %%timeit ...: matrix = np.zeros((dimension,dimension),dtype=int) ...: r = np.arange(dimension) ...: mask = r[:,None] &lt; r ...: matrix[mask] = register ...: matrix.T[mask] = register 10 loops, best of 3: 108 ms per loop # With triangular indices indexing In [5]: %%timeit ...: N = dimension ...: matrix = np.zeros((dimension,dimension),dtype=int) ...: idx = np.triu_indices(N, k=1) ...: matrix = np.zeros((N, N)) ...: matrix[idx] = register ...: matrix.T[idx] = register 1 loop, best of 3: 364 ms per loop
type: Answer

http://stackoverflow.com/comment/91115556
score: 0
has text: Could you please expand on the reason why the syntax `from package import *` is not great? Is there any situation where it can be useful? Should I import each module with his own name, or at max, using `import module as mod`?
type: Comment
comment on: http://stackoverflow.com/a/52082439
type: AnswerComment

http://stackoverflow.com/comment/90975219
comment on: http://stackoverflow.com/a/51990228
type: AnswerComment
score: 0
type: Comment
has text: If you just want to concatenate columns, pandas will broadcast the `+` operator, i.e `df[col1]+df[col2]` will generate a column in which entry is the concatenation of `df[colq]` and `df[col2]` for that row.

http://stackoverflow.com/comment/91096139
comment on: http://stackoverflow.com/a/52050946
score: 0
type: AnswerComment
has text: Oh, you should've made it clearer. Anyway, if you have the `xml` files in you test and train directories, your code should run perfectly
type: Comment

awk
tag name: awk
tags question: http://stackoverflow.com/q/52022692
type: Tag

http://stackoverflow.com/q/52099874
downvote count: 2
has title: Why are placeholders used in python?
favorite count: 0
upvote count: 0
type: UnansweredQuestion
tagged with: python
type: Question
has answer: http://stackoverflow.com/a/52100076
score: -2
answer count: 1
has body: a = "hello" b = 32 print('%s %d' % (a, b)) print(a,b) Both print statement will give out same output i.e hello 32. But using print(a,b) is much easier then the other method so why the concept of placeholders exist in python.
has comment: http://stackoverflow.com/comment/91150524

http://stackoverflow.com/comment/91151118
score: 0
type: AnswerComment
type: Comment
has text: You are quite illegible to disagree :) But note that a MAC is proven secure for modern crypto, and if can use a modern stream cipher you can certainly also use a modern MAC or authenticated mode of encryption. For classic Vigenere ciphers and the like, padding doesn't work that well. For instance, it is easy to miss mistakes if the key is larger than the padding (see the key in the question!). But yeah, sure, any known plaintext can give an *rough indication* - if it *fails* then something is definitely wrong.
comment on: http://stackoverflow.com/a/52029098

http://stackoverflow.com/comment/91063400
type: Comment
comment on: http://stackoverflow.com/a/52055048
score: 0
type: AnswerComment
has text: I know there are Instagram APIs but I was just testing beautyfulsoap library. That's okay. Thanks

http://stackoverflow.com/q/52098893
has comment: http://stackoverflow.com/comment/91148326
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91149844
tagged with: python
has comment: http://stackoverflow.com/comment/91149764
has comment: http://stackoverflow.com/comment/91149510
has comment: http://stackoverflow.com/comment/91149462
has comment: http://stackoverflow.com/comment/91148507
has comment: http://stackoverflow.com/comment/91148337
has body: I have a multiple directory and each has files in thousands(10k+).. Lets pick one directory A having 10k files . I have some another directory(say it as B) that has files in thousands. I'm trying to find all files that appear in both A and B and also have a particular file extension (let's say .docx). I can apply a nested for loop easily, but as the files are in many thousands, it takes lot of time. Is there any faster way in python to perform it? Any specific algo you want to suggest or any snippet code ? Note - I know how to search and get files in multiple ways, I am asking suggestion for the fastest approach, files are in millions and iterating through each again and again will cost resource..
has answer: http://stackoverflow.com/a/52099100
has comment: http://stackoverflow.com/comment/91149325
type: Question
has title: Fastest way to search files in a directory -Python
has comment: http://stackoverflow.com/comment/91148275
has answer: http://stackoverflow.com/a/52098956
linked to: http://stackoverflow.com/q/3964681
has comment: http://stackoverflow.com/comment/91148870
has comment: http://stackoverflow.com/comment/91149070
has answer: http://stackoverflow.com/a/52100354
has comment: http://stackoverflow.com/comment/91148539
score: 0
answer count: 3
tagged with: pandas

http://stackoverflow.com/a/51994187
has body: This code preserves all but the last two characters in their original state. To that, it appends the final two characters in upper case. location = "new orleans, la" location = location[0:-2] + location[-2:].upper() You got cut off because that's exactly what you told it to do: take all characters up to -- but not including -- the last one, convert them all to upper-case, and make that the new value of location. Result: 'new orleans, LA'
has comment: http://stackoverflow.com/comment/90938323
upvote count: 3
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/51994177
accepted answer of: http://stackoverflow.com/q/51994177
type: Answer
score: 3
downvote count: 0

http://stackoverflow.com/q/52022867
accepted answer: http://stackoverflow.com/a/52022948
type: Question
tagged with: numpy
has body: Consider arrays: a = np.array([[nan, 0., 0.], [nan, 1., 1.], [nan, 2., nan]]) b = np.array([2., 0., 0.]) I'm trying to achieve the following: take x, which is not missing element in a replace corresponding item in b with x take sum of that array. In that case it is: For row = 2, col = 1 a[row, col] -&gt; 2. # 1st col Replace 1st element in `b` with 2.: [2., 2., 0.] Full matrix: [[nan, sum([2,0,0]), sum([2,0,0])], [nan, sum([2,1,0]), sum([2,0,1])], [nan, sum([2,2,0]), nan]] result = [[nan, 2, 2], [nan, 3, 3], [nan, 4, nan]] How to achieve that result?
has answer: http://stackoverflow.com/a/52022915
has answer: http://stackoverflow.com/a/52022948
upvote count: 2
answer count: 2
tagged with: matrix
has comment: http://stackoverflow.com/comment/90996109
has comment: http://stackoverflow.com/comment/90996036
favorite count: 0
possible better answer: http://stackoverflow.com/a/52022915
tagged with: python
score: 2
has comment: http://stackoverflow.com/comment/90996057
type: AnsweredQuestion
downvote count: 0
has title: Element-wise apply
has comment: http://stackoverflow.com/comment/90996100

http://stackoverflow.com/q/51992596
accepted answer: http://stackoverflow.com/a/51992741
favorite count: 0
tagged with: pandas
has comment: http://stackoverflow.com/comment/90972650
tagged with: python
has comment: http://stackoverflow.com/comment/90935282
has body: I have a data frame with columns a,b,c,d a b c d 1 2 nan nan 2 3 4 5 4 5 nan nan how do i reshape into 2 columns, when i am not aware of the number of rows that the result will give. (big data) output: a b 1 2 2 3 4 5 4 5
upvote count: 1
type: Question
type: AnsweredQuestion
score: 1
tagged with: dataframe
has answer: http://stackoverflow.com/a/51992741
has title: If dataframe length exceeds threshold, make a new row python
downvote count: 0
answer count: 1

http://stackoverflow.com/comment/90901052
has text: @code_onkel done
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51975080

http://stackoverflow.com/q/52078244
score: 0
answer count: 1
has title: MongoDB optimize multiple find_one + insert inside loop
tagged with: python
type: AnsweredQuestion
tagged with: pymongo
has comment: http://stackoverflow.com/comment/91113732
has answer: http://stackoverflow.com/a/52117885
accepted answer: http://stackoverflow.com/a/52117885
has comment: http://stackoverflow.com/comment/91133788
has body: I'm using MongoDB 4.0.1 and Pymongo with pyhton 3.5. I have to loop over 12000 items every 30 - 60 seconds and add new data into MongoDB. For this example we will talk about User, Pet and Car. The User can get 1 Car and 1 Pet. I need the pet ObjectID and the car ObjectID to create my User so I have to add them one by one in the loop and this is very slow. It takes ~25 seconds to find existing data and add them if the data not exist. while dictionary != False: # Create pet if not exist existing_pet = pet.find_one({"code": dictionary['pet_code']}) if bool(existing_pet): pet_id = existing_pet['_id'] else: pet_id = pet.insert({ "code" : dictionary['pet_code'], "name" : dictionary['name'] }) # Call web service to create pet remote # Create car if not exist existing_car = car.find_one({"platenumber": dictionary['platenumber']}) if bool(existing_car): car_id = existing_car['_id'] else: car_id = car.insert({ "platenumber" : dictionary['platenumber'], "model" : dictionary['model'], "energy" : 'electric' }) # Call web service to create car remote # Create user if not exist existing_user = user.find_one( {"$and": [ {"user_code": dictionary['user_code']}, {"car": car_id}, {"pet": pet_id} ]} ) if not bool(existing_user): user_data.append({ "pet" : pet_id, "car" : car_id, "firstname" : dictionary['firstname'], "lastname" : dictionary['lastname'] }) # Call web service to create user remote # Bulk insert user if user_data: user.insert_many(user_data) I created indexes for each column used for the find_one : db.user.createIndex( { user_code: 1 } ) db.user.createIndex( { pet: 1 } ) db.user.createIndex( { car: 1 } ) db.pet.createIndex( { pet_code: 1 }, { unique: true } ) db.car.createIndex( { platenumber: 1 }, { unique: true } ) There is a way to speed up this loop ? There is something with aggregation or other things to help me ? Or maybe another way to do what I want ? I'm open for all advices.
type: Question
tagged with: mongodb
linked to: http://stackoverflow.com/q/52834594
tagged with: optimization

http://stackoverflow.com/comment/90914131
type: Comment
has text: I have 58 python list so `lists = [list1,list2,...,list58]` and I should type manually?
type: AnswerComment
comment on: http://stackoverflow.com/a/51979960
score: 0

http://stackoverflow.com/q/51968542
tagged with: dataframe
has answer: http://stackoverflow.com/a/51968829
type: Question
downvote count: 0
tagged with: counter
tagged with: series
has title: Python DataFrame column with list of strings does not flatten
tagged with: pandas
answer count: 1
favorite count: 0
has body: I have a column in a DataFrame (production_company) which has a list of strings that are production companies for a movie. I want to search for all unique occurrence of a production company across all movies. In the data below I have given a sample of the column values in production_company. "['Universal Studios', 'Amblin Entertainment', 'Legendary Pictures', 'Fuji Television Network', 'Dentsu']" "['Village Roadshow Pictures', 'Kennedy Miller Productions']" "['Summit Entertainment', 'Mandeville Films', 'Red Wagon Entertainment', 'NeoReel']" "['Lucasfilm', 'Truenorth Productions', 'Bad Robot']" "['Universal Pictures', 'Original Film', 'Media Rights Capital', 'Dentsu', 'One Race Films']" "['Regency Enterprises', 'Appian Way', 'CatchPlay', 'Anonymous Content', 'New Regency Pictures']" I am trying to first flatten the column using a solution to flatten given in Pandas Series of lists to one series But I get error 'TypeError: 'float' object is not iterable' 17 slist =[] 18 for company in production_companies: ---&gt; 19 slist.extend(company ) 20 21 TypeError: 'float' object is not iterable production_companies holds the column df['production_company'] Company is a list so why is it taking it as float? Even list comprehension gives the same error: flattened_list = [y for x in production_companies for y in x]
upvote count: 2
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90887525
tagged with: python
score: 2
linked to: http://stackoverflow.com/q/30885005

http://stackoverflow.com/comment/122819883
comment on: http://stackoverflow.com/a/69486777
type: AnswerComment
type: Comment
score: 3
has text: Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer).

http://stackoverflow.com/comment/91014928
score: 2
has text: @T.Woody note: `any` and `all` are not keywords but builtins (`for` and `in` are keywords). @Stoner `all()` ensures all conditions are `True`, `any()` ensures at least one condition is `True`.
type: AnswerComment
comment on: http://stackoverflow.com/a/52032309
type: Comment

http://stackoverflow.com/comment/91315091
has text: No i don't please check
score: 0
comment on: http://stackoverflow.com/q/52018196
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52045098
downvote count: 1
tagged with: anaconda
score: -1
type: Question
upvote count: 0
answer count: 1
favorite count: 0
has title: /usr/local/bin/python3: No module named pip Error on or near line 85; exiting with status 1
tagged with: intel
has body: (ankit) ankit@ankit-HP-Notebook:~/intel/computer_vision_sdk_2018.3.343/deployment_tools/demo/ $./demo_squeezenet_download_convert_run.sh ################################################### Downloading the Caffe model and the prototxt Installing dependencies Run sudo -E apt -y install build-essential python3-pip virtualenv cmake libpng12-dev libcairo2-dev libpango1.0-dev libglib2.0-dev libgtk2.0-dev libswscale-dev libavcodec-dev libavformat-dev libgstreamer1.0-0 gstreamer1.0-plugins-base Hit:1 https://download.docker.com/linux/ubuntu xenial InRelease Hit:2 http://archive.canonical.com xenial InRelease Reading package lists... Done Building dependency tree Reading state information... Done 1 package can be upgraded. Run 'apt list --upgradable' to see it. Reading package lists... Done Building dependency tree Reading state information... Done build-essential is already the newest version (12.1ubuntu2). libcairo2-dev is already the newest version (1.14.6-1). libpango1.0-dev is already the newest version (1.38.1-1). cmake is already the newest version (3.5.1-1ubuntu3). gstreamer1.0-plugins-base is already the newest version (1.8.3-1ubuntu0.2). libglib2.0-dev is already the newest version (2.48.2-0ubuntu4). libgstreamer1.0-0 is already the newest version (1.8.3-1~ubuntu0.1). libgtk2.0-dev is already the newest version (2.24.30-1ubuntu1.16.04.2). libpng12-dev is already the newest version (1.2.54-1ubuntu1.1). libavcodec-dev is already the newest version (7:2.8.15-0ubuntu0.16.04.1). libavformat-dev is already the newest version (7:2.8.15-0ubuntu0.16.04.1). libswscale-dev is already the newest version (7:2.8.15-0ubuntu0.16.04.1). python3-pip is already the newest version (8.1.1-2ubuntu0.4). virtualenv is already the newest version (15.0.1+ds-3ubuntu1). The following packages were automatically installed and are no longer required: linux-headers-4.15.0-29 linux-headers-4.15.0-29-generic linux-image-4.15.0-29-generic linux-modules-4.15.0-29-generic linux-modules-extra-4.15.0-2…
has answer: http://stackoverflow.com/a/52069795
tagged with: python
has comment: http://stackoverflow.com/comment/91041516
tagged with: jupyter-notebook
tagged with: python-3.x
type: UnansweredQuestion

http://stackoverflow.com/comment/90881151
score: 0
type: Comment
has text: the output is: Insert the number you want to divide: 20 Traceback (most recent call last): File "C:/Users/agama/Desktop/programowanko/python/dobre.py", line 2, in <module> while(true): NameError: name 'true' is not defined
comment on: http://stackoverflow.com/a/51965394
type: AnswerComment

http://stackoverflow.com/a/52069763
has comment: http://stackoverflow.com/comment/91090214
has body: Your code has a few small issues, but it actually works, you just didn't test enough to find your actual problem. The issues: the True lines don't do anything, you don't need them for the while loop; the while will evaluate the True right after it and loop forever. you're mixing single and double quotes for your strings - that gets hard to read and confusing quickly, so you're better off using one style, preferably whatever PEP8 recommends. https://www.python.org/dev/peps/pep-0008/ The problem: your break works just fine; try running your script and entering 'quit' at the first prompt, it quits as expected. the reason it appears not to work is because you restart the entire game by calling the startgame function again after winning the game. This causes a new, nested call from within the game (think 'Inception') and when the game breaks, it ends up on the previous level. A solution would be to remove the call to startgame() and instead wrapping the whole thing in a second while, for example like this: import random def startgame(): b = 0 while b != 'quit': a = random.randint(1, 10) cont = 0 while True: b = input('Guess a number: ') if b == 'quit': break elif int(b) &gt; a: print('Too high!') cont += 1 elif int(b) &lt; a: print('Too low!') cont += 1 elif int(b) == a: print('You got it right!') print('You needed ', cont, 'guesses!') startgame()
type: Answer
has comment: http://stackoverflow.com/comment/91110107
upvote count: 2
answers question: http://stackoverflow.com/q/52069552
score: 2
has comment: http://stackoverflow.com/comment/91090120
has comment: http://stackoverflow.com/comment/92607413
downvote count: 0

http://stackoverflow.com/comment/90884294
comment on: http://stackoverflow.com/q/51966663
score: 0
type: QuestionComment
type: Comment
has text: I'm sorry but don't have any but in the link which i put above is proper equation and value of R array(TR). The T1 will have value around 20-40 expected x value under 700

http://stackoverflow.com/comment/90938276
comment on: http://stackoverflow.com/q/51992641
score: 0
type: Comment
type: QuestionComment
has text: @adrysdale Then your code is not a [MCVE]. Your production code is doing something different or is processing different data or both.

http://stackoverflow.com/comment/91169287
type: QuestionComment
comment on: http://stackoverflow.com/q/52104679
score: 1
has text: can you add the file `/app/wsgi.py` ?
type: Comment

http://stackoverflow.com/comment/91019188
comment on: http://stackoverflow.com/q/52034485
has text: If you're still running out of memory in the second case, the issue is likely somewhere else. Since you mention "pages", best is to try and process the data by page (or a limited set of pages) at a time.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52074716
tagged with: gnuplot
has comment: http://stackoverflow.com/comment/91121160
upvote count: 1
answer count: 1
tagged with: openfoam
has answer: http://stackoverflow.com/a/52151959
has comment: http://stackoverflow.com/comment/91123613
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91123869
has title: How to make a text-based interface (TUI/TLI) for monitoring OpenFOAM solver log file?
has comment: http://stackoverflow.com/comment/91123288
downvote count: 0
score: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/91124011
has comment: http://stackoverflow.com/comment/91122678
has comment: http://stackoverflow.com/comment/91123977
type: Question
has comment: http://stackoverflow.com/comment/91123415
tagged with: grep
tagged with: tui
has body: I'm running OpenFOAM simulations on a cluster and they take days to finish. I am looking for a way to monitor the process and get some meaningful insights. What I can do for the moment is to watch the tail of the log file using watch tail -n 15 log.log From here I have also found a nice GnuPlot-grep script: set logscale y set title "Residuals" set ylabel 'Residual' set xlabel 'Iteration' plot "&lt; cat log.log | grep 'Solving for Ux' | cut -d' ' -f9 | tr -d ','" title 'Ux' with lines,\ "&lt; cat log.log | grep 'Solving for Uy' | cut -d' ' -f9 | tr -d ','" title 'Uy' with lines,\ "&lt; cat log.log | grep 'Solving for Uz' | cut -d' ' -f9 | tr -d ','" title 'Uz' with lines,\ "&lt; cat log.log | grep 'Solving for omega' | cut -d' ' -f9 | tr -d ','" title 'omega' with lines,\ "&lt; cat log.log | grep 'Solving for k' | cut -d' ' -f9 | tr -d ','" title 'k' with lines,\ "&lt; cat log.log | grep 'Solving for p' | cut -d' ' -f9 | tr -d ','" title 'p' with lines,\ "&lt; cat log.log | grep 'Courant Number' | cut -d' ' -f9 | tr -d ','" title 'Courant Number mean' with lines,\ "&lt; cat log.log | grep 'Courant Number' | cut -d' ' -f6 | tr -d ','" title 'Courant Number max' with lines pause 1 reread which extract the information from the log.log file and if I add set term dumb somewhere on top it can plot in terminal. However, the plot is very crowded, it is ugly, it takes forever to show and it prints to the terminal sequentially, instead of updating the former one. Searching the internet I see there are some nice python libraries, such as npyscreen/picotui, ncurses/blessed, Asciimatics, Urwid, Prompt Toolkit ... for creating TUI/TLIs. I was wondering if you could help me know how I can create a text based interface to show basic information and a plot of selected values versus time. I want to have a couple of panels. One to select the variable I want to plot for example Courant Number mean and on the other panel have a plot of showing that variable versus step time. and other to…
tagged with: python

http://stackoverflow.com/q/52008696
has comment: http://stackoverflow.com/comment/90984003
score: 0
has comment: http://stackoverflow.com/comment/90968093
has title: Redirect http to https just on a specific port flask
type: UnansweredQuestion
tagged with: python
answer count: 0
has comment: http://stackoverflow.com/comment/90983713
tagged with: http
tagged with: https
type: Question
has comment: http://stackoverflow.com/comment/90983245
has body: I have a flask application which valids on https. I want to redirect every http request to https. I have this function: @app.before_request def before_request(): if request.url.startswith("http://"): url = request.url.replace('http://', 'https://' , 1) code = 301 return redirect(url, code= code) But it works just when i use port 5000 (Which is flask's default). Otherwise, I get a "connection was reset" error from my browser. Why is that? Thanks!
has comment: http://stackoverflow.com/comment/90968049
tagged with: flask

http://stackoverflow.com/comment/91031416
has text: are those exact lines you are trying to execute? because I tried to load the same content in `BeautifulSoup` and no such issue exist.
comment on: http://stackoverflow.com/q/52040260
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91135623
has text: You need to put `%matplotlib notebook` before importing `pyplot`
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52092842
score: 2

http://stackoverflow.com/q/52096050
has answer: http://stackoverflow.com/a/52096280
answer count: 2
has title: Seaborn Title Position
tagged with: location
has answer: http://stackoverflow.com/a/52096074
downvote count: 0
possible better answer: http://stackoverflow.com/a/52096280
favorite count: 0
has body: The position of my graph title is terrible on this jointplot. I've tried moving the loc = 'left, right, and center but it doesn't move from the position it's in. I've also tried something like ax.title.set_position([3, 15]) based on other suggestions from this site but that also doesn't move it at all. Any suggestions on controlling the location of the title? sns.jointplot(leagueWinners_season['Wins'], leagueWinners_season['Goals'], kind = 'reg', color = 'b') plt.title('Season Winners Goal and Win Regression', loc = 'right', fontsize = 16) plt.show()
accepted answer: http://stackoverflow.com/a/52096074
tagged with: seaborn
score: 6
tagged with: python
upvote count: 6
type: AnsweredQuestion
type: Question
tagged with: matplotlib
tagged with: title

http://stackoverflow.com/q/52054532
tagged with: numpy
tagged with: algorithm
has comment: http://stackoverflow.com/comment/91062241
has body: I need some tips or solutions on how to maintain a list of objects (dicts or custom Python types through Cython) limited to a max length, effectively. Basically doing this takes too much time: my_list = [a, b, c, d, ....] my_list = my_list[-50:] Is there any efficient way to make a list using Python, Cython (C/C++), Numpy that forgets the oldest item added to it above a threshold? For example beyond 50 items.
has comment: http://stackoverflow.com/comment/91059403
accepted answer: http://stackoverflow.com/a/52054613
has comment: http://stackoverflow.com/comment/91059655
type: AnsweredQuestion
favorite count: 0
tagged with: python-3.x
type: Question
upvote count: 1
tagged with: python
answer count: 1
has comment: http://stackoverflow.com/comment/91061953
has comment: http://stackoverflow.com/comment/91059320
has comment: http://stackoverflow.com/comment/91103163
has answer: http://stackoverflow.com/a/52054613
score: 0
tagged with: cython
has title: Python/Cython/Numpy efficiently maintaining a list with max length
downvote count: 1

http://stackoverflow.com/q/52061688
tagged with: python
has answer: http://stackoverflow.com/a/52061823
answer count: 4
type: AnsweredQuestion
tagged with: list
type: Question
has answer: http://stackoverflow.com/a/52061836
possible better answer: http://stackoverflow.com/a/52061823
has body: I have a list of unique file paths read from a csv file and I would like to filter this list via a number of ways. One of which is to exclude paths that contain specific words. I have created a list of words but I'm not sure how to use it to filter the paths. The below code doesn't work. with open("C:\MXD\dataSources.csv") as csvfile: pathList = csvfile.readlines() vendMastList = ["Vendor", "vendor", "master", "Master"] for pth in pathList: for vendMast in vendMastList: if vendMast not in pth: print pth
tagged with: python-2.7
score: 0
has answer: http://stackoverflow.com/a/52061825
has answer: http://stackoverflow.com/a/52063672
accepted answer: http://stackoverflow.com/a/52061825
has title: How to replace part of a string from a list of strings using Python 2.7

http://stackoverflow.com/a/52088046
type: Answer
answers question: http://stackoverflow.com/q/52088018
has body: Try this: funnel.legend(loc='lower right')
score: 0

http://stackoverflow.com/comment/91040627
has text: @Prune yes. Still the same problem...something to do with python 3.7?
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/52044423
type: Comment

http://stackoverflow.com/comment/90913466
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51981841
has text: i think i wasn't clear that `normalize` is a function, which means you have to write `df.x = np.where(df.normalized.values, df.x.values, df.x.apply(normalize))`... is that really faster?

http://stackoverflow.com/comment/91173324
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/52110144
has text: If you cant modify the original class, the easiest solution is to rewrite the function or fork the original project so you can modify the original class, other solutions will be realy advanced programming trick and im not sure this is a good practice it will make your code complicated and simpler is better than complicated
score: 0

http://stackoverflow.com/a/52009971
upvote count: 14
has body: What is overfitting Overfitting ( or underfitting) occurs when a model is too specific (or not specific enough) to the training data, and doesn't extrapolate well to the true domain. I'll just say overfitting from now on to save my poor typing fingers [*] I think the wikipedia image is good: Clearly, the green line, a decision boundary trying to separate the red class from the blue, is "overfit", because although it will do well on the training data, it lacks the "regularized" form we like to see when generalizing [**]. These CMU slides on overfitting/cross validation also make the problem clear: And here's some more intuition for good measure When does overfitting occur, generally? Overfitting is observed numerically when the testing error does not reflect the training error Obviously, the testing error will always (in expectation) be worse than the training error, but at a certain number of iterations, the loss in testing will start to increase, even as the loss in training continues to decline. How to tell when a model has overfit visually? Overfitting can be observed by plotting the decision boundary (as in the wikipedia image above) when dimensionality allows, or by looking at testing loss in addition to training loss during the fit procedure You don't give us enough points to make these graphs, but here's an example (from someone asking a similar question) showing what those loss graphs would look like: While loss curves are sometimes more pretty and logarthmic, note the trend here that training error is still decreasing but testing error is on the rise. That's a big red flag for overfitting. SO discusses loss curves here The slightly cleaner and more real-life example is from this CMU lecture on ovefitting ANN's: The top graph is overfitting, as before. The bottom graph is not. When does this occur? When a model has too many parameters, it is susceptible to overfitting (like a n-degree polynomial to n-1 points). Likewise, a model with not enough parameters ca…
has comment: http://stackoverflow.com/comment/90972061
score: 14
accepted answer of: http://stackoverflow.com/q/52009816
type: AcceptedAnswer
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/52009816

http://stackoverflow.com/a/52025543
score: 0
has body: $ awk ' BEGIN { FS=OFS=", " } $1 ~ / / { last = rest = $1 sub(/ .*/,"",last) sub(/[^ ]+ /,"",rest) $1 = rest " " last } { print } ' file Name, Address1, Address2 Joe M Smith, 123 Apple Rd, Paris TX Keith Randall Adams, 543 1st Street, Salinas CA Tiffany Price, 11232 32nd Street, New York NY Karen E F Walker, 98 West Ave, Denver CO
type: Answer
answers question: http://stackoverflow.com/q/52022692

http://stackoverflow.com/comment/90980446
type: Comment
has text: Hi thanks however i tried the code it prints out all the stopwords however it also prints the new list with stopwords still inside?
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52015032

http://stackoverflow.com/q/52111532
upvote count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/91176209
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/52111585
accepted answer: http://stackoverflow.com/a/52111585
possible better answer: http://stackoverflow.com/a/52111845
has answer: http://stackoverflow.com/a/52112862
tagged with: python
has comment: http://stackoverflow.com/comment/91174163
answer count: 4
type: AnsweredQuestion
tagged with: list
has answer: http://stackoverflow.com/a/52111615
score: 1
has title: python list - only keep only-positive or only-negative values
type: Question
has body: In Python, I have a list with thousands of numbers (negative and positive). What I want, is to eliminate the numbers which occur in the list both positive and negative. So I want only to keep the numbers which occur in the list either only positive or only negative. Example: list = (1, 2, 3, -1, -2, -5, 6, 7, -6) should result in (3, -5, 7). Thanks !
has answer: http://stackoverflow.com/a/52111845

http://stackoverflow.com/a/52056926
score: 0
answers question: http://stackoverflow.com/q/52056462
type: Answer
has body: as mentioned in the comments: you could try to use the re module. here i try to match your search_term only if it is surrounded by characters that are not in [a-zA-Z0-9_] (not sure if that suits your intentions best...): import re def concordance(strg, search_term, width=5): ret = [] # \W Matches any character which is not a word character. # ~ anything that is not [a-zA-Z0-9_] rgx = re.compile('\W{}\W'.format(search_term)) match_end = 0 while True: match = rgx.search(strg, match_end) if match is None: break ret.append(strg[match.start()+1-width:match.end()-1+width]) match_end = match.end() return ret print(concordance(strg, 'and')) # ['beef and beef', 'beef and beef', 'tion and\ncond', 'coat and the ']

http://stackoverflow.com/a/52092446
has comment: http://stackoverflow.com/comment/91134974
upvote count: 1
type: Answer
has body: I do not quite understand what you mean by "without having to declare the layer again". The method tf.nn.conv2d computes a 2-D convolution. That's how to calculate a convolution with TensorFlow. Now, you earlier evaluated the convolution on TrainingDataExample and stored it in ConvExample. By generating a new set of weights, NewWeightExample and assigning it to override the variable WeightExample, it does not automatically change the value of the convolution earlier calculated in ConvExample. Hence, you will have to recompute the convolution again, using the new set of weights. You can do this by simply re-running: ConvExample = tf.nn.conv2d(TrainingDataExample, WeightExample, strides=[1, 1, 1, 1], padding="VALID", name="Conv") To get the following result: &lt;tf.Tensor: id=36, shape=(8, 5, 4, 4), dtype=float32, numpy= array([[[[3., 3., 3., 3.], [3., 3., 3., 3.], [3., 3., 3., 3.], [3., 3., 3., 3.]], ...
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/52091047
has comment: http://stackoverflow.com/comment/91136081
has comment: http://stackoverflow.com/comment/91300685

http://stackoverflow.com/a/51979079
has comment: http://stackoverflow.com/comment/90908346
has comment: http://stackoverflow.com/comment/90908528
type: Answer
upvote count: 1
has comment: http://stackoverflow.com/comment/90912531
score: 1
downvote count: 0
has body: If you don't provide the legend entries within the legend() function, it should be placed after the label-entries in the plot commands. Otherwise legend cannot know what to list. If you want to have a legend within each subplot, you should call axs[i][j].legend() within a loop (or call axs[0][0].legend(), axs[0][1].legend(), ... manually for each subplot of course). The point is: fig.legend() is a legend on figure level, i.e. one legend for all subplots together. This should be called once outside of the loop.
answers question: http://stackoverflow.com/q/51978578
has comment: http://stackoverflow.com/comment/90908518
has comment: http://stackoverflow.com/comment/90908429
has comment: http://stackoverflow.com/comment/90908730

http://stackoverflow.com/a/63586110
type: Answer
score: 2
upvote count: 2
downvote count: 0
answers question: http://stackoverflow.com/q/52068066
has body: I know it's a different client but for anyone still having issues this took me some time to figure out: This client required the initial request params also be included. Here's the code: import boto3 lex_client = boto3.client("lex-models") response = lex_client.get_slot_types( nameContains='search_string', maxResults=50 ) slot_types = response['slotTypes'] while 'nextToken' in response.keys(): response = lex_client.get_slot_types(nameContains='search_string', maxResults=50, nextToken=response['nextToken']) slot_types.extend(response['slotTypes']) print('here are the slot types', slot_types)

http://stackoverflow.com/q/52072438
has title: Is there any way to insert some python statement when using python redis transaction?
score: 2
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/51060226
type: Question
has body: Redis is very easy to use in python. However, now I have a problem in using Redis transaction. First, I have to get a key in Redis, next I have to check whether the value bound to this key is legal. I hope those operations to be atomic. Here is my code. pipe = redis_conn.pipeline() pipe.multi() var = pipe.get('key_want_to_be_read') if is_legal(val): do_something else: do_another_thing pipe.execute() However, when I run these code, python name var is not bound to a value stored in redis, but a Pipeline&lt;ConnectionPool&lt;Connection&lt;host=localhost,port=6379,db=0&gt;&gt;&gt;, So. Is there any way to get a key and bound it to a python name in redis transaction?
downvote count: 0
has answer: http://stackoverflow.com/a/52075745
has comment: http://stackoverflow.com/comment/91096577
answer count: 1
favorite count: 0
tagged with: redis
upvote count: 2
accepted answer: http://stackoverflow.com/a/52075745
tagged with: python

http://stackoverflow.com/q/51976669
answer count: 2
accepted answer: http://stackoverflow.com/a/73092346
tagged with: pymysql
downvote count: 0
possible better answer: http://stackoverflow.com/a/55514423
favorite count: 0
tagged with: sql
has body: i am using pymysql to interact with an sql db, here is the code: query = "SELECT * FROM my_table" c = db.cursor(pymysql.cursors.DictCursor) c.execute(query) c.fetchall() now i am doing this for a database of 3000 enteries which isn't alot, i plan to use this on a database with 15 million enteries and i want to take the data out in a loop as batches of 5000 enteries i wonder if i need to do this using LIMIT and OFFSET in my query, or can i just do it using a method in the pymysql module... Thank You
has answer: http://stackoverflow.com/a/73092346
upvote count: 3
linked to: http://stackoverflow.com/q/32625593
has answer: http://stackoverflow.com/a/55514423
tagged with: python
type: AnsweredQuestion
score: 3
has title: pymysql retrievingdata in batches
tagged with: mysql
type: Question
has comment: http://stackoverflow.com/comment/90903572

http://stackoverflow.com/comment/90933564
type: Comment
score: 1
comment on: http://stackoverflow.com/q/51989564
has text: I have no idea, but maybe because someone has undone his/her vote.
type: QuestionComment

http://stackoverflow.com/comment/90979479
comment on: http://stackoverflow.com/q/52009449
score: 0
type: Comment
type: QuestionComment
has text: It may or may not be applicable to your probelm, but maybe `pexpect` would be useful for you?

http://stackoverflow.com/comment/91067107
comment on: http://stackoverflow.com/a/52051912
score: 0
type: AnswerComment
has text: there was a syntax error in `for` loop indentation. i fixed it and now it will works fine.
type: Comment

http://stackoverflow.com/q/52059197
type: Question
duplicate of: http://stackoverflow.com/q/847179
tagged with: centos6
upvote count: 1
tagged with: drmaa
downvote count: 0
tagged with: glibc
has body: I am trying to run drmaa (a python module that controls jobs in SGE) under a CentOS 6.x. According to the drmaa-python (https://github.com/pygridtools/drmaa-python) one of the requirement is libdrmaa.so, which I acquired from gridengine-libdrmaa-dev package. I stored a copy of libdrmaa.so under mydir/lib/. I also put the DRMAA_LIBRARY_PATH environmental variable in .bashrc: DRMAA_LIBRARY_PATH=mydir/lib/libdrmaa.so And the error message showed when I ran main.py: Traceback (most recent call last): File "mydir/main.py", line 3, in &lt;module&gt; from . import tools ImportError: cannot import name 'tools' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "mydir/main.py", line 5, in &lt;module&gt; import tools File "mydir/tools.py", line 20, in &lt;module&gt; import drmaa File "mydir/anaconda3/lib/python3.6/site-packages/drmaa/\__init\__.py", line 63, in &lt;module&gt; from .session import JobInfo, JobTemplate, Session File "mydir/anaconda3/lib/python3.6/site-packages/drmaa/session.py", line 39, in &lt;module&gt; from drmaa.helpers import (adapt_rusage, Attribute, attribute_names_iterator, File "mydir/anaconda3/lib/python3.6/site-packages/drmaa/helpers.py", line 36, in &lt;module&gt; from drmaa.wrappers import (drmaa_attr_names_t, drmaa_attr_values_t, File "mydir/anaconda3/lib/python3.6/site- packages/drmaa/wrappers.py", line 56, in &lt;module&gt; _lib = CDLL(libpath, mode=RTLD_GLOBAL) File "mydir/anaconda3/lib/python3.6/ctypes/__init__.py", line 348, in __init__ self._handle = _dlopen(self._name, mode) OSError: /lib64/libc.so.6: version 'GLIBC_2.14' not found (required by mydir/lib/libdrmaa.so) I suspected that the libdrmaa.so is using the default libc.so.6 with GLIBC lower than 2.14. Let's assume that I do not have sudo privilege and no superuser could upgrade the glibc for me. I installed glibc-2.19 under my home directory and ran main.py again. The error message remained the same. After some research, I now c…
favorite count: 0
linked to: http://stackoverflow.com/q/847179
tagged with: linux
tagged with: python
has comment: http://stackoverflow.com/comment/91159488
answer count: 0
type: UnansweredQuestion
score: 1
has title: How to get libdrmaa.so to use locally installed GLIBC?
has comment: http://stackoverflow.com/comment/91090240

http://stackoverflow.com/q/52101845
has comment: http://stackoverflow.com/comment/91154717
has comment: http://stackoverflow.com/comment/91154767
has comment: http://stackoverflow.com/comment/91154664
has comment: http://stackoverflow.com/comment/91154689
has comment: http://stackoverflow.com/comment/91154773
has answer: http://stackoverflow.com/a/52102087
has comment: http://stackoverflow.com/comment/91154678
type: Question
answer count: 1
has title: Subprocess Popen to run python command
score: 0
has body: I need to run a python command inside a Popen. The problem is that the command NEEDS to run in python3 and I need it to be portable, which means that I can't really use the python3 alias for every situation... I have computers where python is already the correct version, and others where the correct one is python3. I tried to insert #!/usr/bin python3 in the beginning of the file and then run as python but it didn't work. I can't modify environment vars to change python3 to python. I would like to know if there is a way to check which one I need to use or a way to change the python3 to python ONLY inside the Popen command... The Popen command I am trying to run is very simple and no I can't just import the file and use as a class... it needs to be ran through Popen. Also, virtualenv or similars are not an option. subprocess.Popen(['python', 'main.py'], shell=True, universal_newlines=True)
accepted answer: http://stackoverflow.com/a/52102087
has comment: http://stackoverflow.com/comment/91154518
has comment: http://stackoverflow.com/comment/91154780
tagged with: python-3.x
tagged with: subprocess
has comment: http://stackoverflow.com/comment/91154574
has comment: http://stackoverflow.com/comment/91154595
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91154641
tagged with: popen

http://stackoverflow.com/comment/91089030
score: 1
type: AnswerComment
type: Comment
has text: You need to open the zipfilename, not zipf. Once more, you are working with a ZipFile object rather than a filename. Thus, My first answer was correct.
comment on: http://stackoverflow.com/a/52069538

http://stackoverflow.com/comment/91096429
type: QuestionComment
has text: You generally should avoid testing things provided by framework, or third parties generally speaking, so testing if urls are registered correctly is pointless. What you should test is behavior that you implement.
score: 0
comment on: http://stackoverflow.com/q/52073187
type: Comment

http://stackoverflow.com/comment/90945481
type: Comment
type: QuestionComment
has text: My scoring looks like this: `scoring = {'rec': 'recall', 'acc': 'accuracy', 'prec': 'precision', 'rocauc': 'roc_auc'}`. I updated my initial post of how my approach looks like without RFE - but still with a lot of error messages.
comment on: http://stackoverflow.com/q/51986706
score: 0

http://stackoverflow.com/q/52046690
tagged with: python
has comment: http://stackoverflow.com/comment/91044461
type: AnsweredQuestion
downvote count: 0
has title: Pandas Drop Duplicates Series Hashing Error
has answer: http://stackoverflow.com/a/52046754
has body: I have created a pandas dataframe but when dropping duplicate rows I am given the error: TypeError: 'Series' objects are mutable, thus they cannot be hashed This happens when I run: print(type(data)) # &lt;class 'pandas.core.frame.DataFrame'&gt; check that it's not a series data.drop_duplicates(subset=['statement'], inplace=True) print(data.info()) Info returns this: &gt; class 'pandas.core.frame.DataFrame' &gt; Int64Index: 39671 entries, 0 to 39670 &gt; Data columns (total 4 columns): &gt; statement 39671 non-null object &gt; topic_direction 39671 non-null object &gt; topic 39671 non-null object &gt; direction 39671 non-null object &gt; dtypes: object(4) &gt; memory usage: 1.5+ MB &gt; None
type: Question
accepted answer: http://stackoverflow.com/a/52046754
has comment: http://stackoverflow.com/comment/91044407
score: 5
has comment: http://stackoverflow.com/comment/91044468
has comment: http://stackoverflow.com/comment/91044347
tagged with: pandas
answer count: 1
favorite count: 0
upvote count: 5
has comment: http://stackoverflow.com/comment/91044482
has comment: http://stackoverflow.com/comment/91044530

http://stackoverflow.com/comment/90997484
type: Comment
comment on: http://stackoverflow.com/a/52020860
has text: Most of the projects use implicit wait so this method doesn't fit well, that's what I said you can't check the status of the element properly in selenium.
type: AnswerComment
score: 0

http://stackoverflow.com/comment/91084299
has text: Yes, sir! Got it. :)
type: AnswerComment
type: Comment
score: 0
comment on: http://stackoverflow.com/a/52066850

http://stackoverflow.com/comment/90868351
has text: No they are not always increasing, they typically only change by 1 or 2 values, but they decrease and increase. They also never change consistently, so a constant step size would alter the data.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51958885
score: 0

http://stackoverflow.com/comment/90964820
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52007283
has text: Re-read the example you're trying to copy: you're missing the second argument. `sum((a, b), [])` works just fine.
score: 1

http://stackoverflow.com/a/52096819
type: Answer
has comment: http://stackoverflow.com/comment/91144222
has body: You can use re.sub to replace one or more new-lines (\n) with a singular space. Then strip the result (of any trailing and leading spaces) and concatenate that onto a '#': import re '#' + re.sub('\n+',' ',s).strip() #'#Created on Mar 11, 2017 @author: XXZ This file is to demonstrate the word frequency counter. This is a very important practical'
has comment: http://stackoverflow.com/comment/91144366
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/91145056
has comment: http://stackoverflow.com/comment/91144196
answers question: http://stackoverflow.com/q/52096773
downvote count: 0
has comment: http://stackoverflow.com/comment/91143792

pyo
tag name: pyo
tags question: http://stackoverflow.com/q/51958667
type: Tag

http://stackoverflow.com/q/52042370
tagged with: for-loop
has body: This is super bad and messy, I am new to this, please help me. Basically, I was trying to find two numbers from a list that add up to a target number. I have set up an example with lst = [2, 4, 6, 10] and a target value of target = 8. The answer in this example would be (2, 6) and (6, 2). Below is my code but it is long and ugly and I am sure there is a better way of doing it. Can you please see how I can improve from my code below? from itertools import product, permutations numbers = [2, 4, 6, 10] target_number = 8 two_nums = (list(permutations(numbers, 2))) print(two_nums) result1 = (two_nums[0][0] + two_nums[0][1]) result2 = (two_nums[1][0] + two_nums[1][1]) result3 = (two_nums[2][0] + two_nums[2][1]) result4 = (two_nums[3][0] + two_nums[3][1]) result5 = (two_nums[4][0] + two_nums[4][1]) result6 = (two_nums[5][0] + two_nums[5][1]) result7 = (two_nums[6][0] + two_nums[6][1]) result8 = (two_nums[7][0] + two_nums[7][1]) result9 = (two_nums[8][0] + two_nums[8][1]) result10 = (two_nums[9][0] + two_nums[9][1]) my_list = (result1, result2, result3, result4, result5, result6, result7, result8, result9, result10) print (my_list) for i in my_list: if i == 8: print ("Here it is:" + str(i))
downvote count: 0
tagged with: permutation
favorite count: 0
has comment: http://stackoverflow.com/comment/91036710
has answer: http://stackoverflow.com/a/52042453
has answer: http://stackoverflow.com/a/58793547
answer count: 10
tagged with: python
has title: Find two numbers from a list that add up to a specific number
score: 2
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52042572
upvote count: 2
has answer: http://stackoverflow.com/a/77024457
has comment: http://stackoverflow.com/comment/91035720
has comment: http://stackoverflow.com/comment/91035639
has answer: http://stackoverflow.com/a/58663517
has comment: http://stackoverflow.com/comment/91036084
accepted answer: http://stackoverflow.com/a/52042453
has comment: http://stackoverflow.com/comment/91035836
type: Question
has answer: http://stackoverflow.com/a/53367963
has comment: http://stackoverflow.com/comment/91036575
possible better answer: http://stackoverflow.com/a/52042630
has answer: http://stackoverflow.com/a/68617765
has answer: http://stackoverflow.com/a/52042454
has answer: http://stackoverflow.com/a/59317814
has comment: http://stackoverflow.com/comment/91035862
has answer: http://stackoverflow.com/a/52042630

http://stackoverflow.com/comment/90996287
has text: Just saw your edit, and it doesn't seem to be that fishy, or is it? Your outuput Instances have different number of `AmiLaunchIndex` have different values but that shouldn't bother you as you can easily iterate through them without having to know the number of instances. Just follow the instructions in the answers and use `for loop` to open and iterate through any list that is being returned
comment on: http://stackoverflow.com/a/52018673
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/90985852
has text: yes it have: https://github.com/django/django/blob/83b04d4f88dd65ae630a45385de34e275899dc41/django/db/models/fields/related_descriptors.py#L702 And the base Manage class doesn't have `set2` and I can define it, that doesn't matter. I just want to define some methods but looks like some of them have a constraint that unable me to override them.
score: 0
comment on: http://stackoverflow.com/q/52012401
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/90965207
comment on: http://stackoverflow.com/q/52007401
has text: See this lovely [debug](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/) blog for help. If you insert a few tracing `print` commands to follow the values you're generating, you'll see the sequence of problems in this logic.
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/90938291
has text: @DYZ: If that is the case, I would have to write C++ code to do it. The huge bummer is that there is no C++ analogue of pandas, and so I would have to figure out a way to convert a pandas DataFrame into a list of C++ arrays and then convert them back into a pandas DataFrame.
comment on: http://stackoverflow.com/q/51994045
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52008692
has title: Should we use tuple or list for index_together
type: AnsweredQuestion
score: 1
has answer: http://stackoverflow.com/a/52008933
tagged with: django
upvote count: 1
type: Question
has body: For index_together, I was wondering, should I use tuple or list, as both seems workable. tuple class ApiMonthlyUsage(models.Model): month = models.IntegerField(blank=False, null=False) count = models.IntegerField() user = models.ForeignKey(User, on_delete=models.CASCADE) class Meta: index_together = ( ('month', 'user'), ) list class ApiMonthlyUsage(models.Model): month = models.IntegerField(blank=False, null=False) count = models.IntegerField() user = models.ForeignKey(User, on_delete=models.CASCADE) class Meta: index_together = [ ['month', 'user'], ]
accepted answer: http://stackoverflow.com/a/52008933
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/90967923
favorite count: 0
tagged with: python
has comment: http://stackoverflow.com/comment/90967964

http://stackoverflow.com/q/52059849
has comment: http://stackoverflow.com/comment/91070225
has body: On https://en.wikipedia.org/wiki/Quadratic_equation there is a graph shown... It shows the quadratic y = ax2 + bx + c, varying each coefficient separately while the other coefficients are fixed (at values a = 1, b = 0, c = 0) As a learning experience I decided to replicate these plots in Matplotlib as follows: import numpy as np import matplotlib.pyplot as plt import math #Plot the quadratic function y = ax2 + bx + c #Varying each coefficient [a, b, c] separately while the other coefficients are fixed (at values a = 1, b = 0, c = 0) #Iterate these 5 coeficients and plot each line coefs = [-2, -1, 0, 1, 2] #set up the plot and 3 subplots (to show the effect of varying each coefficient) f, (ax1, ax2, ax3) = plt.subplots(1, 3, sharey=True, figsize=(18, 6)) #some x values to plot x = np.linspace(-2, 2, 30) for idx, val in enumerate([ax1, ax2, ax3]): for i, v in enumerate(coefs): a, b, c = 1, 0, 0 if idx == 0: a = v elif idx == 1: b = v else: c = v y = a * (x**2) + (b * x) + c val.plot(x, y, label="Coeficient is " + str(coefs[i])) val.axhline(y=0, color='k') val.axvline(x=0, color='k') val.grid() val.legend(loc='lower center') plt.show() It works fine... but I am new to programming and I have an uneasy feeling that using if statements isn't optimal. It feels like I should be iterating over something rather than using ifs. What other ways could I iterate over the coefficients a, b &amp; c to produce the 3 different subplots?
tagged with: iteration
has title: Matplotlib iterate plots without if statements - Python3
has comment: http://stackoverflow.com/comment/91070234
tagged with: python
has comment: http://stackoverflow.com/comment/91070192
has comment: http://stackoverflow.com/comment/91070095
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91072392
has comment: http://stackoverflow.com/comment/91070351
has comment: http://stackoverflow.com/comment/91070443
has comment: http://stackoverflow.com/comment/91070418
tagged with: matplotlib
type: Question
score: 0
has comment: http://stackoverflow.com/comment/91070278

network-programming
tags question: http://stackoverflow.com/q/51958326
type: Tag
tag name: network-programming
tags question: http://stackoverflow.com/q/52077150
tags question: http://stackoverflow.com/q/52064721
tags question: http://stackoverflow.com/q/52059220

http://stackoverflow.com/comment/90887859
score: 0
has text: @Ahmed Yes. Will do that in a while.
type: QuestionComment
comment on: http://stackoverflow.com/q/51962506
type: Comment

http://stackoverflow.com/comment/90926015
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51987962
has text: @asdfasdfasdf can you open this link ? https://pypi.org/simple/ or blocked?
score: 0

http://stackoverflow.com/a/52035114
answers question: http://stackoverflow.com/q/52033958
downvote count: 0
upvote count: 2
has body: from datetime import datetime t = datetime.strptime('Mon Aug 27 04:47:45 +0000 2008', '%a %b %d %H:%M:%S % z %Y') t.strftime('%Y-%m-%d %H:%M:%S') Refer section 8.1.8 here
type: Answer
score: 2

http://stackoverflow.com/comment/91018476
has text: I think there is another cause that makes form disappear. I will check it again.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52031838

http://stackoverflow.com/q/52110753
tagged with: python
accepted answer: http://stackoverflow.com/a/52110814
upvote count: 3
answer count: 1
has title: Pool.apply_async function in Python prints number in order
has answer: http://stackoverflow.com/a/52110814
type: AnsweredQuestion
score: 3
downvote count: 0
has body: This question is about Pool apply_async function. Shouldn't this function call other function asynchronously? Code: import multiprocessing as mp def foo_pool(x): return x result_list = [] def log_result(result): result_list.append(result) def apply_async_with_callback(): pool = mp.Pool() for i in range(10): pool.apply_async(foo_pool, args = (i, ), callback = log_result) pool.close() pool.join() print(result_list) if __name__ == '__main__': apply_async_with_callback() After running this code for a while I keep getting this print: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] Why is it in order? Shouldn't the output sometimes be out of order?
favorite count: 0
type: Question

http://stackoverflow.com/q/52012173
has title: Drop NaN values by group
has answer: http://stackoverflow.com/a/52012357
answer count: 2
tagged with: pandas
downvote count: 0
favorite count: 0
has body: I have a dataframe with the 'Materiais' column that indicates the code of the product, the 'Values' Column, that corresponds to the product values, and 'Month' columns that corresponds to it months. Year Month Materiais Values 0 2018 M1 52745 NaN 1 2018 M2 52745 NaN 2 2018 M3 52745 NaN 3 2018 M4 52745 NaN 4 2018 M5 52745 NaN 5 2018 M6 52745 NaN 6 2018 M7 52745 NaN 7 2018 M1 58859 NaN 8 2018 M2 58859 NaN 9 2018 M3 58859 NaN 10 2018 M4 58859 NaN 11 2018 M5 58859 300 12 2018 M6 58859 NaN 13 2018 M7 58859 NaN 14 2018 M1 57673 NaN 15 2018 M2 57673 100 16 2018 M3 57673 NaN 17 2018 M4 57673 150 1-) I would like to have in this dataframe, only products that had at least a value in one month. So my idea is to group all the similar products codes and check if there is at least one value != NaN. In order to group, I am using this function: df = df_demand.groupby(['Materiais'], sort=False, as_index=False) I would like to know, how to create a condition to apply dropna(), only for products that has NaN values in all months ? 2-) Filter the months that there is at least one value != NaN', using a similar approach: df = df_demanda.groupby(['Month'], sort=False, as_index=False)
tagged with: python
possible better answer: http://stackoverflow.com/a/52012268
accepted answer: http://stackoverflow.com/a/52012357
has answer: http://stackoverflow.com/a/52012268
type: AnsweredQuestion
score: 1
upvote count: 1
type: Question

http://stackoverflow.com/q/51988768
tagged with: scikit-learn
has comment: http://stackoverflow.com/comment/90927954
score: 0
has comment: http://stackoverflow.com/comment/90928128
has comment: http://stackoverflow.com/comment/90928289
favorite count: 0
answer count: 0
type: UnansweredQuestion
upvote count: 1
tagged with: python
tagged with: multilabel-classification
downvote count: 1
has comment: http://stackoverflow.com/comment/90927681
type: Question
has comment: http://stackoverflow.com/comment/90927932
has body: I would like to do K-fold cross-validation. the code before K-fold cross validation is like this: and it working perfectly df = pd.read_csv('finalupdatedothers-multilabel.csv') X= df'sentences' dfy = df'ADR','WD','EF','INF','SSI','DI','others' df1 = dfy.stack().reset_index() df1.columns = ['a','b','c'] y_train_text = df1.groupby('a')['b'].apply(list) lb = preprocessing.MultiLabelBinarizer() # Run classifier stop_words = stopwords.words('english') classifier=make_pipeline(CountVectorizer(), TfidfTransformer(), #SelectKBest(chi2, k=4), OneVsRestClassifier(SGDClassifier())) #combined_features = FeatureUnion([("pca", pca), ("univ_select", selection)]) random_state = np.random.RandomState(0) # Split into training and test X_train, X_test, y_train, y_test = train_test_split(X_train, y_train_text, test_size=.2, random_state=random_state) print y_train # # Binarize the output classes Y = lb.fit_transform(y_train) Y_test=lb.transform(y_test) classifier.fit(X_train, Y) y_score = classifier.fit(X_train, Y).decision_function(X_test) print ("y_score"+str(y_score)) predicted = classifier.predict(X_test) all_labels = lb.inverse_transform(predicted) #print accuracy_score print ("accuracy : "+str(accuracy_score(Y_test, predicted))) print ("micro f-measure "+str(f1_score(Y_test, predicted, average='weighted'))) print("precision"+str(precision_score(Y_test,predicted,average='weighted'))) print("recall"+str(recall_score(Y_test,predicted,average='weighted'))) for item, labels in zip(X_test, all_labels): print ('%s =&gt; %s' % (item, ', '.join(labels))) when I change the code to use k fold cross-validation instead of train_tes_split. I got this error: ValueError: Found input variables with inconsistent numbers of samples: [1, 6008] Updated with iloc my code to use k-fold cross validation looks like this: kf = KFold(n_splits=10) kf.get_n_splits(X) KFold(n_splits=2, random_state=None, shuffle=False) for train_index, test_index in kf.split(X): X_train, X_test = X.iloc[train_index], …
has comment: http://stackoverflow.com/comment/90928011
tagged with: cross-validation
has title: got error while using k fold split in multilabel in sklearn

http://stackoverflow.com/comment/90964361
type: AnswerComment
type: Comment
has text: Thanks, though I get another error when trying that: `OpenSSL.SSL.Error: [('SSL routines', 'SSL_CTX_set_cipher_list', 'no cipher match')]` as if there was no such cipher in OpenSSL 1.0.2p. And yet it appears when I list them via `/usr/local/opt/openssl/bin/openssl ciphers` Was your environment otherwise the same as mine?
comment on: http://stackoverflow.com/a/51993543
score: 0

pygame
tags question: http://stackoverflow.com/q/51957162
tags question: http://stackoverflow.com/q/52035565
tags question: http://stackoverflow.com/q/52015473
tags question: http://stackoverflow.com/q/52032825
tags question: http://stackoverflow.com/q/52083847
tags question: http://stackoverflow.com/q/51977051
tags question: http://stackoverflow.com/q/52104513
tags question: http://stackoverflow.com/q/52105116
tags question: http://stackoverflow.com/q/51959467
tags question: http://stackoverflow.com/q/51962516
tags question: http://stackoverflow.com/q/52084840
tags question: http://stackoverflow.com/q/52048419
tags question: http://stackoverflow.com/q/52070631
tags question: http://stackoverflow.com/q/51971213
tags question: http://stackoverflow.com/q/52006196
tags question: http://stackoverflow.com/q/52064358
tags question: http://stackoverflow.com/q/52022554
tags question: http://stackoverflow.com/q/52066346
tags question: http://stackoverflow.com/q/51967307
tag name: pygame
tags question: http://stackoverflow.com/q/52017596
tags question: http://stackoverflow.com/q/52036123
tags question: http://stackoverflow.com/q/52026315
tags question: http://stackoverflow.com/q/52059053
tags question: http://stackoverflow.com/q/52016098
tags question: http://stackoverflow.com/q/51965617
tags question: http://stackoverflow.com/q/52045413
tags question: http://stackoverflow.com/q/51973441
tags question: http://stackoverflow.com/q/52090460
tags question: http://stackoverflow.com/q/52044109
tags question: http://stackoverflow.com/q/52040002
tags question: http://stackoverflow.com/q/52066935
tags question: http://stackoverflow.com/q/52056472
tags question: http://stackoverflow.com/q/52105750
tags question: http://stackoverflow.com/q/52015758
tags question: http://stackoverflow.com/q/52010337
type: Tag

http://stackoverflow.com/q/52038539
has answer: http://stackoverflow.com/a/65702971
upvote count: 2
answer count: 2
has answer: http://stackoverflow.com/a/52039126
tagged with: diacritics
favorite count: 0
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/19591458
tagged with: python
tagged with: utf-8
score: 2
downvote count: 0
has title: UT8 issue - Is there a way to convert strange looking characters Ã¤ to its proper German character ä in Python?
type: Question
has body: I have a .txt file, which should contain German Umlauts like ä,ö,ß,ü. But, these characters don't apear as such, instead what appears is Ã¤ instead of ä, Ã instead of Ü and so on. It happens because the .txt file is stored in ANSI encoding. Now, when I import this file, with respective columns as Strings, in either SAS (DataStep) or Python (with .read_csv), then these strange characters appear in the .sas7bat and the Python DataFrame as such, instead of proper characters like ä,ö,ü,ß. One work around to solve this issue is - Open the file in standard Notepad. Press 'Save As' and then a window appears. Then in the drop down, change encoding to UTF-8. Now, when you import the files, in SAS or Python, then everything is imported correctly. But, sometimes the .txt files that I have are very big (in GBs), so I cannot open them and do this hack to solve this issue. I could use .replace() function, to replace these strange characters with the real ones, but there could be some combinations of strange characters that I am not aware of, that's why I wish to avoid that. Is there any Python library which can automatically translate these strange characters into their proper characters - like Ã¤ gets translated to ä and so on?

http://stackoverflow.com/q/51992766
score: 2
tagged with: django-celery
has body: So basically, I want to manage the workers based on the queue size/time of the day for one particular queue. I want to run less number of workers for a queue in peak hours and increase them when the load comes down.
type: Question
answer count: 1
downvote count: 0
has title: How to add/remove workers programatically in celery?
tagged with: python
favorite count: 0
upvote count: 2
type: UnansweredQuestion
tagged with: django
has answer: http://stackoverflow.com/a/51994235
tagged with: celery

http://stackoverflow.com/comment/91017851
has text: @bigbounty I waited for 4 hours just for reading 120 pins.. and Pinterest is responding fast.. also not blocked because using selenium.
comment on: http://stackoverflow.com/q/52033607
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91110329
type: Comment
has text: I tried `class Address(object)`: without `from builtins import object` and the test passes. But since `newstyle` is in the list of checks in the CI CD, it needs `from builtins import object` else there is difference in futurize error.
type: AnswerComment
comment on: http://stackoverflow.com/a/52079498
score: 0

http://stackoverflow.com/q/51982017
downvote count: 4
has answer: http://stackoverflow.com/a/51982268
upvote count: 0
answer count: 1
favorite count: 0
tagged with: python-3.x
linked to: http://stackoverflow.com/q/36982858
has body: So to start off I'm converting pyggel to python 3 all the converted files run in IDLE no issues but when I run the game included in python 3 I hit this error GameObject.__init__(self, game, obj=pyggel.mesh.OBJ("data/gun.obj", colorize=[0.2, 0.2, 0.2, 1]), File "/home/pi/Downloads/PYGGEL-V0.08-alpha4c/pyggel/mesh.py", line 58, in OBJ cur_mtl.set_color(map(float, values[1:])) File "/home/pi/Downloads/PYGGEL-V0.08-alpha4c/pyggel/data.py", line 355, in set_color if len(color) == 3: TypeError: object of type 'map' has no len() here is the part of the code the error comes from: class Material(object): """A simple class to store a color and texture for an object.""" def __init__(self, name): """Create the material name is the name of the material""" self.name = name self.color = (1,1,1,1) self.texture = BlankTexture() def set_color(self, color): """Set color of material.""" if len(color) == 3: color += (1,) self.color = color def copy(self): """Copy material.""" a = Material(self.name) a.color = self.color a.texture = self.texture return a update my question isn't a duplicate I'm not trying to find out the lengh of a list the "if len()" statement is suppost to set a color (also this module is still working in python 2.5)
tagged with: python
duplicate of: http://stackoverflow.com/q/36982858
has comment: http://stackoverflow.com/comment/90914518
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51982268
has title: Converting a python 2 module to python3 Error: object of type 'map' has no len()
type: Question
has comment: http://stackoverflow.com/comment/90914248
has comment: http://stackoverflow.com/comment/90915823
score: -4
tagged with: python-2.7

http://stackoverflow.com/q/51975737
type: UnansweredQuestion
type: Question
has comment: http://stackoverflow.com/comment/90902008
tagged with: matplotlib
has body: When I run this little program ( a little experiment to see a linear transformation of a chosen vector), the python launcher icon on my mac starts to activate itself by bouncing on the dock but then nothing is displayed. What is the problem? import matplotlib.pyplot as plt def linear_transformation(up_sx,up_dx,down_sx,down_dx): x_vect_val=(input('what is the X value of the vector?')) y_vect_val=(input('what is the Y value of the vector?')) x_vect_transfval=str((int(x_vect_val)*str(up_sx))+(int(y_vect_val)*str(up_dx))) y_vect_transfval=str((int(x_vect_val)*str(down_sx))+(int(y_vect_val)*str(down_dx))) xvals=[x_vect_val,x_vect_transfval] yvals=[y_vect_val,y_vect_transfval] plt.plot(xvals,yvals) plt.show It might be some stupid reason that I don't know, I am a beginner linear_transformation(1,2,0,1) the icon activating
score: 0
has comment: http://stackoverflow.com/comment/90901922
has title: matplotlib not showing result
tagged with: python
answer count: 0

http://stackoverflow.com/comment/91027582
score: 0
type: AnswerComment
has text: by the way , implementing it the way it works now makes it more easier to be controlled with other languages such as python for example as you can integrate it within your program code and use any where along when you type the commands
comment on: http://stackoverflow.com/a/52035175
type: Comment

http://stackoverflow.com/comment/90904843
comment on: http://stackoverflow.com/q/51976479
has text: @Ykh I just edited this thread and added error message! Now I found out that the save method in Work model causes this error. But I don't know how to fix it...
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91015262
type: Comment
comment on: http://stackoverflow.com/a/52032467
has text: not sure I follow. `keyword` is the actual name of the key in that particular dictionary. It cannot be changed
score: 0
type: AnswerComment

http://stackoverflow.com/a/52045901
score: 0
answers question: http://stackoverflow.com/q/52045899
type: Answer
has body: The problem in your 1st example isn't that the regexp is matching too many spaces; it's matching too many letters before a space. So don't put your "non-greedy" ? modifier after spaces, put it after the .* because that's what is currently matching too much. py3.7 &gt;&gt;&gt; re.findall('http.*? ', s) ['https://.com/abcabcabc '] On the other hand, [^ \n] is not a modifier of any sort – it's a full match expression on its own. So putting it after an existing expression won't make it match less; you now have two match expressions which together match more. You have to use it in place of the expression which matches too much, namely instead of the .: py3.7 &gt;&gt;&gt; re.findall('http[^ \n]*', s) ['https://.com/abcabcabc', 'https://.com/abcabcabc', 'https://.com/djflkajdsfl']

http://stackoverflow.com/comment/91139806
type: Comment
comment on: http://stackoverflow.com/a/52093408
score: 0
type: AnswerComment
has text: I can not do that as the dates would change every day, so I would need to set the Column names every day.

http://stackoverflow.com/comment/90985839
type: Comment
comment on: http://stackoverflow.com/q/52017849
has text: What is the index? `Time`?
score: 0
type: QuestionComment

http://stackoverflow.com/comment/90960609
type: Comment
comment on: http://stackoverflow.com/q/52005295
type: QuestionComment
score: 0
has text: Thomas Why am I getting the error "TypeError: list indices must be integers or slices, not str"?

http://stackoverflow.com/q/52003530
favorite count: 0
tagged with: python-3.x
tagged with: python
tagged with: regex
downvote count: 6
type: AnsweredQuestion
score: -5
has answer: http://stackoverflow.com/a/52005035
has title: Extract text with conditions in Python
upvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/90958045
has comment: http://stackoverflow.com/comment/90956361
has comment: http://stackoverflow.com/comment/90957304
has comment: http://stackoverflow.com/comment/90956512
accepted answer: http://stackoverflow.com/a/52005035
answer count: 1
has body: I have researched lot and couldn't find a regex where I can achieve the desired text with below conditions. I have a huge paragraph of text, I want to extract text with certain conditions: The extracted text should start with list of words. eg: Apple, Banana, Orange, Pineapple. It should end with when any of the other 3 words is encountered and there is a preceding number. The extraction should start only when there is a preceding number to it. Sample text: I have 2 apples in my bag and apples are great food toeat. you shud eat apples daily. it is very good for health. 3 bananas are also good. it reduces fat. Below is the excepted output apples in my bag and apples are great......good for health. bananas are also good. it reduces fat So, if there are 2 keywords present, I want 2 files to be created and so on. Update of what I tried: The regex which I tried is: (?=(\d+)(\s?)apple)(.*)(?=\d+\s?banana:?s) Regex I tried I have 2 problems here: In the extracted text I don't want the 1st number How to make it dynamic as in if I have 4 words, I don't have to write that many combinations and if we are searching for apple the extracted text for that is saved in that variable Python version: 3.5 Can you please help me with a regex for this.
has comment: http://stackoverflow.com/comment/90958215

http://stackoverflow.com/q/52059254
accepted answer: http://stackoverflow.com/a/52077294
type: AnsweredQuestion
has title: Odoo 10: How do I disable Click on Base Tree View
type: Question
score: 0
tagged with: odoo-10
answer count: 1
tagged with: python
tagged with: http://stackoverflow.com/tag/xml
tagged with: formview
has answer: http://stackoverflow.com/a/52077294
has body: I'm attempting to disable the click to form view on a base level tree view (not from an x2many field) Is there a way to do this? here is my tree view code. attendance.tree.read_only hr.attendance 17 Is there a way to do this? if not is there a way to point this specific tree view to another specific form view? The reason we need this is so that anyone who doesn't have manager permissions can only see their attendances.
tagged with: treeview

http://stackoverflow.com/comment/91070225
has text: But for working code I think you should post on [code review](https://codereview.stackexchange.com/)
score: 1
comment on: http://stackoverflow.com/q/52059849
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52087404
tagged with: python
has body: I am using ExponentialSmoothing from statsmodels to run Holt-Winters method on time series. I get forecasted values but can not extract calculated values and compare them with observed values. from pandas import Series from scipy import stats import statsmodels.api as sm from statsmodels.tsa.api import ExponentialSmoothing modelHW = ExponentialSmoothing(np.asarray(passtrain_df['n_passengers']), seasonal_periods=12, trend='add', seasonal='mul',).fit() y_hat_avg['Holt_Winter'] = modelHW.forecast(prediction_size) So here, prediction_size = number of forecasted datapoints (4 in my case) passtrain_df is a dataframe with observations (140 datapoints) based on which Holt_Winter model is built (regression). I can easily display 4 forecasted values. How do I extract 140 calculated values? Tried to use: print(ExponentialSmoothing.predict(np.asarray(passtrain_df), start=0, end=139)) But I probably have a syntax error somewhere Thank you!
has comment: http://stackoverflow.com/comment/91691323
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91705573
has title: Interpolation using ExponentialSmoothing from stats models
upvote count: 1
has comment: http://stackoverflow.com/comment/91705056
accepted answer: http://stackoverflow.com/a/52095244
type: Question
tagged with: statsmodels
tagged with: time-series
has comment: http://stackoverflow.com/comment/91698046
tagged with: holtwinters
answer count: 1
downvote count: 0
score: 1
favorite count: 0
has answer: http://stackoverflow.com/a/52095244

http://stackoverflow.com/q/52031721
downvote count: 4
has title: I intend to write a quiz program that adds up points when the answer is correct and deducts point when a wrong answer is given in python
has comment: http://stackoverflow.com/comment/91014046
has body: This is what i came up with, and i cant understand why what is going on, as my expectation is to have point increment for every correct answer and point deduction for any wrong answer. name = str(input("What is your name?: ")) score = 0 answer1 = str(input("(1) What is the name of the first president of Nigeria? \n(a) Amadu Bello \n(b) Shehu Shagari \n(c) Olusegun Obasanjo \n(d) Nnamdi Azikwe\n:Your answer: ")) if answer1 == "d" or "D" or "Nnamdi" or "Nnamdi Azikwe" and "Azikwe": score = score+5 print ( "Weldone", name, "you've scored", score, "points") else: score = score - 5 print( "ouch!!!", name, "you missed that, you've scored, ", score, "points") answer2 = str(input("(2) What is the name of the capital of Lagos state? \n(a) Ikorodu\n(b) Ikeja\n(c) Surulere\n(d) Victoria Island\nYour answer: ")) if answer2 == "a" or "A" or "Ikeja": score = score+5 print ( "Weldone", name, "you've scored", score, "points") else: score = score - 5 print( "ouch!!!", name, "you missed that, you've scored, ", score, "points") answer3 = str(input("(3) What is the name of the first capital of Nigeria?\n(a) Kano \n(b) Abuja\n(c) Lagos\n(d) Calabar\nYour Answer: ")) if answer3 == "c" or "C" or "lagos" and "Lagos": score = score+5 print ( "Weldone", name, "you've scored", score, "points") else: score = score - 5 print( "ouch!!!", name, "you missed that, you've scored, ", score, "points") answer4 = str(input("(4) What is the name of the governor of Lagos when Code-Lagos was first implemented? \n(a)Raji Fashola\n(b)Akinwunmi Ambode\n(c) Ahmed Tinubu\n (d) Lateef Jakande\nYour answer: ")) if answer4 == "b" or "B" or "Ambode" or "Akinwunmi Ambode" or "akinwunmi ambode": score = score+5 print ( "Weldone", name, "you've scored", score, "points") else: score = score - 5 print( "ouch!!!", name, "you missed that, you've scored, ", score, "points") answer5 = str(input("(5) Which of the following is indigenous Nigerian content? \n(a) Etisalat\n(b) Airtel\n(c) MTN\n(d) Globacoms\n Your Answer: ")) i…
linked to: http://stackoverflow.com/q/15851146
duplicate of: http://stackoverflow.com/q/20002503
answer count: 1
accepted answer: http://stackoverflow.com/a/52031747
favorite count: 0
has comment: http://stackoverflow.com/comment/91013985
score: -3
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/52031747
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91013870
type: Question

http://stackoverflow.com/a/52006938
has body: My approach involves running through pairs of consecutive numbers and examine the gaps between them, just like everybody else's. The difference here is in the use of iter() to create two iterables from one list. # Given: l = [26.051, 26.084, 26.117, 26.15, 26.183, 31.146, 31.183, 34.477, 34.51, 34.543] gap = 0.033 # Make two iterables (think: virtual lists) from one list previous_sequence, current_sequence = iter(l), iter(l) # Initialize the groups while advancing current_sequence by 1 # element at the same time groups = next(current_sequence) # Iterate through pairs of numbers for previous, current in zip(previous_sequence, current_sequence): if abs(previous - current) &gt; gap: # Large gap, we create a new empty sublist groups.append([]) # Keep appending to the last sublist groups[-1].append(current) print(groups) A few notes My solution looks long, but if you subtract all the comments, blank likes, and the last print statement, it is only 6 lines It is efficient because I did not actually duplicate the list An empty list (empty l) will generate a StopIteration exception, so please ensure the list is not empty
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/52005258
type: Answer
downvote count: 0

http://stackoverflow.com/q/52038190
has comment: http://stackoverflow.com/comment/91026975
tagged with: pip
has body: Creating a virtualenv with site packages: $ virtualenv env New python executable in env/bin/python Installing setuptools, pip...done. Activating it ... $ source env/bin/activate (env)/home/pkara/Workspace Checking number or packages: $ pip freeze | wc -l 0 deactivating / removing previous virtualenv (env)/home/pkara/Workspace $ deactivate /home/pkara/Workspace $ rm -rf env/ Now creating a virtualenv without site packages: $ virtualenv env --no-site-packages New python executable in env/bin/python Installing setuptools, pip...done. Activating and counting: $ source env/bin/activate (env)/home/pkara/Workspace $ pip freeze | wc -l 0 (env)/home/pkara/Workspace Why in both cases the number of packets is zero? The number of packages in my system (outside any virtualenv whatsoever): $ pip freeze | wc -l 106
type: AnsweredQuestion
has title: pip freeze in virtualenv created with and without site packages
type: Question
answer count: 1
tagged with: virtualenv
score: 0
has comment: http://stackoverflow.com/comment/91026938
has answer: http://stackoverflow.com/a/52038598
tagged with: python
accepted answer: http://stackoverflow.com/a/52038598

http://stackoverflow.com/comment/90911077
type: Comment
comment on: http://stackoverflow.com/a/51980684
type: AnswerComment
has text: I am actually looking to edit the 'id' in _data and not to add a new column.
score: 0

http://stackoverflow.com/a/54396801
score: 7
has comment: http://stackoverflow.com/comment/114740613
has body: Some points to clarify first: Pandas doesn't have anything to do with the styling, and the styling happens to all HTML tables, not only dataframes. That is easily checked by displaying an HTML table in Jupyter (example code at the end of the answer). It seems that your Jupyter or one of your installed extensions is doing "extra" styling, the default style doesn't include column sorting or column highlighting. There is only odd/even rows coloring and row highlighting (checked on Jupyter source code and my local Jupyter installation). This means that my answer may not include all the styling you want. The Answer Is the dataframe rendering code used by jupyter available as a standalone module that can be used in any web app? Not exactly a standalone module, but all the tables formatting and styling seem to be attached to the rendered_html class. Double-checked that by inspecting the notebook HTML in Firefox. You can use the .less file linked above directly or copy the required styles to your HTML. Also, are the assets such as js/css files decoupled from jupyter so that they can be easily reused? Like any well-designed web project (and actually any software project), the packages and modules are well separated. This means that you can re-use a lot of the code in your project with minimal effort. You can find most of the .less styling files in Jupyter source code here. An example to check if the styling happens to all HTML tables: from IPython.display import HTML HTML(''' a b 0 1 3 1 2 4 ''')
upvote count: 7
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/52104682
type: Answer
accepted answer of: http://stackoverflow.com/q/52104682
has comment: http://stackoverflow.com/comment/95648855
downvote count: 0

http://stackoverflow.com/comment/91022838
has text: I have edited in the stats function. Sorry for the inconvenience.
score: 0
comment on: http://stackoverflow.com/q/52036195
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91017001
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52032757
has text: Edited.Thank you!
score: 0

http://stackoverflow.com/q/52086283
has comment: http://stackoverflow.com/comment/91123441
score: 0
tagged with: concatenation
answer count: 1
has answer: http://stackoverflow.com/a/52086655
has comment: http://stackoverflow.com/comment/91123172
type: UnansweredQuestion
tagged with: python
has body: I've recently received a .csv data frame from a database that was supposed to return 4 columns but actually returned 8. When I checked, I found that some columns have been added because it seems like the string that belonged in the fourth column had a newline in it. In other words, I'm seeing something like this: index A B C D (extra) (extra) (extra) (extra) 0 1 2 'abc\' 'def\' 'ghi\' 'jkl\' 'xyz' some_date 1 1 2 'abc' some_date 2 1 2 'abc\' 'def' some_date As opposed to this: index A B C D 0 1 2 'abcdefghijklxyz' some_date 1 1 2 'abc' some_date 2 1 2 'abcdef' some_date Is there an efficient way to combine columns that end in a newline with the column to the right?
has title: Python: Concatenate columns based on "\"
type: Question
tagged with: newline
tagged with: string-concatenation

http://stackoverflow.com/comment/90945706
type: Comment
has text: Inside `isin` the series has `p` value twice. If the data is huge my opinion is to take unique of the series. Since, `isin` iterates over given values.
score: 2
comment on: http://stackoverflow.com/a/51998197
type: AnswerComment

http://stackoverflow.com/q/52059053
upvote count: 1
tagged with: python
type: AnsweredQuestion
score: 1
type: Question
has answer: http://stackoverflow.com/a/52059386
downvote count: 0
answer count: 1
tagged with: virtualenv
accepted answer: http://stackoverflow.com/a/52059386
has body: I am creating a virtual environment testenv to run some python project. This is my environment.yml file: name: testenv channels: - !!python/unicode 'defaults' dependencies: - python=3.5 - pip==9.0.1 - numpy==1.12.0 - jupyter==1.0 - matplotlib==2.0.0 - scikit-learn==0.18.1 - scipy==0.19.0 - pandas==0.19.2 - pip: - tensorflow==1.1.0 - keras==2.0.4 - plotly==2.7.0 I want to add pygame to this environenment. However, if I add pygame==1.9.4 to dependencies or pip, then the creation of a virtual environment fails: conda env create Therefore I should source activate testenv and then install pygame manually, but it's not very convenient. brew install sdl sdl_image sdl_mixer sdl_ttf portmidi pip install pygame Has anybody tried installing pygame in the automated way in the virtual environment?
tagged with: pygame
favorite count: 0
has title: How to install pygame automatically when virtual environment is created?

http://stackoverflow.com/a/52093266
type: AcceptedAnswer
downvote count: 0
score: 1
has body: Simply install openpyxl to your own computer by opening Command Prompt or Terminal, and typing: pip install openpyxl # For Python 2 pip3 install openpyxl # For Python 3
type: Answer
accepted answer of: http://stackoverflow.com/q/52093212
answers question: http://stackoverflow.com/q/52093212
upvote count: 1
has comment: http://stackoverflow.com/comment/91137018
has comment: http://stackoverflow.com/comment/91136516

http://stackoverflow.com/q/51980469
has answer: http://stackoverflow.com/a/51980488
tagged with: dataframe
upvote count: 2
answer count: 2
tagged with: pandas
has answer: http://stackoverflow.com/a/51980512
tagged with: nan
favorite count: 0
tagged with: python
score: 2
type: AnsweredQuestion
downvote count: 0
accepted answer: http://stackoverflow.com/a/51980488
possible better answer: http://stackoverflow.com/a/51980512
has title: Retrieve indices of rows that contain NaN values
type: Question
has body: I try to retrieve for each row containing NaN values all the corresponding indices. A B C D 0 11.4 1.3 2.0 NaN 1 11.4 1.3 NaN NaN 2 11.4 1.3 2.8 0.7 3 NaN NaN 2.8 0.7 The desired result : [0,1,3] I'm looking for a pandas way to be able to deal with my huge dataset. thanks in advance

http://stackoverflow.com/comment/91139513
comment on: http://stackoverflow.com/q/52094675
type: Comment
type: QuestionComment
has text: Your screenshot does not contain the complete error. The traceback is cut off. Please copy and paste the complete traceback into your question and put it in code formatting by pasting, then highlighting the whole traceback and then clicking the `{}` button
score: 1

http://stackoverflow.com/comment/91002858
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/52026352
has text: I don't see you update `label1` anywhere...?
score: 0

http://stackoverflow.com/a/51956791
has comment: http://stackoverflow.com/comment/90890207
has comment: http://stackoverflow.com/comment/90890886
has comment: http://stackoverflow.com/comment/90867860
has comment: http://stackoverflow.com/comment/90890858
upvote count: 4
type: AcceptedAnswer
score: 4
answers question: http://stackoverflow.com/q/51956676
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51956676
has comment: http://stackoverflow.com/comment/90890583
has comment: http://stackoverflow.com/comment/90890623
has comment: http://stackoverflow.com/comment/90890057
has body: Using IntervalIndex matchdf=pd.DataFrame.from_dict(h,'index').reset_index() matchdf.index=pd.IntervalIndex.from_arrays(left=matchdf[0],right=matchdf[1],closed= 'both') df['New']=matchdf.loc[df.file_id]['index'].values df Out[128]: file_id filename New 0 30140 WS52RN-300-7750460312963... 28 1 30730 DMX5N4H-336-7G5082A_15089528977... 29 2 31215 114-403CBC_1508935183409.mp4 30 3 32000 VQCYSR-300-84L7F5D9_1508937725363... 31 4 32648 69HM-336-6262906_48508952353171.mp4 32
type: Answer

http://stackoverflow.com/a/52039792
has comment: http://stackoverflow.com/comment/91031331
type: AcceptedAnswer
upvote count: 1
has body: There must be a better way, but this one works: df = pd.DataFrame({'team': [' a', ' a', ' a', ' a', 'b', 'b', 'c'], 'IndexMatch': [1, 2, 3, 4, 5, 6, 7], 'isVictoryTeam': [1, 0, 1, 1, 0, 1, 1]}) df['winrate'] = df.groupby('team')['isVictoryTeam'].expanding().mean().reset_index().groupby('team')['isVictoryTeam'].shift().reset_index(drop=True) df # IndexMatch isVictoryTeam team winrate #0 1 1 a NaN #1 2 0 a 1.000000 #2 3 1 a 0.500000 #3 4 1 a 0.666667 #4 5 0 b NaN #5 6 1 b 0.000000 #6 7 1 c NaN
type: Answer
accepted answer of: http://stackoverflow.com/q/52037095
downvote count: 0
answers question: http://stackoverflow.com/q/52037095
score: 1

http://stackoverflow.com/comment/91111051
type: Comment
has text: I want to use + or %s for this
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52079141

http://stackoverflow.com/q/51959369
accepted answer: http://stackoverflow.com/a/51959389
has body: I have to following forms.py and models.py: # models class BHA_Component(models.Model): item_description = models.CharField(max_length=111) num_of_jts = models.CharField(max_length=111) length = models.CharField(max_length=111) cum_length = models.CharField(max_length=111) outer_d = models.CharField(max_length=111) # forms class BHA_Component_Form(forms.ModelForm): class Meta(): model = BHA_Component fields = '__all__' So far, I've been printing the field names on the screen using html like this: {% for field in bha_form %} {{ field.name }} {% endfor %} I passed in the form, bha_form as a context variable in views.py. If I use this set of code, it this on a screen: item_description, num_of_jts, length, cum_length, outer_d But I want to print this on a screen: Item Description, # of jts, Lenth, Cum. Len., OD As you can see, I can't get this output by simply using some s.upper() method, or regex method, because there no certain string transformation relationship between the original field names and the output I want. I want to manually decide what field names will be printed on a screen for each field. But I don't want to do this by hard coding html elements like this: Item Description # of jts Length I want to do this on the backend using Django. How should I go about this?
type: AnsweredQuestion
upvote count: 3
tagged with: django
type: Question
score: 3
tagged with: django-forms
has answer: http://stackoverflow.com/a/51959389
has title: Django - Forms - change field names on template
answer count: 1
downvote count: 0
favorite count: 0
tagged with: python

http://stackoverflow.com/q/52070462
answer count: 5
has answer: http://stackoverflow.com/a/60030705
tagged with: django
tagged with: python
has answer: http://stackoverflow.com/a/52070665
type: AnsweredQuestion
has title: Django generate custom ID
score: 7
has answer: http://stackoverflow.com/a/52070551
has comment: http://stackoverflow.com/comment/91090715
linked to: http://stackoverflow.com/q/38698729
upvote count: 7
has comment: http://stackoverflow.com/comment/91090782
type: Question
has body: I saw this answer but there is no specific answer yet. I want to create custom id that starts with letter. When a new record comes into database I want to change the id to A00001, .... A00002, .... A00010, ...A10000 etc. The id will be always in range 99999- 00001 so how can I do that? my model is simple: class Custom(models.Model): id = models.AutoField(primary_key=True, editable=False)
possible better answer: http://stackoverflow.com/a/52070551
has comment: http://stackoverflow.com/comment/91090849
accepted answer: http://stackoverflow.com/a/52070665
downvote count: 0
tagged with: django-models
linked to: http://stackoverflow.com/q/517579
favorite count: 0
has answer: http://stackoverflow.com/a/53278044
has answer: http://stackoverflow.com/a/67720882

http://stackoverflow.com/a/51989379
has comment: http://stackoverflow.com/comment/90953594
has comment: http://stackoverflow.com/comment/91023341
upvote count: 1
has comment: http://stackoverflow.com/comment/91066486
downvote count: 0
has comment: http://stackoverflow.com/comment/90948096
has comment: http://stackoverflow.com/comment/90948726
has comment: http://stackoverflow.com/comment/91023908
has body: Slightly slow solution (repeating the same actions) Edit - fit BinatyEncoder before create generators Drop NA first and work with clean data further to avoid reassignments of data frame. data = pd.read_msgpack('datum.msg') data.dropna(subset=['s_address','d_address']).to_msgpack('datum_clean.msg') In this solution data_generator can process same data multiple times. If it's not critical, you can use this solution. Define function which reads the data snd splits index to train and test. It won't consume a lot of memory. import pandas as pd from category_encoders import BinaryEncoder as be from sklearn.preprocessing import StandardScaler from sklearn.model_selection import train_test_split import numpy as np def model(): #some code defining the model def train_test_index_split(): # if there's enough memory to add one more column data = pd.read_msgpack('datum_cleaned.msg') train_idx, test_idx = train_test_split(data.index) return data, train_idx, test_idx data, train_idx, test_idx = train_test_index_split() Define and initialize data generator, both for train and validation def data_generator(data, encX, encY, bathc_size, n_steps, index): # EDIT: As the data was cleaned, you don't need dropna # data = data.dropna(subset=['s_address','d_address']) for i in range(n_steps): batch_idx = np.random.choice(index, batch_size) sample = data.loc[batch_idx] y = sample's_address', 'd_address' x = sample.drop(['s_address', 'd_address'], 1) numeric_X = encX.transform(x) numeric_Y = encY.transform(y) scaler = StandardScaler() X_all = scaler.fit_transform(numeric_X) yield X_all, numeric_Y Edited part now train binary encoders. You should sub-sample your data to create representative training set for encoders. I guess error with the shape of the data was caused by incorrecly trained BinaryEncoder (Error when checking input: expected dense_9_input to have shape (233,) but got array with shape (234,)): def get_minimal_unique_frame(df): return (pd.Series([df[column].unique() for colum…
type: Answer
has comment: http://stackoverflow.com/comment/91057621
answers question: http://stackoverflow.com/q/51983391
score: 1
has comment: http://stackoverflow.com/comment/91054224
has comment: http://stackoverflow.com/comment/91073984

http://stackoverflow.com/q/52031044
has body: One part of a program I am writing requires me to list the files and folders within a Google Drive folder. I am currently using the following code: page_token = None while True: response = service.files().list(pageSize=1000,q="'folder_id' in parents",fields="nextPageToken, files(id, name)").execute() for file in response.get('files', []): print('Found file: %s (%s)' % (file.get('name'), file.get('id'))) page_token = response.get('nextPageToken', None) if page_token is None: break For some reason, one folder that I am testing returns only one file, even if I add additional files/folders, and every other parent folder_id I try results in no files being returned. I even tried deleting the one file that is being returned, and it still gets returned when I call the function again.
type: UnansweredQuestion
tagged with: google-api-python-client
tagged with: python
tagged with: google-drive-api
has answer: http://stackoverflow.com/a/75944312
has comment: http://stackoverflow.com/comment/91047094
score: 1
upvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/91012752
answer count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/91012750
has title: Python Google Drive API not listing all files in folder
favorite count: 0
has answer: http://stackoverflow.com/a/60739303

http://stackoverflow.com/q/52054196
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/64790902
tagged with: python
tagged with: imaplib
score: 7
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/52066820
favorite count: 0
tagged with: python-2.7
has body: I'm trying to read all emails from a particular date and time. mail = imaplib.IMAP4_SSL(self.url, self.port) mail.login(user, password) mail.select(self.folder) since = datetime.strftime(since, '%d-%b-%Y %H:%M:%S') result, data = mail.uid('search', '(SINCE &quot;'+since+'&quot;)', 'UNSEEN') It is working fine without time. Is it possible to search with time also?
upvote count: 7
has title: Python imaplib search email with date and time
tagged with: python-3.x
downvote count: 0

http://stackoverflow.com/a/51967308
accepted answer of: http://stackoverflow.com/q/51966456
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/51966456
type: Answer
score: 0
has body: When you create the 'class chatServer(threading.Thread):' you said to Python that the class chatServer will inherit the methods of threading.Thread, that is, all methods in threading.Thread will be "copied" for chatServer. If you want, you can check the methods contained in a class by typing dir(class). dir(threading.Thread) ['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_bootstrap', '_bootstrap_inner', '_delete', '_exc_info', '_initialized', '_reset_internal_locks', '_set_ident', '_set_tstate_lock', '_stop', '_wait_for_tstate_lock', 'daemon', 'getName', 'ident', 'isAlive', 'isDaemon', 'is_alive', 'join', 'name', 'run', 'setDaemon', 'setName', 'start'] As you can see, the threading.Thread has two peculiar methods: run and start. In your case, the run method inherted was overwrited by you when you create the def run()... However, the method start still remain in the class chatServer, check it by typing dir(chatServer) in your console. That method start has a callable __call__ that call, doh', the method run(self) in their class. So, that is why it is running.

http://stackoverflow.com/a/75816102
has body: The pull request #1327 (https://github.com/facebookresearch/fastText/pull/1327) Allows for: test after each epoch checkpointing training on large data which does not fit into memory (largest I tested was 1.6TB) finetuning already trained models The trained model is indistinguishable from a model that was created by an original tool and can be used for inference by the old code.
downvote count: 0
answers question: http://stackoverflow.com/q/52080365
type: Answer
upvote count: 1
score: 1

http://stackoverflow.com/comment/91041433
type: QuestionComment
has text: Map is tons faster than replace.
comment on: http://stackoverflow.com/q/52043153
score: 0
type: Comment

http://stackoverflow.com/comment/90879667
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51964400
has text: Where is your `except` block? Which line leading to exception?

http://stackoverflow.com/comment/91137640
has text: Of course, sometimes it's necessary to downgrade when future versions are not stable or bugs are found causing the latest versions not to behave correctly. Also you'll find that some libraries do not support certain versions of other libraries, or even Python, and you will have to downgrade. I put it as a comment because as you say this isn't really the 'answer', but more of a workaround.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52092999

http://stackoverflow.com/a/51989082
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51976401
has comment: http://stackoverflow.com/comment/90932312
score: 2
answers question: http://stackoverflow.com/q/51976401
has body: Hope this will work for x in pyre_game.each(): print( x.key(), x.val() )
upvote count: 2
type: Answer
has comment: http://stackoverflow.com/comment/90933332

http://stackoverflow.com/comment/91112960
type: AnswerComment
comment on: http://stackoverflow.com/a/52081009
score: 0
type: Comment
has text: I actually think the most efficient test would be `len(set(s)) == len(s)`

http://stackoverflow.com/comment/90991764
type: Comment
comment on: http://stackoverflow.com/a/52020409
type: AnswerComment
has text: ive deleted everything with googlesearch in its name except for under Anaconda3 on my hard drive and now I am "ModuleNotFoundError: No module named 'googlesearch'
score: 0

http://stackoverflow.com/comment/91017373
type: Comment
type: QuestionComment
has text: Lambda is used for anonymous functions. Ur requirement can be done using numpy arrays and numpy arrays are fast. Or just without mapping with list you can multiply them
comment on: http://stackoverflow.com/q/52033518
score: 0

http://stackoverflow.com/comment/90903154
has text: Have you tried prepending your string with an `r`? As in, instead of `'%WINDIR%\\system32\\netsh.exe'`, using `r'%WINDIR%\\system32\\netsh.exe'`?
comment on: http://stackoverflow.com/q/51976453
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/91171713
comment on: http://stackoverflow.com/q/52091758
has text: I was checking the package folder, and it turns out that there is multiple numpy and pandas versions in the same folder. Do you think that could be linked? @Lomtrur
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/a/52008270
type: Answer
accepted answer of: http://stackoverflow.com/q/52008200
upvote count: 2
score: 2
answers question: http://stackoverflow.com/q/52008200
has body: You can use map for rules In [1066]: df['time_2'] = df.time / df.category.map({'T': 24, 'L': 3.5}).fillna(1) In [1067]: df Out[1067]: id category time time_2 0 43 S 8 8.000000 1 22 I 10 10.000000 2 15 T 350 14.583333 3 18 L 46 13.142857
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/90927381
comment on: http://stackoverflow.com/q/51986354
has text: Checkout this discussion https://stackoverflow.com/questions/51555208/how-to-handle-browser-notification-popup-which-is-without-any-elements
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/51974546
type: Question
has answer: http://stackoverflow.com/a/51974652
has title: Python: How to recall position after break from iteration over start, stop, step loop
has answer: http://stackoverflow.com/a/51974628
answer count: 2
tagged with: iterator
has comment: http://stackoverflow.com/comment/90899670
downvote count: 0
tagged with: listiterator
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/90899714
tagged with: python
accepted answer: http://stackoverflow.com/a/51974652
possible better answer: http://stackoverflow.com/a/51974628
type: AnsweredQuestion
score: 1
has body: I am learning about iterators and how to use them and in the process have come up with a question. Is it possible to recall where a loop left off during iteration (if the loop were to have a break condition that was met) and then to pick up from the recalled spot? An example of what I am saying is, I have this code: print("Range() Test") for i in range(10, 100, 10): if i == 60: print('Break Point') break print(i) for i in range(10, 100, 10): print(i) Which should run and give you something like this: Range() Test 10 20 30 40 50 Break Point 10 20 30 40 50 60 70 80 90 My first question is: 1) Is there a way to recall the position where the break took place and begin from there as opposed to my bumbling start-over? I have seen instanced where the iteration was over a list of items, but have not been able to find an example/work out a functioning example of using iter() on the start/stop/step notation. 2) In doing research (I am learning Python and doing a lot of self-teaching) I have seen the range() function describer both as an iterator and NOT as an iterator so, if anyone has more definitive information on this, as opposed to tearing me a new one for using it in my example, that would be much appreciated. Thanks!
upvote count: 1

http://stackoverflow.com/comment/90917107
type: Comment
has text: who said it should be numpy array?
comment on: http://stackoverflow.com/a/51983618
type: AnswerComment
score: 0

http://stackoverflow.com/q/52097767
has title: Find the start of the index of a phrase in a list
type: Question
score: -2
has comment: http://stackoverflow.com/comment/91145823
has answer: http://stackoverflow.com/a/52097878
downvote count: 2
answer count: 3
has comment: http://stackoverflow.com/comment/91145807
favorite count: 0
has answer: http://stackoverflow.com/a/52097872
type: UnansweredQuestion
tagged with: python
upvote count: 0
tagged with: list
has answer: http://stackoverflow.com/a/52097934
has body: Assuming I have this list: text = ['Malte', 'ex', 'precio', 'empcionis', 'bovum', 'septem', 'laborancium', 'et', 'unius', 'thaurj', 'et', 'unius', 'vacce', 'cum', 'vitulo', 'sequenti', 'et', 'pecudum', 'fetancium', 'sexdecim', 'et', 'duarum', 'caprarum', 'cum', 'duobus', 'et', 'cum', 'vitulo'] And I want to find every index of the beginning of 'cum vitulo' ie: 13 and 26. At the moment I am getting the start of 'cum' but sometimes this is followed by another word ex: 'duobus' in this case

http://stackoverflow.com/comment/90961505
comment on: http://stackoverflow.com/q/52005741
has text: Both, I would like to store in database without dashes, and use it without dashes.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/90983848
score: 0
type: Comment
has text: The exception is logged not by aiohtp itself but by asyncio. Nothing to do on aiohttp side.
type: QuestionComment
comment on: http://stackoverflow.com/q/52012488

http://stackoverflow.com/comment/91063447
type: QuestionComment
score: 0
has text: uhhh maybe have you tried resizing the image equal to the resolution of your screen?
comment on: http://stackoverflow.com/q/52056470
type: Comment

http://stackoverflow.com/comment/91054661
has text: Youa re correct, you have overwritten your `PATH` variable. You probably forgot to add `:${PATH}` at the end of your `export` command.
type: QuestionComment
type: Comment
score: 3
comment on: http://stackoverflow.com/q/52051760

http://stackoverflow.com/q/51957162
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/90936627
has comment: http://stackoverflow.com/comment/90864994
has comment: http://stackoverflow.com/comment/90865054
has comment: http://stackoverflow.com/comment/90865987
tagged with: pygame
has comment: http://stackoverflow.com/comment/90917179
accepted answer: http://stackoverflow.com/a/51994091
has body: I have made a pygame game where 2 cars race around a football pitch and try to score a goal. I have added a boost function where a countdown timer starts as long as the up button is being pressed and is stopped when the key is no longer being pressed. When the timer = 0,the boosting feature stops. This works 70-80% of the time, but with strange glitches. (Glitch 1)Sometimes, even after the up arrow has been let go, the boosted speed stays the same, and the timer does not turn on. (Glitch 2)Another strange glitch is when the boosttimer has gone to 0, and the user hold down both up and a sideways arrow, then let go of the sidewards arrow(left or right), the boosted speed still says. I've got my code for the boost below, hope someone can help. import pygame from pygame.math import Vector2 import time pygame.font.init() pygame.init() WIDTH = 1150 HEIGHT = 800 screen = pygame.display.set_mode((WIDTH, HEIGHT)) pygame.display.set_caption("Rocket League") clock = pygame.time.Clock() start_ticks = pygame.time.get_ticks() REDGOAL = pygame.Surface((50, 150), pygame.SRCALPHA) REDGOAL.fill((255, 0, 0)) redgoal_rect = REDGOAL.get_rect(topleft=(0, 340)) redgoal_mask = pygame.mask.from_surface(REDGOAL) REDCAR_ORIGINAL = pygame.Surface((50, 30), pygame.SRCALPHA) pygame.draw.polygon( REDCAR_ORIGINAL, (255, 0, 0), [(0, 30), (50, 20), (50, 10), (0, 0)]) redangle = 180 redcar = pygame.transform.rotate(REDCAR_ORIGINAL, redangle) redspeed = 5 dx = 0 dy = 0 x = 800 y = 500 pos_red = Vector2(x,y) vel_red = Vector2(-redspeed,0) redrect = redcar.get_rect(center=pos_red) redangle = 180 redcar = pygame.transform.rotate(REDCAR_ORIGINAL, redangle) mask_red = pygame.mask.from_surface(redcar) def starttimer(): global timer timer -= dt def starttimer1(): global timer1 timer1 -= dt def redboost(): font4 = pygame.font.Font(None, 72) timer10 = int(timer) timer11 = round(timer10, 1) timer12 = str(timer11) global timer13 timer13 = font4.render(timer12, False, (255,0,0)) timer = 3 dt = 1 run = True while …
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/90865020
has title: Pygame - Scale_to_length not working 100% of times
downvote count: 2
upvote count: 1
tagged with: python
type: AnsweredQuestion
score: -1
has answer: http://stackoverflow.com/a/51994091
type: Question

http://stackoverflow.com/q/52095800
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/91152098
has comment: http://stackoverflow.com/comment/91141938
answer count: 0
has comment: http://stackoverflow.com/comment/91142838
has comment: http://stackoverflow.com/comment/91143973
type: Question
has comment: http://stackoverflow.com/comment/91148070
has title: django nested inlines, any workaround?
has body: I want to edit a model in admin that has a foreign key to another model that in turn has a foreign key to the base modell: from django.contrib import admin from .models import Role from .models import Address from .models import Date from .models import Person from .models import Name # Register your models here. admin.site.register(Role) admin.site.register(Address) admin.site.register(Date) #admin.site.register(Name) #admin.site.register(Person) class RoleInline(admin.TabularInline): model=Role extra=3 class NameInline(admin.TabularInline): model=Name extra=3 class PersonInline(admin.ModelAdmin): fieldsets=[ (None,{'fields': ['mail','firstName','lastName','phoneNumber','streetAdress','zipcode','city']}), ] inlines = [RoleInline,Name] search_fields = ['firstName'] #admin.site.register(Name,NameInline) admin.site.register(Person,PersonInline) and this is the model: class Role(models.Model): role=models.CharField(max_length=200) person=models.ForeignKey(Person,on_delete=models.CASCADE) def __str__(self): return self.role class Meta: ordering = ('role',) class Name(models.Model): name=models.CharField(max_length=200) role=models.ForeignKey(Role,on_delete=models.CASCADE) def __str__(self): return self.name class Meta: ordering = ('name',) class Address(models.Model): name=models.ForeignKey(Name,on_delete=models.CASCADE) street=models.CharField(max_length=200) city=models.CharField(max_length=200) mail=models.EmailField() phone=PhoneNumberField() def __str__(self): return self.name class Meta: verbose_name_plural = "addreses" class Meta: ordering = ('name',) class Date(models.Model): date=models.DateField() location=models.ManyToManyField(Address) the problem is that name is related to role, not directly to person, i.e role has a foreign key to person and name has a foreign key to role, and that has to be added in tha admin page that I am using. The nested inlines semes to be missing in django, is there any workaround?
score: 0
tagged with: inline
has comment: http://stackoverflow.com/comment/91143006
tagged with: nested
type: UnansweredQuestion

indexing
tags question: http://stackoverflow.com/q/51966528
tags question: http://stackoverflow.com/q/52038461
tags question: http://stackoverflow.com/q/51958145
tags question: http://stackoverflow.com/q/51966498
tags question: http://stackoverflow.com/q/52034957
type: Tag
tags question: http://stackoverflow.com/q/52083304
tags question: http://stackoverflow.com/q/52008437
tags question: http://stackoverflow.com/q/52063689
tags question: http://stackoverflow.com/q/52093302
tags question: http://stackoverflow.com/q/51966450
tags question: http://stackoverflow.com/q/52031908
tags question: http://stackoverflow.com/q/51967890
tags question: http://stackoverflow.com/q/52103100
tags question: http://stackoverflow.com/q/52062560
tags question: http://stackoverflow.com/q/52091177
tags question: http://stackoverflow.com/q/52007584
tags question: http://stackoverflow.com/q/52086486
tags question: http://stackoverflow.com/q/52006325
tags question: http://stackoverflow.com/q/52019960
tags question: http://stackoverflow.com/q/51971312
tag name: indexing
tags question: http://stackoverflow.com/q/52109977
tags question: http://stackoverflow.com/q/52021314
tags question: http://stackoverflow.com/q/51970065
tags question: http://stackoverflow.com/q/52061661
tags question: http://stackoverflow.com/q/52076956
tags question: http://stackoverflow.com/q/51983141
tags question: http://stackoverflow.com/q/52024847
tags question: http://stackoverflow.com/q/52047506
tags question: http://stackoverflow.com/q/51984042
tags question: http://stackoverflow.com/q/51972197
tags question: http://stackoverflow.com/q/51985096
tags question: http://stackoverflow.com/q/52016803

http://stackoverflow.com/q/52052299
tagged with: pytorch
has comment: http://stackoverflow.com/comment/91058397
type: Question
has comment: http://stackoverflow.com/comment/116087958
has comment: http://stackoverflow.com/comment/91055741
score: 0
has comment: http://stackoverflow.com/comment/91057618
upvote count: 1
has title: Cuda error out of memory while running a python code
downvote count: 1
favorite count: 0
answer count: 0
type: UnansweredQuestion
has body: I am trying to run this following code. I am getting an error. The code is from Deep Image Prior downloaded from Github. Can anyone tell me why I am getting this error and where I am wrong? I read something about this and it said to reduce the batch size. How to reduce it? Is it because the .tif file is around 100 MB? The error is RuntimeError: CUDA error: out of memory and I am using 12 GB GPU and CUDA 9.2 from __future__ import print_function import matplotlib.pyplot as plt %matplotlib inline import argparse import os #os.environ['CUDA_VISIBLE_DEVICES'] = '0' import numpy as np from models import * import torch import torch.optim import torch.nn as nn from torch.utils.data import Dataset, DataLoader import warnings warnings.filterwarnings("ignore") from skimage.measure import compare_psnr from models.downsampler import Downsampler from utils.sr_utils import * torch.backends.cudnn.enabled = True torch.backends.cudnn.benchmark =True dtype = torch.cuda.FloatTensor device = torch.device("cuda:0" if torch.cuda.is_available() else"cpu") imsize = (819,819) factor = 2 # 8 enforse_div32 = 'CROP' # we usually need the dimensions to be divisible by a power of two (32 in this case) PLOT = True # To produce images from the paper we took *_GT.png images from LapSRN viewer for corresponding factor, # e.g. x4/zebra_GT.png for factor=4, and x8/zebra_GT.png for factor=8 with torch.no_grad(): path_to_image = '/home/smitha/deep-image-prior/resize.tif' imgs = load_LR_HR_imgs_sr(path_to_image , imsize, factor, enforse_div32) imgs['bicubic_np'], imgs['sharp_np'], imgs['nearest_np'] = get_baselines(imgs['LR_pil'], imgs['HR_pil']) if PLOT: plot_image_grid([imgs['HR_np'], imgs['bicubic_np'], imgs['sharp_np'], imgs['nearest_np']], 4,12); print ('PSNR bicubic: %.4f PSNR nearest: %.4f' % ( compare_psnr(imgs['HR_np'], imgs['bicubic_np']), compare_psnr(imgs['HR_np'], imgs['nearest_np']))) input_depth = 8 INPUT = 'noise' pad = 'reflection' OPT_OVER = 'net' KERNEL_TYPE='lanczos2' LR = 1 tv_weight…
tagged with: python

http://stackoverflow.com/q/52057927
tagged with: python
has answer: http://stackoverflow.com/a/52059227
possible better answer: http://stackoverflow.com/a/52058264
type: AnsweredQuestion
has body: I am tracking some particles on a flat surface using the TrackPy plugin. This results in a dataframe with positions in x and y and a corresponding frame number, here illustrated by a simple list: x=[80.1,80.2,80.1,80.2,80.3] y=[40.1,40.2,40.1,40.2,40.3] frame = [1,2,3,4,5] However, due to the experimental setup, one may lose the particle for a single frame resulting in: x=[80.1,80.2,80.1,80.2,80.3] y=[40.1,40.2,40.1,40.2,40.3] frame = [1,2,3,4,6] Now i would like to extend all list, so that ´frame´ is continues and 'x,y' will repeat the previous value if no frame is present in the original data resulting in something like: x=[80.1,80.2,80.1,80.2,80,2,80.3] y=[40.1,40.2,40.1,40.2,40.2,40.3] frame = [1,2,3,4,5,6]
has answer: http://stackoverflow.com/a/52058259
accepted answer: http://stackoverflow.com/a/52058259
type: Question
tagged with: numpy
has title: Extending array by repeating values if another array is not continues
tagged with: arrays
tagged with: sorting
score: 4
has answer: http://stackoverflow.com/a/52058264
upvote count: 4
has comment: http://stackoverflow.com/comment/91066151
answer count: 3
tagged with: pandas
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/91066108

http://stackoverflow.com/q/52068557
tagged with: google-cloud-pubsub
downvote count: 1
has comment: http://stackoverflow.com/comment/91100054
favorite count: 0
answer count: 0
has comment: http://stackoverflow.com/comment/91127775
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/91132153
has title: Delay in callback method processing in Google PubSub
type: Question
has body: I am trying to pass on the message from a publisher to one of my subscribers in Google Pub/Sub. I think there is a delay in callback method being recognized late by the subscriber. Below is the example: I have executed the callback method as below: def callback(message): print(message.data) message.ack() I am trying to publish the content from publisher publisher.publish(topic,b"Hi hello",spam="eggs") The result is b'hi hello' since I am printing only message.data in callback. Now I am changing my call back function def callback(message): print(message.data) print("hello message") message.ack() The result when I publish the content is still b'hi hello' and it is not showing "hello message". After waiting for 2-3 minutes, it is finally showing the actual result in call back when I execute it again. Could you please help me in addressing this delay if it is possible ? Thank you
has comment: http://stackoverflow.com/comment/91087244
has comment: http://stackoverflow.com/comment/91087291
score: 0
tagged with: google-cloud-platform
upvote count: 1

http://stackoverflow.com/q/52011219
favorite count: 0
has comment: http://stackoverflow.com/comment/90973596
tagged with: tkinter
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90974180
linked to: http://stackoverflow.com/q/38925115
tagged with: python
has body: I am using python 3 tkinter and sqlite I have data inside tkinter Text Widget and then i need to split and save it in a data base table here is my code attempts data = txtReceipt.get("4.0" ,"end") for line in data.splitlines()[2:-2]: no = line.split()[2:3] name = line.split()[1:2] price = line.split()[3:4] series = line.split()[:1] print(no) c.execute("INSERT INTO billed_items(item_name,billed_qty,price,item_bill_series) VALUES(?,?,?,?)",(name),(no),(price),(series)) conn.commit() but i am getting this error message TypeError: function takes at most 2 arguments (5 given) any help please here also when i am trying to read back into text widget su=c.execute("SELECT * FROM billed_items") for row in su: text = str(row) txtReceipt.insert("end",str(row[0])+" "+str(row[1])+'\t\t'+str(row[2])+'\t'+" "+str(row[3])+"\n") in there it only reads the last row in the table i dont know why he cant read all the rows
has answer: http://stackoverflow.com/a/52011365
has title: python sqlite inserting error
downvote count: 1
type: Question
upvote count: 0
has comment: http://stackoverflow.com/comment/90973897
score: -1
answer count: 1
has comment: http://stackoverflow.com/comment/90984395

http://stackoverflow.com/comment/91112207
comment on: http://stackoverflow.com/a/52063468
has text: How skipping rows is going to help me achieve what i want
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/91107679
type: Comment
has text: Does one of these classes define a `next` or `__next__` method? Can we see them?
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/52078738

http://stackoverflow.com/comment/91190116
type: AnswerComment
comment on: http://stackoverflow.com/a/52119613
has text: but however this gives the error as mentioned for one hot encoder.
score: 0
type: Comment

http://stackoverflow.com/q/51962659
downvote count: 0
tagged with: keras
has title: tf.keras.utils.multi_gpu_model does use only one GPU
favorite count: 0
answer count: 0
upvote count: 2
type: UnansweredQuestion
tagged with: python
score: 2
has body: I have two GPUs available which I want to use both to get maximal throughput during inference. That why I wanted to use multi_gpu_model, it should process half of the batch on one GPU and the other half of the other. However, only one GPU is used (checking with nvidia-smi). I could reproduce it with the following code import tensorflow as tf from tensorflow.keras.applications import Xception from tensorflow.keras.utils import multi_gpu_model import numpy as np num_samples = 32 height = 224 width = 224 num_classes = 1000 with tf.device('/cpu:0'): model = Xception(weights=None,input_shape=(height, width, 3),classes=num_classes) # Replicates the model on 2 GPUs. # This assumes that your machine has 2 available GPUs. parallel_model = multi_gpu_model(model, gpus=2) parallel_model.compile(loss='categorical_crossentropy', optimizer='rmsprop') # Generate dummy data. x = np.random.random((num_samples, height, width, 3)).astype(np.float32) dataset = tf.data.Dataset.from_tensor_slices(x) dataset = dataset.batch(32) dataset = dataset.repeat() iterator = dataset.make_one_shot_iterator() batch = iterator.get_next() y = parallel_model(batch) sess = tf.keras.backend.get_session() while True: try: result = sess.run(y) print(result.shape) except tf.errors.OutOfRangeError: break I expect this to use two GPUs, but it uses only 1. Is this a bug or is this expected behaviour? How to change this example to use multiple GPUs?
tagged with: tensorflow
type: Question

http://stackoverflow.com/a/52092729
upvote count: 3
downvote count: 0
has body: You need to break down the code into simpler form to understand it. Taking the first example. a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13] def common_in_two_lists1(list1, list2): re_list = [] for val1 in list1: for val2 in list2: if val1 == val2 and val1 not in re_list: re_list.append(val1) print(re_list) return re_list l = common_in_two_lists1(a, b) OUTPUT [1] [1, 2] [1, 2, 3] [1, 2, 3, 5] [1, 2, 3, 5, 8] [1, 2, 3, 5, 8, 13] You can see that the re_list is appending the value every time. And the [] you have put for the first example is useless. Coming to your second example. If you check the type of the expression, you would find it to be generator. re_list = print(type(val1 for val1 in list1 for val2 in list2 if val1 == val2 and val1 not in re_list)) &lt;class 'generator'&gt; And generator expression is evaluated only when you are try to fetch the value, that explains why you are getting the duplicate 1 on this code. Because in the expression re_list is empty when the generator is created. Finally coming to your solution: I trying to write a program that returns a list that contains only the elements that are common between the lists (without duplicates). You should follow Jon Clements♦ advice and implement it using a set you should take a look at sets... eg: list(set(a).intersection(b))
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/52092566
has comment: http://stackoverflow.com/comment/91136172
answers question: http://stackoverflow.com/q/52092566
has comment: http://stackoverflow.com/comment/91135989
type: Answer
has comment: http://stackoverflow.com/comment/91136311
score: 3

http://stackoverflow.com/a/52085516
has comment: http://stackoverflow.com/comment/91147770
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/52085388
has comment: http://stackoverflow.com/comment/91153434
has body: Try setting your random seed for reproducibility: random.seed(10) Also, if the model is stateless, the cell states are reset at each sequence. But if not for example if your using stateful = True, you will need to reset states after each training run.
has comment: http://stackoverflow.com/comment/91144157
upvote count: 1
type: Answer

http://stackoverflow.com/q/51962673
favorite count: 0
tagged with: subprocess
has comment: http://stackoverflow.com/comment/90875652
has comment: http://stackoverflow.com/comment/90875611
has answer: http://stackoverflow.com/a/51963415
tagged with: git
has body: I am trying to run git clone command using subprocess.check_output() so that I can verify if it clones successfully or not, but its throwing error. Command 'git clone &lt;url&gt;' returned non-zero exit status 128 I am doing: resp = subprocess.check_output('git clone &lt;url&gt;', shell=True) How can I get the output of git clone so that I can verify it worked fine or not and can catch any errors if any. Thanks
type: Question
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90876445
upvote count: 4
linked to: http://stackoverflow.com/q/30474447
accepted answer: http://stackoverflow.com/a/51963415
answer count: 1
downvote count: 0
has title: How to capture the output of git clone command running from python subprocess
score: 4
tagged with: python

http://stackoverflow.com/q/51998226
type: Question
tagged with: statistics
score: 0
has answer: http://stackoverflow.com/a/51999843
answer count: 1
tagged with: scikit-learn
has title: Creating a real estate price index for a given location
has body: I have a dataset with property sales data for a city for the last several years. I am attempting to create a price index, but struggling to find any examples in code or even those same algorithms applied in other sectors. From what I understand, the main algorithms to use are RSR, Case-Shiller and hedonic regression. Maybe there are other methods? But again, there's nothing available that I managed to come across online, all ML work I have looked at so far is aimed at estimating values of individual properties. Would appreciate if anyone could suggest something helpful. Also, what other factors should I consider and what methods to look at?
favorite count: 0
type: UnansweredQuestion
tagged with: python
tagged with: machine-learning
upvote count: 1
downvote count: 1
tagged with: tensorflow

http://stackoverflow.com/q/52020503
score: 0
tagged with: photoshop
has body: The google results return old posts and expired links. As a python user, what can I do to grab all these personal data when I am drawing a picture in photoshop? Are there relevant frameworks that I can use? I am completely baffled on where to even start.
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90991964
tagged with: python
tagged with: logging
has comment: http://stackoverflow.com/comment/90994082
answer count: 0
has comment: http://stackoverflow.com/comment/90995452
type: Question
has title: How can you use python to log pen pressure, stroke length and x,y coordinate using a Wacom tablet?
tagged with: wacom

http://stackoverflow.com/q/52015114
tagged with: python
has body: I tried this approach to pass the form input variable to function via url_for method. But its not working. can anyone check and let me know whats wrong in this code. Function: @app.route('/report_data/&lt;year&gt;/&lt;week&gt;', methods = ['POST']) def report_data(year,week): print year print woy HTML Code : &lt;html&gt; &lt;body&gt; &lt;form action="{{ url_for('report_data', year=n_year, week=n_woy) }}" method="post"&gt; &lt;h3&gt; Enter the details &lt;/h3&gt; Year : &lt;input type="text" name="n_year"&gt; &lt;br&gt; &lt;br&gt; Week : &lt;input type="text" name="n_woy"&gt; &lt;br&gt; &lt;br&gt; &lt;input type="submit" value="Submit"&gt; &lt;br&gt; &lt;/form&gt; &lt;/body&gt; &lt;/html&gt; Issue: Getting "None" for both variable.
type: UnansweredQuestion
type: Question
has title: Python Flask : url_for to pass the variable to function from form template
tagged with: python-2.7
has answer: http://stackoverflow.com/a/52015472
answer count: 1
tagged with: flask
score: 0

http://stackoverflow.com/comment/91088762
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52069454
has text: Oh okay. Will edit it. Thanks!
score: 0

http://stackoverflow.com/q/52072898
answer count: 1
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/52076762
has comment: http://stackoverflow.com/comment/91099319
tagged with: python
tagged with: nlp
type: AnsweredQuestion
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/91099250
type: Question
has body: I'd like to know exactly what is being done to text using the specified pattern in this tokenizer: from nltk.tokenize import RegexpTokenizer tokenizer = RegexpTokenizer(r'[a-zA-Z]\w+\'?\w*') text_token = text.apply(tokenizer.tokenize) Where "text" is a pandas series, each row being a sentence. I specifically want to understand the r'[a-zA-Z]\w+\'?\w'* part. Details (explanation of each component) would be appreciated.
accepted answer: http://stackoverflow.com/a/52076762
has comment: http://stackoverflow.com/comment/91099199
tagged with: nltk
has title: Explanation of Pattern for text tokenizer

http://stackoverflow.com/a/52033693
type: Answer
upvote count: 5
answers question: http://stackoverflow.com/q/52033397
downvote count: 0
score: 5
has body: Let's say you have a mix of different formats that looks like this: import pandas as pd df = pd.DataFrame() df['time'] = ['2018-06-01 06:36:40.047883+00:00', '2018-06-01 06:36:40.047883+00:00', '2018-06-04 11:30:00+00:00', '2018-06-01 06:36:40.047883'] Corresponding output: time 0 2018-06-01 06:36:40.047883+00:00 1 2018-06-01 06:36:40.047883+00:00 2 2018-06-04 11:30:00+00:00 3 2018-06-01 06:36:40.047883 You wish to get to a common format by removing microseconds and anything after +. In short, you want something that is in Y-M-D H-M-S format. Currently, let me assume that your column is in string format. So, we now convert this to a datetime format and then replace the microseconds part with 0 and get rid of it. df['time'] = pd.to_datetime(df['time']) df['time'] = df['time'].apply(lambda x: x.replace(microsecond = 0)) Output: time 0 2018-06-01 06:36:40 1 2018-06-01 06:36:40 2 2018-06-04 11:30:00 3 2018-06-01 06:36:40
has comment: http://stackoverflow.com/comment/91017458

http://stackoverflow.com/a/55027168
type: Answer
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/133824134
has body: So I managed to do it like this: Given 'test_samples' is your 'scipy.sparse.csr.csr_matrix' import json import base64 np_test_samples=test_samples.toarray() jason_test_samples=json.dumps({"data": np_test_samples.tolist()})
downvote count: 0
answers question: http://stackoverflow.com/q/52037323
has comment: http://stackoverflow.com/comment/116565090

http://stackoverflow.com/comment/90940005
type: Comment
has text: Please make *sure* your code executes ... `index` is now undefined.
score: 1
comment on: http://stackoverflow.com/q/51995105
type: QuestionComment

http://stackoverflow.com/comment/91012887
score: 0
type: Comment
has text: Hmm... Interesting. This claim is also supported by the documentation - see here: https://wxpython.org/Phoenix/docs/html/wx.Panel.html#events-events-emitted-by-this-class I didn't notice that.
comment on: http://stackoverflow.com/a/52013024
type: AnswerComment

http://stackoverflow.com/comment/90964843
type: QuestionComment
score: 1
has text: Notice `sum([[1] , [2]], [])` will work.
comment on: http://stackoverflow.com/q/52007283
type: Comment

http://stackoverflow.com/comment/107236516
type: AnswerComment
type: Comment
has text: This answer has nothing to do with the original post at all.
comment on: http://stackoverflow.com/a/52079720
score: 0

http://stackoverflow.com/a/51965716
accepted answer of: http://stackoverflow.com/q/51965561
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/51965561
has comment: http://stackoverflow.com/comment/90881692
type: Answer
score: 5
upvote count: 5
has body: Use only driver.current_url instead of driver.current_url(). From the docs: Some attributes are callable (or methods) and others are non-callable (properties). All the callable attributes are ending with round brackets. So, current_url is a property and not a method hence you don't call it. Usage Example (Python 3) : my_url = driver.current_url print(my_url)

http://stackoverflow.com/q/52032139
has comment: http://stackoverflow.com/comment/91014566
tagged with: python
answer count: 2
downvote count: 3
linked to: http://stackoverflow.com/q/4446366
has answer: http://stackoverflow.com/a/52032207
tagged with: function
tagged with: init
type: UnansweredQuestion
score: -3
tagged with: class
linked to: http://stackoverflow.com/q/45621722
upvote count: 0
has body: class Myclass(object): def __init__(self , msg , integer): self.msg = msg self.integer = integer print (self.msg) print (self.integer) return Error File "&lt;input&gt;", line 3 self.msg = msg ^ IndentationError: expected an indented block
has title: Using MyClass(object) gone wrong?
favorite count: 0
has answer: http://stackoverflow.com/a/52032215
duplicate of: http://stackoverflow.com/q/45621722
type: Question

http://stackoverflow.com/comment/90907500
has text: @CharlesDuffy thank you for information. I tried `bash -x beta.sh` command. It don't raise any error (minus). All lines has plus symbols. So I am really confused.
score: 0
comment on: http://stackoverflow.com/q/51978270
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91156300
type: Comment
has text: Not sure what variable StringIO is supposed to be.
comment on: http://stackoverflow.com/a/52102557
type: AnswerComment
score: 0

http://stackoverflow.com/comment/90975545
type: QuestionComment
has text: two* :) - not 'to'.
score: 0
comment on: http://stackoverflow.com/q/52009967
type: Comment

http://stackoverflow.com/q/52104316
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/91159756
has answer: http://stackoverflow.com/a/64512939
tagged with: django
has title: Reading all the image files in a folder in Django
type: Question
tagged with: file-read
has body: I am trying to create a picture slideshow which will show all the png and jpg files of a folder using django. Problem is how do I open windows explorer through django and prompt user to choose a folder name to load images from. Once this is done, how do I read all image files from this folder? Can I store all image files from this folder inside a list and pass this list in template views through context?
score: 0
has comment: http://stackoverflow.com/comment/91160555
answer count: 1
has comment: http://stackoverflow.com/comment/91160370
linked to: http://stackoverflow.com/q/5871730

http://stackoverflow.com/q/52016690
has comment: http://stackoverflow.com/comment/90983476
tagged with: python
tagged with: curl
has comment: http://stackoverflow.com/comment/90983507
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/52016750
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/90983394
has answer: http://stackoverflow.com/a/52016821
type: Question
has title: How to convert a curl request to python?
possible better answer: http://stackoverflow.com/a/52016821
answer count: 2
has body: I need to convert a curl statement to Python curl -k -d 'id=id1' --data-urlencode 'username=user1' --data-urlencode 'password=pass1' https://aaaa.bbb.com:nnnn I was able to use import requests data = [ ('id', 'id1'), ] response = requests.post('https://aaaa.bbb.com/:nnnn', data=data) With this I get certificate_verify_failed. How can I include urlencode for the username and password
downvote count: 0
has answer: http://stackoverflow.com/a/52016750
favorite count: 0

http://stackoverflow.com/q/52016793
tagged with: encryption
tagged with: python
tagged with: aes
has comment: http://stackoverflow.com/comment/91003355
downvote count: 0
has body: I am writing a program about AES encryption. To get a faster speed for AES encryption and decryption, three states of AES (sub byte, shift row, and mix column) can be combined into one round state. I can successfully combine these three states into one round in AES encryption (it can decrypt with original flow AES decryption) but for AES decryption I can't get the original data. I think it's because of the flow of decryption. In decryption, shift row and sub byte do first and followed by add round and mix column. So, shift row, sub byte and mix column is not continuous. My code is here: """Tham module provides encrypting/decrypting according AES(128) standard. Based on Rijndael algorithm, AES uses 4 transformation for encrypting: SubSytes(), ShiftRows(), MixColumns() and AddRoundKey(). For decrypting it uses inverse functions of that fout. Detales you can read here: http://csrc.nist.gov/publications/fips/fips197/fips-197.pdf or here: http://en.wikipedia.org/wiki/Advanced_Encryption_Standard or here: http://www.cs.bc.edu/~straubin/cs381-05/blockciphers/rijndael_ingles2004.swf or somewhere else. Comments rather won't help if don't read documentation of the algorithm. """ nb = 4 # number of column of State (for AES = 4) nr = 14 # number of rounds ib cipher cycle (if nb = 4 nr = 10) nk = 8 # the key length (in 32-bit words) # This dict will be used in SubBytes(). hex_symbols_to_int = {'a': 10, 'b': 11, 'c': 12, 'd': 13, 'e': 14, 'f': 15} sbox = [ 0x63, 0x7c, 0x77, 0x7b, 0xf2, 0x6b, 0x6f, 0xc5, 0x30, 0x01, 0x67, 0x2b, 0xfe, 0xd7, 0xab, 0x76, 0xca, 0x82, 0xc9, 0x7d, 0xfa, 0x59, 0x47, 0xf0, 0xad, 0xd4, 0xa2, 0xaf, 0x9c, 0xa4, 0x72, 0xc0, 0xb7, 0xfd, 0x93, 0x26, 0x36, 0x3f, 0xf7, 0xcc, 0x34, 0xa5, 0xe5, 0xf1, 0x71, 0xd8, 0x31, 0x15, 0x04, 0xc7, 0x23, 0xc3, 0x18, 0x96, 0x05, 0x9a, 0x07, 0x12, 0x80, 0xe2, 0xeb, 0x27, 0xb2, 0x75, 0x09, 0x83, 0x2c, 0x1a, 0x1b, 0x6e, 0x5a, 0xa0, 0x52, 0x3b, 0xd6, 0xb3, 0x29, 0xe3, 0x2f, 0x84, 0x53, 0xd1, 0x00, 0xed, 0x20, 0xfc, 0xb1, 0x5b, 0x6a,…
score: 1
has title: Combining three states into one round in AES decryption
type: Question
upvote count: 1
has comment: http://stackoverflow.com/comment/91002022
favorite count: 0
answer count: 0
type: UnansweredQuestion

http://stackoverflow.com/a/52098307
has comment: http://stackoverflow.com/comment/91148827
type: Answer
downvote count: 1
has comment: http://stackoverflow.com/comment/91147230
has comment: http://stackoverflow.com/comment/91147063
answers question: http://stackoverflow.com/q/52098163
has body: Assuming you want to overwrite the destination folder if already exists you could easily solve your problem with something like this: if os.path.exists(destination_path): shutil.rmtree(destination_path) shutil.copytree(&lt;your_params&gt;)
score: -1
has comment: http://stackoverflow.com/comment/91146972
upvote count: 0
has comment: http://stackoverflow.com/comment/132240881

http://stackoverflow.com/comment/91123842
type: Comment
comment on: http://stackoverflow.com/a/52086223
type: AnswerComment
score: 0
has text: I do have one more question actually. For the dataframe, I would like to keep the first column (the id number). Would it be possible to state in that line that I would like to keep the 'id' column?

http://stackoverflow.com/a/52086440
score: 1
has body: You should evaluate data['success'] in a condition, whether it is false, then you raise your exception. import json data = json.load(open('data.json')) if data['success'] is not True: raise Exception("Success is false") order = data['order'] print(order)
upvote count: 1
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52086363
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/91123258
type: Answer
answers question: http://stackoverflow.com/q/52086363

http://stackoverflow.com/q/52034360
upvote count: 3
has title: how to create all possible combinations of multiple variables in python
answer count: 1
favorite count: 0
linked to: http://stackoverflow.com/q/16384109
has comment: http://stackoverflow.com/comment/91019150
tagged with: python
accepted answer: http://stackoverflow.com/a/52034467
type: AnsweredQuestion
tagged with: python-3.x
duplicate of: http://stackoverflow.com/q/533905
downvote count: 0
has body: I have a arbitrary number of variables with arbitrary number of valid values each variable can take. For eg. a - (a1,a2,a3), b - (b1,b2), c - (c1,c2,c3,c4,c5). Now I wanted the a list of dictionaries as below [ {a:a1,b:b1,c:c1}, {a:a1,b:b1,c:c2}, {a:a1,b:b1,c:c3}, . . . {a:a3,b:b2,c:c3} ] Total 3*2*5 = 30 combinations will come for the above scenario. How to create them in python. I could have three for loops for each variable as below result_list = list() for a_val in [a1,a2,a3]: for b_val in [b1,b2]: for c_val in [c1,c2,c3,c4,c5]: result_list.append({a:a_val,b:b_val,c:c_val}) But the number of variables also vary. Instead of 3 variables, I wanted to apply on 5 variables as well (a,b,c,d,e) and so on. How to have a common code to achieve this in python
has answer: http://stackoverflow.com/a/52034467
type: Question
tagged with: combinations
score: 3

http://stackoverflow.com/comment/90984662
type: Comment
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/52017297
has text: You probably need to set the axes position property to [0,0,1,1].

http://stackoverflow.com/comment/91124238
type: QuestionComment
comment on: http://stackoverflow.com/q/52086973
score: 1
has text: If `Data_X` is a 2D array, then `for numeric_string in data_X` gives you a 1D array, with at least 7 elements. You can't call `int` on that, for exactly the reason the error message says. Just naming the variable `numeric_string` doesn't change it into a string. And it's not clear what string you were expecting to get there.
type: Comment

http://stackoverflow.com/q/51977053
tagged with: python
tagged with: matplotlib
downvote count: 3
answer count: 1
has comment: http://stackoverflow.com/comment/90904387
upvote count: 0
has answer: http://stackoverflow.com/a/51977192
has comment: http://stackoverflow.com/comment/90904383
score: -3
has body: I am new to matplotlib and I meet a problem when I study by myself I have 3 Numpy arrays and try to put in a bar chart. years_5: array([1975., 1980., 1985., 1990., 1995., 2000., 2005., 2010., 2015.]) ct_5: array([ 6, 21, 27, 28, 67, 163, 198, 192, 192]) ct_norm_5: array([ 0.72488688, 2.53710407, 3.26199095, 3.38280543, 8.09457014, 19.69276018, 23.92126697, 23.19638009, 23.19638009]) Here is part of my code: fig,ax=plt.subplots(figsize=(14,4),linewidth=5,edgecolor='0.5') ax.bar(years_5,ct_norm_5,3,facecolor='.5',alpha='.3',label='Movie Per Year') But I got an error: TypeError: must be real number, not str Can anyone gives me an idea, what does this mean?
has comment: http://stackoverflow.com/comment/90904330
accepted answer: http://stackoverflow.com/a/51977192
type: AnsweredQuestion
has title: Python TypeError: must be real number, not str
favorite count: 0
type: Question

http://stackoverflow.com/q/52038755
score: 5
has comment: http://stackoverflow.com/comment/91028358
answer count: 1
tagged with: variables
favorite count: 0
has comment: http://stackoverflow.com/comment/91027965
has answer: http://stackoverflow.com/a/52038959
upvote count: 5
has comment: http://stackoverflow.com/comment/91027856
tagged with: python
tagged with: list
downvote count: 0
type: UnansweredQuestion
has body: I want to get the name of the variable in a list with the index. For example: a = 1 b = 2 list = [a, b] print(list[0]) and the output is 1 Is there a way to get "a" as a String instead of 1? Also, the above code is just an example. I am coding in pygame, so the actual type of values of the variables in the list is Surface, not int.
duplicate of: http://stackoverflow.com/q/544919
has title: Getting the name of variables in a list
has comment: http://stackoverflow.com/comment/91027780
linked to: http://stackoverflow.com/q/2553354
linked to: http://stackoverflow.com/q/544919
has comment: http://stackoverflow.com/comment/91027784
type: Question
has comment: http://stackoverflow.com/comment/91035699
has comment: http://stackoverflow.com/comment/135609830

ssdp
tag name: ssdp
type: Tag
tags question: http://stackoverflow.com/q/51972632

http://stackoverflow.com/q/52107533
has body: I'm coding a universal controller that controls all smart devices in the house my script runs correctly but show's nothing` ##this is a universal controller #1_controlling LG Webos smart tv import os from pylgtv import WebOsClient import sys import logging class Device: counter=0 def __init__(self,ip,name): self.ip=(ip) self.name=(name) Device.counter += 1 smarttv=Device('192.168.0.105','Smart') class tv(Device): #launching an application def launch_app(self): logging.basicConfig(stream=sys.stdout, level=logging.INFO) try: webos_client = WebOsClient(self) webos_client.launch_app('com.webos.app.music') for app in webos_client.get_apps(): print(app) except: print("Error connecting to TV")
downvote count: 4
has title: Control WebOS SmartTV with Python
tagged with: webos
answer count: 1
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/52107678
has comment: http://stackoverflow.com/comment/91165935
type: UnansweredQuestion
tagged with: python
tagged with: oop
type: Question
upvote count: 0
score: -4

http://stackoverflow.com/comment/91035546
comment on: http://stackoverflow.com/q/52042024
has text: Could you please share some code, what have you tried so far ?
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/52037501
favorite count: 0
has answer: http://stackoverflow.com/a/52050731
tagged with: bnf
upvote count: 5
downvote count: 0
type: UnansweredQuestion
tagged with: python
tagged with: ebnf
has body: I attempt to document a syntax I use in menuentries.conf, which is a configuration file for menu entries, by describing the syntax / grammar using the notation known as extended Backus-Naur-Form EBNF(BNF) This menuentries.conf uses indenting levels as syntactical component as should be displayed in this example: menu_entry_1 menu_entry_2 menu_entry_2_submenu_entry_1 menu_entry_2_submenu_entry_2 menu_entry_2_submenu_entry_2_subsubmenu_1 menu_entry_2_submenu_entry_2_subsubmenu_2 menu_entry_2_submenu_entry_3 menu_entry_3 menu_entry_3_submenu_entry_1 In the above example each entry is represented by a string, which for the sake of the example implies/indicates its position. In addition the example should follow these rules each menu item is represented by single line (hence the menu entries are delimited by NEWLINE) menu entries without any indenting are "top level" menu entries menu entries with an indenting are not "top level" but child entries to the respective higher/upper level menu entry. My attempt at providing a BNF is the following: NEWLINE := '\n' INDENTING := ' ' menu_entry_string := ('a'|'b'|....|'z'|'_'|'0'|'1'|...|'9')+ menu_entries := menu_entry (NEWLINE menuentry)* menu_entry := menu_entry_string (NEWLINE INDENTING menu_entry)* submenu_entry := INDENTING menu_entry_string subsubmenu_entry := INDENTING INDENTING menu_entry_string My question hence is with regards to my disatisfaction of the recursively declared notion menu_entry and its redundancy with submenu_entry and subsubmenu_entry. Knowing that python uses indenting as well to create the notion of blocks, I thought to look up the BNF/definition of pythons grammar (as found here: https://docs.python.org/3/reference/grammar.html) but it leaves the relevant notions of INDENT and DEDENT out of is grammar. My question is hence: How to correctly use EBNF to describe a grammar/syntax in which indenting is employed as a grouping block? Ideally a small example (or if possible correction of my attempt) would …
type: Question
score: 5
tagged with: indentation
answer count: 1
has title: BNF example for language grammar where indenting level defines a block?

sentry
tags question: http://stackoverflow.com/q/52048778
type: Tag
tag name: sentry

http://stackoverflow.com/a/51957956
type: Answer
has comment: http://stackoverflow.com/comment/91007417
has body: pywin32 has been pip-installable for quite some time now. And there are some advantages to installing that way: It avoids this antivirus problem. This is the same way you install every other Python package in 2018. pip can upgrade it, install it into virtual environments (even different versions in different environments), etc. But there are also some disadvantages: Running pip as a normal user can't run the post-install script with elevated privileges. As the docs say, "if you want to use pywin32 for "system wide" features, such as registering COM objects or implementing Windows Services, then you must run the following command from an elevated command prompt: python Scripts/pywin32_postinstall.py -install. pip support is still considered "experimental". I haven't heard of any problems, but this means that if you have a problem and ask for help, you may be asked to pip uninstall it and install it the officially-recommended way (grabbing an installer package from the Releases page and running it). One more option worth considering—probably not relevant if you're using ArcPro, but maybe for other people reading this question—is using Anaconda Python instead of a different Python. Anaconda comes with pywin32 pre-installed. Miniconda can install it with conda install pywin32. While this isn't officially supported by the pywin32 team, it is supported and tested by the Anaconda team.
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/91007317
downvote count: 0
answers question: http://stackoverflow.com/q/51957188

http://stackoverflow.com/q/52075557
favorite count: 0
has comment: http://stackoverflow.com/comment/91182207
has title: memory efficient solution for similarity calculations between items - purchases data
type: UnansweredQuestion
tagged with: python
answer count: 0
score: 1
upvote count: 1
tagged with: scipy
has body: I'm working on product recommendations. My dataset is as follow ( A sample, the full one is with more than 110 000 rows and more than 80000 unique product_id): user_id product_id 0 0E3D17EA-BEEF-493 12909837 1 0FD6955D-484C-4FC8-8C3F 12732936 2 CC2877D0-A15C-4C0A Gklb38 3 b5ad805c-f295-4852 12909841 4 0E3D17EA-BEEF-493 12645715 I want to calculate the cosine similarity between products based on purchased products per user. Why? I need to have as a final result: the list of the 5 most similar products for each product_id. So, I thought the 1st thing that I need to do is to convert the dataframe into this format: where I have one row per user_id and columns are product_ids. If a user bought product_id X then the correspondant row,column will contain the value 1, otherwise 0. I did that using crosstab function of pandas dataframe. crosstab_df = pd.crosstab(df.user_id, df.product_id).astype('bool').astype('int') After that, I calculated the similarities between products. def calculate_similarity(data_items): """Calculate the column-wise cosine similarity for a sparse matrix. Return a new dataframe matrix with similarities. """ # create a scipy sparse matrix data_sparse = sparse.csr_matrix(data_items) #pairwise similarities between all samples in data_sparse.transpose() similarities = cosine_similarity(data_sparse.transpose()) #put the similarities between products in a dataframe sim = pd.DataFrame(data=similarities, index= data_items.columns, columns= data_items.columns) return sim similarity_matrix = calculate_similarity(crosstab_df) I know that this is not efficient, because crosstab doesn't perform well when there is many rows and many columns, which is a case that I have to handle. So, I thought about instead of using a Crosstab DataFrame, I have to use scipy sparse matrix as it makes calculations faster (similarity calculations, vectors normalisation) because the input will be a numpy array, not a dataframe. However, I didn't know how to do it. I also need to keep …
type: Question
tagged with: cosine-similarity
tagged with: numpy
has comment: http://stackoverflow.com/comment/91325123
tagged with: pandas
downvote count: 0

http://stackoverflow.com/comment/91092672
score: 0
type: AnswerComment
has text: I have n number of records. So in that case I think your [:2] will be wrong. Isn't ?
type: Comment
comment on: http://stackoverflow.com/a/52070766

http://stackoverflow.com/a/51966113
upvote count: 2
answers question: http://stackoverflow.com/q/51966089
downvote count: 0
has body: The else and elif should not be indented that much. They should be on the same indentation-level of the if they match: n=int(input("Enter n:")) if 1&lt;x and 5&gt;=x: if n%2==0: print("Wierd") else: print("Not Wierd") elif 5&lt;n and 20=&lt;n: if n%2==0: print("Not Wierd") else: print("Wierd") elif n&gt;20: if n%2==0: print("Wierd") else: print("Not Wierd")
type: Answer
score: 2

http://stackoverflow.com/a/52007600
score: 0
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/52006761
has comment: http://stackoverflow.com/comment/90967815
type: Answer
has body: You can use .join() and .rename(): position.join(data, on=['Date','Symbol']).rename(columns={'Open': 'Open_price'}) Here is a full example: data = pd.DataFrame([['08-02-2018', 'NDA', 0.123], ['08-02-2018','DFA', 0.234], ['08-03-2018', 'NFX', 0.451], ['08-04-2018', 'BBA', 0.453]], columns=['Date', 'Symbol', 'Open']).set_index(['Date', 'Symbol']) position = pd.DataFrame([['08-02-2018', 'NDA'],['08-03-2018', 'NFX'], ['08-04-2018', 'TYA'],['08-04-2018', 'BBA']], columns=['Date', 'Symbol']).set_index(['Date']) data.index = data.index.set_levels([pd.to_datetime(data.index.levels[0]), data.index.levels[1]]) position.index = pd.to_datetime(position.index) position = position.join(data, on=['Date','Symbol']).rename(columns={'Open': 'Open_price'}) Which gives: data Open Date Symbol 2018-08-02 NDA 0.123 DFA 0.234 2018-08-03 NFX 0.451 2018-08-04 BBA 0.453 position Symbol Date 2018-08-02 NDA 2018-08-03 NFX 2018-08-04 TYA 2018-08-04 BBA Using the above .join() and printing position gives: Symbol Open Date 2018-08-02 NDA 0.123 2018-08-03 NFX 0.451 2018-08-04 TYA NaN 2018-08-04 BBA 0.453
has comment: http://stackoverflow.com/comment/90967737
accepted answer of: http://stackoverflow.com/q/52006761

http://stackoverflow.com/a/52027010
upvote count: 5
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52020474
type: AcceptedAnswer
has body: Looking at the documentation, you can pass dedicated options to the text objects in your pie chart using the textprops keyword. textprops accepts a dict, which apparently accepts all options that are accepted by matplotlib.text.Text. Feeding it the options rotation_mode='anchor', va='center' and ha='left' gives pretty good results: import matplotlib.pyplot as plt figure = plt.figure() figure.patch.set_facecolor("None") figure.subplots_adjust(left=0.08, bottom=0.10, right=0.99, top=0.97) figure.clf() axes = figure.add_subplot(111) axes.set_aspect(1) y = [1,2,3, 4,8,16,32] label = ['1.52%', '3.03%', '4.55%', '6.06%', '12.12%', '24.24%', '48.48%'] axes.pie( y, labels=label, labeldistance=0.6, rotatelabels =True, textprops = dict(rotation_mode = 'anchor', va='center', ha='left'), ) plt.show() The result of the code looks like this: Note that I added ax.set_aspect(1) to make the pie chart circular. If you don't want that, just leave out that line.
type: Answer
answers question: http://stackoverflow.com/q/52020474
score: 5

http://stackoverflow.com/comment/91101191
score: 0
type: AnswerComment
type: Comment
has text: But you can make it work for starting digits with a little change: [`(?:\D|^)(?!2016\b)(\d{3,})`](https://regex101.com/r/RtBjE4/2). Further regarding lookbehind version, be aware that it matches such as `102016`.
comment on: http://stackoverflow.com/a/52071940

http://stackoverflow.com/comment/90894265
type: AnswerComment
has text: Did you upgrade your version of ruamel.yaml, as instructed to do? You should be getting 0.15.60. The first one doesn't dump correct: I get `!sometag` and you get `!!sometag` in the output. That error was fixed since 0.15.0 and support for tags on scalars added as well.
type: Comment
comment on: http://stackoverflow.com/a/51971513
score: 0

http://stackoverflow.com/comment/90866968
has text: Did you try using [`order_by`](http://docs.sqlalchemy.org/en/latest/orm/query.html#sqlalchemy.orm.query.Query.order_by)?
comment on: http://stackoverflow.com/q/51958257
score: 0
type: QuestionComment
type: Comment

qpushbutton
type: Tag
tags question: http://stackoverflow.com/q/52015269
tag name: qpushbutton

telegram-bot
tags question: http://stackoverflow.com/q/52029026
tag name: telegram-bot
tags question: http://stackoverflow.com/q/52090122
tags question: http://stackoverflow.com/q/52020056
tags question: http://stackoverflow.com/q/52013582
type: Tag

http://stackoverflow.com/q/52013784
score: 0
answer count: 1
tagged with: dockerpy
accepted answer: http://stackoverflow.com/a/52017674
favorite count: 0
has comment: http://stackoverflow.com/comment/90983296
tagged with: python
type: AnsweredQuestion
upvote count: 1
downvote count: 1
has body: I'm using docker python SDK docker-py, which is quite convenient. I look through the document, I still can't figure out how to create a daemon container with interface terminal,that is to say, if in the shell, this equals to the command docker run -dit image. I know docker-py right now offers the client.containers.run to run a contaniner, and with deatch argument I can run it as a daemon. However, I want start it with a interface terminal. 'Cause my further code would access to the container from the remote server. Is there any way to create it directly with docker-py instead of using os.system(docker run -dit image)?
type: Question
has answer: http://stackoverflow.com/a/52017674
has title: How to create a daemon container with interface terminal using docker-py?
tagged with: docker

http://stackoverflow.com/q/52030954
upvote count: 9
has answer: http://stackoverflow.com/a/79281853
has title: How to change version of Python in PyCharm
has body: I wanted to make Discord bot (should I even write this here), but it's said that I need Python 3.6, not Python 3.7 that I have. How can I change from Python 3.7 to Python 3.6 to make something like that?
score: 9
possible better answer: http://stackoverflow.com/a/79281853
answer count: 3
downvote count: 0
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/52031264
has answer: http://stackoverflow.com/a/52031021
tagged with: python
type: AnsweredQuestion
tagged with: pycharm
has comment: http://stackoverflow.com/comment/129604992
has comment: http://stackoverflow.com/comment/91012386
accepted answer: http://stackoverflow.com/a/52031264
type: Question
has comment: http://stackoverflow.com/comment/91012424

http://stackoverflow.com/a/51979833
type: Answer
answers question: http://stackoverflow.com/q/51977550
has body: My guess is that you have an implicit wait of 15 secs set somewhere in your code because of which your method takes 15 secs if the element is not visible. This is the reason why mixing implicit waits and explicit waits is not recommended. To check if an element is visible on the page you may use find_elements method. This method will wait for the time specified in your implicit wait and return a list of all the elements identified by your locator. Comparing the length of this list to 0 should tell you whether the element is visible or not def check_for_visibility_of_the_element(self, by, locator, timeout): driver.implicitly_wait(timeout) return len(driver.find_elements(By.by, locator)) &gt; 0 driver.implicitly_wait(0)
score: 0

amazon-s3
tags question: http://stackoverflow.com/q/52088524
tags question: http://stackoverflow.com/q/52107184
tags question: http://stackoverflow.com/q/51974324
tags question: http://stackoverflow.com/q/52069265
tags question: http://stackoverflow.com/q/52046518
tags question: http://stackoverflow.com/q/52072672
type: Tag
tags question: http://stackoverflow.com/q/52095823
tags question: http://stackoverflow.com/q/52059567
tags question: http://stackoverflow.com/q/52064420
tags question: http://stackoverflow.com/q/51970168
tags question: http://stackoverflow.com/q/52057964
tags question: http://stackoverflow.com/q/52037563
tags question: http://stackoverflow.com/q/51973670
tags question: http://stackoverflow.com/q/52053693
tag name: amazon-s3

http://stackoverflow.com/comment/91025077
has text: i got [0 1 2 4 5 6 0 1 2 4 5 6] after concatenating as you described. could you please correct your code in question?
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/52037352

http://stackoverflow.com/comment/91020541
type: QuestionComment
comment on: http://stackoverflow.com/q/52035149
score: 0
type: Comment
has text: If you look at the instructions in the repo again, the correct step is: `cd <syntaxnet-git-clone-directory>`. `cd <path>` is useful for navigating between directories using the terminal/command prompt. You should look at some cmd basics before you dig deeper into Python.

http://stackoverflow.com/comment/90990063
type: Comment
type: QuestionComment
has text: When my raspberry pi was called 'MyPi' and was the only one in network I could find its ip by its name... when I named it like some other device, the problem started
score: 0
comment on: http://stackoverflow.com/q/52018811

http://stackoverflow.com/comment/91738486
type: AnswerComment
has text: First, what you mean is that `DataIter` could save at most half of the memory if you do not use it. Then if I have a really large dataset, I still have to split it into many different `npz` files. Second, the `npz` I use is really small but it could still sometimes cause the `Failed to allocate CPU memory` problem. But this is occasionally, not always. So I doubt is the CPU usage problem, rather than the size of the data?
comment on: http://stackoverflow.com/a/52378181
type: Comment
score: 0

http://stackoverflow.com/comment/90902337
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51963207
has text: @robbah yes - that could be it. If commas are not being replaced, it would seem that the string you are attempting to clean up is being split on the commas and so there are none in the values being processed. Perhaps you need to change the [quotechar](https://docs.python.org/3/library/csv.html#csv-fmt-params) to make sure the string ends up in a single value in line.

http://stackoverflow.com/comment/91030160
type: Comment
score: 1
has text: I havent use `langid`. Thank you for advise, I will try to use it!
comment on: http://stackoverflow.com/q/52039155
type: QuestionComment

http://stackoverflow.com/q/52063264
tagged with: matplotlib
has title: Consecutive update figure matplotlib
has comment: http://stackoverflow.com/comment/91077621
has comment: http://stackoverflow.com/comment/91263823
has body: I am plotting pairs of images from two different folders, for each pair I plotted them one after the other using: plt.imshow() and save the fig after each loop. In order to speed it up I want to use the option .set_data so that I only update the figure and not redraw everything. Since I have to do it two times it seems to use only the last one and no update is done on the first call. I am doing somthing like this: data=np.arange(9).reshape(3,3)*10 im1=plt.imshow([data]*4) # simulating an rgb image that i read from file mask=np.ma.array(np.arange(9).reshape(3,3)*10, mask=np.eye(3)) # 1D map im2=plt.imshow(mask, vmin=2, vmax=7) for i in range(10): data=np.arange(9).reshape(3,3)*10 + np.random.randint(0,100,size=(3,3)) im1.set_data([data]*4) # simulating another rgb image read from file mask=np.ma.array(np.arange(9).reshape(3,3)*10+np.random.randint(0,100,size=(3,3)), mask=np.eye(3)) # 1D map im2.set_data(mask) plt.savefig("{}.png".format(i)) with this code, only the mask is being updated but not the background image. Is there a way to make matplotlib use both updates of the data?
has comment: http://stackoverflow.com/comment/91307200
favorite count: 0
tagged with: python
score: 2
answer count: 0
upvote count: 3
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91076955
has comment: http://stackoverflow.com/comment/91312839
downvote count: 1
has comment: http://stackoverflow.com/comment/91262991
type: Question
has comment: http://stackoverflow.com/comment/91077283

http://stackoverflow.com/comment/90901829
comment on: http://stackoverflow.com/q/51975479
type: Comment
score: 2
has text: Just a heads up that your example JSON file is not a valid JSON. You would need to encapsulate the entire file in a set of square brackets, as well as encapsulate your keys with double quotations.
type: QuestionComment

http://stackoverflow.com/a/52080239
has comment: http://stackoverflow.com/comment/91118496
type: AcceptedAnswer
downvote count: 0
has body: To create an output you need to create a figure with your data and layout variables. Then use iplot to display the figure. fig = dict(data=data, layout=layout) iplot(fig) Depending on the type of map you are trying to make, you may need to reformat your data and layout variables. You can find the different map options here.
has comment: http://stackoverflow.com/comment/91171889
type: Answer
upvote count: 1
accepted answer of: http://stackoverflow.com/q/52064771
has comment: http://stackoverflow.com/comment/91161596
score: 1
answers question: http://stackoverflow.com/q/52064771

http://stackoverflow.com/comment/90950313
type: QuestionComment
has text: You have a variable named `winner` and a function named `winner`. See the problem?
score: 5
comment on: http://stackoverflow.com/q/52000635
type: Comment

http://stackoverflow.com/comment/91073924
comment on: http://stackoverflow.com/q/52061299
type: QuestionComment
type: Comment
score: 1
has text: Right, so you have a [XY problem](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem). You have mis-diagnosed the problem and asked a question about your diagnosis, not the real problem you were trying to solve. Sounds like you need to use SQL parameters.

http://stackoverflow.com/comment/91036489
has text: I guess we have a different understanding of the question. I added mine to my answer, and maybe you should do the same, so that OP and others know the prerequisites for our solutions.
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52042515

http://stackoverflow.com/q/52103408
has comment: http://stackoverflow.com/comment/91157799
has title: Seaborn pairplot hue parameter not working as expected
tagged with: seaborn
score: 13
tagged with: python
has comment: http://stackoverflow.com/comment/91157916
tagged with: plot
type: AnsweredQuestion
type: Question
has comment: http://stackoverflow.com/comment/136268307
has answer: http://stackoverflow.com/a/52657076
accepted answer: http://stackoverflow.com/a/52657076
answer count: 1
downvote count: 1
has body: If "C" was assigned as value for the "hue" parameter, it was expected Seaborn not displayed column "C". Am I wrong? sns.pairplot(df, hue='C') DataFrame:
favorite count: 0
upvote count: 14
has comment: http://stackoverflow.com/comment/91158861

http://stackoverflow.com/q/51975723
has comment: http://stackoverflow.com/comment/90909030
upvote count: 1
type: Question
has title: Tkinter treeview widgets not properly aligned/added space between widgets
downvote count: 0
has answer: http://stackoverflow.com/a/51980677
accepted answer: http://stackoverflow.com/a/51980677
tagged with: grid-layout
answer count: 1
favorite count: 0
has body: I am working on this table in tkinter made from a bunch of treeveiw widgets. The idea is to get a table where I can add lines, select lines and edit them. In the code below you can add lines to the table by pushing the button. I now want to control the height of each row by configuring the style. However, when I use style the alignment of the treeview widgets is messed up, see attached picture. Any suggestions how to fix this? EDIT: The problem is the added space between the widgets. The code for the table is: from tkinter import * from tkinter import ttk class MyApp(Tk): def __init__(self): super(MyApp, self).__init__() self.geometry('950x500+100+100') self.NewTree = [] label = Label(self,text='Table with some data', font=("Arial Bold", 25)) label.pack() self.addLine() master_frame = Frame(self, bd=3, relief=RIDGE) master_frame.pack(side=BOTTOM) # Create a frame for the canvas and scrollbar(s). frame2 = Frame(master_frame) frame2.pack(side = BOTTOM) # Add a canvas in that frame. self.canvas = Canvas(frame2) self.canvas.grid(row=0, column=0) # Create a vertical scrollbar linked to the canvas. vsbar = Scrollbar(frame2, orient=VERTICAL, command=self.canvas.yview) vsbar.grid(row=0, column=1, sticky=NS) self.canvas.configure(yscrollcommand=vsbar.set) # Create a frame on the canvas to contain the buttons. self.table_frame = Frame(self.canvas) # Create canvas window to hold the buttons_frame. self.canvas.create_window((0,0), window=self.table_frame, anchor=NW) def addLine(self): #Make button for adding step bt = Button(self,text='Add Line',command=lambda: self.addLineMethod()) bt.config(width=9, height=1) bt.pack() def addLineMethod(self): lineNumber = int(len(self.NewTree)/5) for index in range(5): s = ttk.Style() s.configure('MyStyle.Treeview', rowheight=25) self.NewTree.append(ttk.Treeview(self.table_frame, height=1,show="tree",columns=("0"),style='MyStyle.Treeview')) #Works fine when using this line instead of those above #self.NewTree.append(ttk.Treeview(self.table_f…
tagged with: python-3.x
tagged with: python
has comment: http://stackoverflow.com/comment/90901946
type: AnsweredQuestion
tagged with: tkinter
score: 1
tagged with: treeview

http://stackoverflow.com/comment/91140315
type: QuestionComment
has text: I *think* you simply want to reverse your list. There's a very easy way to do that.
comment on: http://stackoverflow.com/q/52095027
score: 0
type: Comment

http://stackoverflow.com/a/52103575
type: Answer
has body: Using a list comprehension and np.array: df.assign(sumCol=[np.array(x) + np.array(y) for x, y in zip(df.Col1, df.Col2)]) DateTime Col1 Col2 sumCol 0 2018-01-02 [1, 2] [11, 21] [12, 23] 1 2018-01-03 [3, 4] [31, 41] [34, 45] If the arrays are always the same length: df.assign(sumCol=[np.stack([x,y]).sum(0) for x, y in zip(df.Col1, df.Col2)]) To apply this to many columns, you can use iloc zip(*df.iloc[:, 1:].values.T) Here is an example on a wider DataFrame: A B C D 0 1 [1, 2] [1, 2] [1, 2] 1 2 [3, 4] [3, 4] [3, 4] 2 3 [5, 6] [5, 6] [5, 6] Using zip with df.values df.assign(sumCol=[np.stack(a).sum(0) for a in zip(*df.iloc[:, 1:].values.T)]) A B C D sumCol 0 1 [1, 2] [1, 2] [1, 2] [3, 6] 1 2 [3, 4] [3, 4] [3, 4] [9, 12] 2 3 [5, 6] [5, 6] [5, 6] [15, 18]
upvote count: 3
has comment: http://stackoverflow.com/comment/91158393
score: 3
has comment: http://stackoverflow.com/comment/91158248
downvote count: 0
answers question: http://stackoverflow.com/q/52103441

http://stackoverflow.com/a/52029914
type: Answer
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/52029879
accepted answer of: http://stackoverflow.com/q/52029879
has body: Yes you can. As long as it is a minimization instead of maximization, everything should be exactly the same as in the examples.
upvote count: 1
type: AcceptedAnswer

http://stackoverflow.com/a/51999937
answers question: http://stackoverflow.com/q/51999353
type: Answer
upvote count: 5
downvote count: 0
has body: Adding to Sapan's answer: In C++ it might conceptionally use a third variable to swap. But you can see here that the compiler can produce the same assembly as the one shown from python: void foo(int&amp; a, int&amp; b) { std::swap(a, b); } turns into foo(int&amp;, int&amp;): mov eax, DWORD PTR [rdi] mov edx, DWORD PTR [rsi] mov DWORD PTR [rdi], edx mov DWORD PTR [rsi], eax ret https://godbolt.org/g/dRrzg6
score: 5

opencv
type: Tag
tags question: http://stackoverflow.com/q/52048578
tags question: http://stackoverflow.com/q/52050917
tags question: http://stackoverflow.com/q/52083129
tags question: http://stackoverflow.com/q/52029332
tags question: http://stackoverflow.com/q/51987825
tags question: http://stackoverflow.com/q/52078231
tags question: http://stackoverflow.com/q/51961800
tags question: http://stackoverflow.com/q/52017963
tags question: http://stackoverflow.com/q/52099151
tags question: http://stackoverflow.com/q/51962783
tags question: http://stackoverflow.com/q/52065142
tags question: http://stackoverflow.com/q/52044149
tags question: http://stackoverflow.com/q/52087533
tags question: http://stackoverflow.com/q/52099356
tags question: http://stackoverflow.com/q/51974279
tags question: http://stackoverflow.com/q/52004739
tags question: http://stackoverflow.com/q/52075881
tags question: http://stackoverflow.com/q/52043621
tags question: http://stackoverflow.com/q/51970072
tags question: http://stackoverflow.com/q/51983058
tags question: http://stackoverflow.com/q/52001891
tags question: http://stackoverflow.com/q/52024946
tags question: http://stackoverflow.com/q/52037644
tags question: http://stackoverflow.com/q/52029233
tags question: http://stackoverflow.com/q/51969992
tags question: http://stackoverflow.com/q/52021661
tags question: http://stackoverflow.com/q/52072784
tags question: http://stackoverflow.com/q/52017123
tags question: http://stackoverflow.com/q/51971493
tag name: opencv
tags question: http://stackoverflow.com/q/52056470
tags question: http://stackoverflow.com/q/52107379
tags question: http://stackoverflow.com/q/52046064
tags question: http://stackoverflow.com/q/52060611
tags question: http://stackoverflow.com/q/52082329
tags question: http://stackoverflow.com/q/52090826
tags question: http://stackoverflow.com/q/52039683
tags question: http://stackoverflow.com/q/51961068
tags question: http://stackoverflow.com/q/52043671
tags question: http://stackoverflow.com/q/52035388
tags question: http://stackoverflow.com/q/52061680
tags question: http://stackoverflow.com/q/52044711
tags question: http://stackoverflow.com/q/52081318
tags question: http://stackoverflow.com/q/52078258
tags question: http://stackoverflow.com/q/52031502
tags question: http://stackoverflow.com/q/52089937
tags question: http://stackoverflow.com/q/51976832
tags question: http://stackoverflow.com/q/51996937
tags question: http://stackoverflow.com/q/51990390
tags question: http://stackoverflow.com/q/52052480
tags question: http://stackoverflow.com/q/52050860
tags question: http://stackoverflow.com/q/52084725
tags question: http://stackoverflow.com/q/52041888
tags question: http://stackoverflow.com/q/52020536
tags question: http://stackoverflow.com/q/52059560
tags question: http://stackoverflow.com/q/52007898
tags question: http://stackoverflow.com/q/52095906
tags question: http://stackoverflow.com/q/52052884
tags question: http://stackoverflow.com/q/52083714
tags question: http://stackoverflow.com/q/52016253
tags question: http://stackoverflow.com/q/52096625
tags question: http://stackoverflow.com/q/51983458
tags question: http://stackoverflow.com/q/51986717
tags question: http://stackoverflow.com/q/52112399
tags question: http://stackoverflow.com/q/52044113
tags question: http://stackoverflow.com/q/51990490
tags question: http://stackoverflow.com/q/52049143
tags question: http://stackoverflow.com/q/52083797
tags question: http://stackoverflow.com/q/52029115
tags question: http://stackoverflow.com/q/52000260

http://stackoverflow.com/q/51957339
tagged with: go
has answer: http://stackoverflow.com/a/51958401
type: UnansweredQuestion
tagged with: python
score: 2
upvote count: 2
type: Question
has comment: http://stackoverflow.com/comment/90865289
tagged with: http://stackoverflow.com/tag/json
has title: Can I load a Python trained classifier in Golang?
has body: I am trying to load a python trained classifier in a Golang server. In python, I generally do that: classifier = pickle.load( open("classifier1.p", "rb")) Is there any equivalent in Golang? It took me 3 days to train the data and I can't wait again. So I tried to convert the classifier1.p to JSON format using this code. fpkl = pickle.load( open("whatever/classifier1.p", "rb")) fjson = open("whatever/classifier.json", "w") json.dump(fpkl, fjson, ensure_ascii=False, sort_keys=True, indent=4) An error occured: Object of type 'Pipeline' is not JSON serializable I need some advice. Is there any Golang equivalent for my first problem? If there isn't, what can I do to avoid the data training again? Thanks in advance.
downvote count: 0
answer count: 1
favorite count: 0

http://stackoverflow.com/comment/90917712
type: Comment
comment on: http://stackoverflow.com/a/51983955
score: 2
type: AnswerComment
has text: @AgostBiro I appreciate your comment. It is just that my assumptions met expectations of OP. Thank you.

http://stackoverflow.com/a/52106288
type: Answer
score: 3
upvote count: 3
answers question: http://stackoverflow.com/q/52106273
downvote count: 0
has body: Try this: for k, v in humans.items(): if v &gt; 20: print(k) Or, a more pythonic way: print([k for k, v in humans.items() if v &gt; 20])

http://stackoverflow.com/comment/90938705
type: AnswerComment
has text: Thanks a lot Prune, it works with your idea. Here a very naive implementation:
type: Comment
comment on: http://stackoverflow.com/a/51994159
score: 0

http://stackoverflow.com/q/51957706
has comment: http://stackoverflow.com/comment/90865909
answer count: 0
has comment: http://stackoverflow.com/comment/90865868
has comment: http://stackoverflow.com/comment/90865843
linked to: http://stackoverflow.com/q/51956302
type: Question
has comment: http://stackoverflow.com/comment/90865851
score: 0
tagged with: python-import
linked to: http://stackoverflow.com/q/2459300
has body: Earlier today I asked a closely related question and got great answers. But I'd really asked the wrong question. So I'll try again: Suppose I have a Python module "main.py": # main.py import math # from the standard Python library from my_own_module import * ... foo = math.cos(bar) And I also need to import the standard math module in "my_own_module.py": # my_own_module.py import math ... baz = math.sin(qux) In this case I think import math in "main.py" is redundant and can be omitted. What's best practice in this case: Omit import math from "main.py" becuase it's redundant? Or, Keep import math in "main.py" to clarify that the code in that module requires it? I suppose somebody will say "don't use import *". In this case "my_own_module.py" is a personal library of small routines that I include in every Python project. (For example, I have my own mkdir() that doesn't complain if the directory already exists.) It seems very convenient to use import * here.
duplicate of: http://stackoverflow.com/q/2459300
type: UnansweredQuestion
has title: Best practice for nested Python module imports with *
tagged with: python

http://stackoverflow.com/a/51959734
type: Answer
score: -1
downvote count: 1
upvote count: 0
has body: This looks like a great use for ChainMap &gt;&gt;&gt; a={'A': ['Zero'], ... 'B': ['Zero'], ... 'C': ['Zero'], ... 'D': ['Zero']} &gt;&gt;&gt; b={'A': [2338.099365234375, ... -3633.070068359375, ... -73.45938873291016], ... 'D':[2839.291015625, ... -2248.350341796875, ... 1557.59423828125]} &gt;&gt;&gt; map=ChainMap(b,a) &gt;&gt;&gt; map['A'] [2338.099365234375, -3633.070068359375, -73.45938873291016] &gt;&gt;&gt; map['C'] ['Zero'] The key precedence will be on the order of the dictionaries, so if you can't control order or if the ['Zero'] are mixed and matched: this way can't help.
answers question: http://stackoverflow.com/q/51959569

http://stackoverflow.com/comment/90948227
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51999623
has text: Interesting that you get two different errors. For `[Errno 13] Permission denied`, you don't have the file opened with anything do you?
score: 0

http://stackoverflow.com/comment/91102249
type: QuestionComment
has text: Amazing. Thank you.
comment on: http://stackoverflow.com/q/52073938
score: 0
type: Comment

http://stackoverflow.com/comment/101272388
type: Comment
comment on: http://stackoverflow.com/a/57393328
has text: haven't used airflow in a while so could be wrong: dag level args are kwargs in `DAG` init, but `default_args` set defaults on each task which you can then override on the tasks. `sleep1 >> sleep2` is the same as setting which tasks are down stream. But I think in this case I was mixing up upstream and downstream. I *think* in your case `sleep2` is down stream so by setting wait for downstream to false on `sleep1`, you are telling sleep1 is doesn't have to wait for the previous dagrun to finish before starting another. You could test by making the `sleep` longer than the `schedule_interval`
type: AnswerComment
score: 0

compilation
tags question: http://stackoverflow.com/q/52022315
tag name: compilation
tags question: http://stackoverflow.com/q/52017740
type: Tag

http://stackoverflow.com/comment/91055376
comment on: http://stackoverflow.com/a/52052293
type: Comment
has text: Well, I changed to `(https:\/\/smtgvs\.weathernews\.jp\/s\/topics\/img\/\d+\/\w+\.(jpg|png))`, cause I need full URL, this way I got a list as `[https://smtgvs.weathernews.jp/s/topics/img/201807/201807300285_sns_img_A.jpg, jpg]`, can I only get URL? I mean how can I omit `(` and `)` for `jpg|png`?
score: 0
type: AnswerComment

http://stackoverflow.com/q/52016555
has body: I have following list of dictionaries which contains job_name,count and city name question = [{ "count": 2, "city": "Pune", "job_NAME": "clerk" }, { "count": 1, "city": "kolkata", "job_NAME": "manager" }, { "count": 2, "city": "Mumbai", "job_NAME": "accountant" }, { "count": 1, "city": "New Delhi", "job_NAME": "clerk" }] what i want is if job_name is same in this case "clerk" the count and city has to be in one list under key "jobs" answer = [{ "job_name": "clerk", "jobs": [{ "city": "pune", "count": 2 }, { "city": "New Delhi", "count": 1 }] }, { "job_name": "manager", "jobs": [{ "city": "kolkata", "count": 1 }] }, { "job_name": "accountant", "jobs": [{ "city": "Mumbai", "count": 2 }] }] if there is any job duplicate job profile in question list in this case clerk its city and count should be appended in "jobs" key list. i would be very grateful for any help provided! Thanks in advance
answer count: 3
favorite count: 0
tagged with: python-3.x
has title: I am working with python3, where i have list of dictionaries
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/52016626
upvote count: 2
score: 1
tagged with: pymongo
has answer: http://stackoverflow.com/a/52016649
downvote count: 1
type: Question
has answer: http://stackoverflow.com/a/52016660

http://stackoverflow.com/comment/90891960
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/51970737
has text: What exactly is this? A numpy array or a Series? Or just a Python list?

http://stackoverflow.com/q/51986706
type: Question
has comment: http://stackoverflow.com/comment/90924096
score: 0
has comment: http://stackoverflow.com/comment/90945481
upvote count: 1
downvote count: 1
tagged with: scikit-learn
favorite count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90945192
has comment: http://stackoverflow.com/comment/90923318
tagged with: machine-learning
tagged with: python
has comment: http://stackoverflow.com/comment/90945314
answer count: 0
has body: Is it possible to use RFE and GridSearch together with ClassifierChain? A short snippet of my current approach: sss = StratifiedShuffleSplit(n_splits=7, test_size=600, random_state=1) clf = ClassifierChain(LinearSVC(), order='random', cv=sss, random_state=3) rfe = RFE(estimator=clf, step=100, n_features_to_select=0.93) features_array = rfe.fit_transform(features_array, labels_data.values.ravel()) parameters = { "clf__base_estimator": (LinearSVC(C=1e-20), ), "clf__order": ([0,1,2,3,4,5,6],), "clf__cv": (sss, ), "clf__random_state": (None, 0, 1, 2) } pipeline = Pipeline([('clf', clf)]) grid_search = GridSearchCV(pipeline, parameters, scoring = scoring, refit = 'rec', n_jobs=-1, cv=sss, error_score='raise', return_train_score=True, verbose=True) grid_search.fit(features_array, labels_data.values.ravel()) This doesn't work, after executing I get a huge load of exceptions. I use Anaconda Jupyter Notebook so there are also exceptions from the runtime environment. Maybe you guys cut through the problem and will see on first glance what the problem is, otherwise I will post the exceptions. Edit: New approach without RFE: scoring = {'rec': 'recall', 'acc': 'accuracy', 'prec': 'precision', 'rocauc': 'roc_auc'} tfidf = TfidfVectorizer(#stuff) features_array = tfidf.fit_transform(clean_features_ref) clf = ClassifierChain(LinearSVC(), order='random', cv=sss, random_state=3) parameters = { 'base_estimator__C': (1e-14,1e-10, 1e-4) } grid_search = GridSearchCV(clf, parameters, scoring = scoring, refit = 'rec', n_jobs=-1, cv=sss, error_score='raise', return_train_score=True, verbose =True) grid_search.fit(features_array, labels_data.values.ravel()) Edit_2: So I just found out that this isn't working already: clf = ClassifierChain(LinearSVC(), order='random', cv=sss, random_state=3) clf.fit(features_array, labels_data.values.ravel()) with IndexError: tuple index out of range
has comment: http://stackoverflow.com/comment/90948097
has title: Python Sklearn - Use RFE and GridSearch with ClassifierChain

http://stackoverflow.com/q/52084421
type: Question
tagged with: line-plot
score: 10
has answer: http://stackoverflow.com/a/77068597
accepted answer: http://stackoverflow.com/a/52085010
tagged with: visualization
answer count: 3
has body: I want to fill the area under a line plot so it looks as the picture below: instead of built on the following .csv file: 01-01-97 1 01-02-97 2 01-03-97 3 ... 01-11-17 251 01-12-17 252 01-01-18 253 what should I change in this code to generate the desired graph? import pandas as pd import seaborn as sns from matplotlib import pyplot as plt # load csv df=pd.read_csv("test.csv") # generate graph g = sns.lineplot(x="Date", y="Data", data=df) plt.show()
downvote count: 0
has title: How to fill area under line plot in seaborn
has answer: http://stackoverflow.com/a/54756334
favorite count: 0
has answer: http://stackoverflow.com/a/52085010
tagged with: seaborn
upvote count: 10
tagged with: python
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/54756334

http://stackoverflow.com/q/51998917
tagged with: docker-compose
has body: I'm writing project using docker and django (2.1). I've installed module 'django-widget-tweaks' inside a container and added 'widget_tweaks' to INSTALLED_APPS. When I start project using docker-compose up everything works well, but when I want to run something like docker-compose run &lt;container name&gt; python manage.py test in another terminal an error occurs. Traceback (most recent call last): File "manage.py", line 15, in &lt;module&gt; execute_from_command_line(sys.argv) File "/usr/local/lib/python3.6/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.6/site-packages/django/core/management/__init__.py", line 357, in execute django.setup() File "/usr/local/lib/python3.6/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/usr/local/lib/python3.6/site-packages/django/apps/registry.py", line 89, in populate app_config = AppConfig.create(entry) File "/usr/local/lib/python3.6/site-packages/django/apps/config.py", line 90, in create module = import_module(entry) File "/usr/local/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "&lt;frozen importlib._bootstrap&gt;", line 994, in _gcd_import File "&lt;frozen importlib._bootstrap&gt;", line 971, in _find_and_load File "&lt;frozen importlib._bootstrap&gt;", line 953, in _find_and_load_unlocked ModuleNotFoundError: No module named 'widget_tweaks' But when I directly run the same command python manage.py test inside a docker container, it works. widget-tweaks has been installed both on container and on my machine. Could you advice something to solve the problem? Thanks in advance!
type: Question
has comment: http://stackoverflow.com/comment/90973741
has comment: http://stackoverflow.com/comment/90966350
score: 0
answer count: 0
type: UnansweredQuestion
tagged with: django
has comment: http://stackoverflow.com/comment/90972308
tagged with: python
has comment: http://stackoverflow.com/comment/90965412
has title: ModuleNotFoundError: No module named 'widget_tweaks'

http://stackoverflow.com/q/52017357
score: 0
answer count: 1
tagged with: pycharm
type: UnansweredQuestion
has body: Helllo, Im trying to do do tutorial from https://behave.readthedocs.io/en/latest/tutorial.html and when im creating tutorial.feature in pycharm (by gherkin file), all the code is underlined and marked as wrong... Here you can see my setup (i have pycharm pro) and in BDD i have behave. tutorial.feature file settings
tagged with: python
tagged with: python-behave
has comment: http://stackoverflow.com/comment/90984746
type: Question
has title: Pycharm can't interprete behave
has answer: http://stackoverflow.com/a/52017885

http://stackoverflow.com/comment/91105823
score: 0
type: Comment
comment on: http://stackoverflow.com/q/52077632
type: QuestionComment
has text: @MartijnPieters I cant quite get what you mean, Basically whenever I run the code that I posted, I get this print (Will edit in post) - Which means that somehow I do get all the options including the first one.

http://stackoverflow.com/comment/91119261
has text: Can you move it into the `try` clause?
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52084429
type: Comment

http://stackoverflow.com/comment/91442052
type: QuestionComment
has text: Thanks to all for your input. Indeed it was a numpy versioning issue. Issue resolved.
comment on: http://stackoverflow.com/q/52064375
score: 0
type: Comment

http://stackoverflow.com/q/51984225
has comment: http://stackoverflow.com/comment/90918013
tagged with: python
type: AnsweredQuestion
tagged with: python-3.x
has title: I am getting __init__() got an unexpected keyword argument 'instance' with CreateView
has comment: http://stackoverflow.com/comment/90918413
has comment: http://stackoverflow.com/comment/90918427
tagged with: django
possible better answer: http://stackoverflow.com/a/51984817
type: Question
has comment: http://stackoverflow.com/comment/90930779
has comment: http://stackoverflow.com/comment/90918102
tagged with: django-views
has body: I am using Django 2.1 version. I am trying to make CreateView. Here is my views.py; # views.py class CreateJob(CreateView): form_class = CreateJob template_name = 'category_list.html' and here is my forms.py; # forms.py from django import forms from myapp.models import Category class CreateJob(forms.Form): CATEGORY_CHOICES = ( ) category_list = forms.ChoiceField( widget=forms.Select(attrs={ "id": "cate" }), choices=CATEGORY_CHOICES, required=True, ) def __init__(self, *args, **kwargs): super(CreateJob, self).__init__(*args, **kwargs) category_choices = [(cat.id, cat.name) for cat in Category.objects.all()] self.fields['category_list'].choices = category_choices in this forms.py I am trying to make choicefield and list category objects. and in my template, when i select category, it will make ajax request and will list description list which is related to Category model. you can look my template below. once I select one of categories which is created via choicefield in forms.py, it will list description list in option which has "desc" id. {% extends '../base.html' %} {% block body %} {% csrf_token %} {{ form }} {% for description in description_list %} {{ description.name }}> {% endfor %} {% endblock %} {% block script %} {% endblock %} and my urls.py is looks like this; path('test/', CreateJob.as_view()), when I proceed to 127.0.0.1:8000/test, it gives me this error: File "C:\Users\kenan\Desktop\Django\jobs\myapp\forms.py", line 16, in __init__ super(CreateJob, self).__init__(*args, **kwargs) TypeError: __init__() got an unexpected keyword argument 'instance' [23/Aug/2018 14:37:03] "GET /test/ HTTP/1.1" 500 89443 I want to note that, I searched for it and some people fix their problem by changing forms.Form to forms.ModelForm. but that's not what I want. Thanks in advance!
has comment: http://stackoverflow.com/comment/90918054
has comment: http://stackoverflow.com/comment/90922753
tagged with: django-forms
upvote count: 4
has comment: http://stackoverflow.com/comment/90918201
answer count: 2
has answer: http://stackoverflow.com/a/51985390
accepted answer: http://stackoverflow.com/a/51985390
downvote count: 0
has comment: http://stackoverflow.com/comment/90920776
score: 4
has comment: http://stackoverflow.com/comment/90918923
has answer: http://stackoverflow.com/a/51984817
favorite count: 0
has comment: http://stackoverflow.com/comment/90918492
has comment: http://stackoverflow.com/comment/90918987

http://stackoverflow.com/a/52005357
downvote count: 0
has comment: http://stackoverflow.com/comment/90960575
has comment: http://stackoverflow.com/comment/90960562
answers question: http://stackoverflow.com/q/52005226
accepted answer of: http://stackoverflow.com/q/52005226
upvote count: 2
type: AcceptedAnswer
has body: You don't get 20000 because you are creating powers of 10 as pow(10,i-1). It is mathematically not possibly from this equation. Moreover, 10000 is not displayed because you just use ax.set_xticklabels to reset the labels of the already existing xticks. Since you have only 5 major ticks in your first plot, you only create 5 labels as 0, 1, 10, 100, 1000 as per your definition. To get what you want, just replace the last three lines of your code (after plotting) by: locs = ax.get_xticks() labels = [ '{}{}'.format(int(i), '\u20ac') for i in locs] ax.set_xticklabels(labels) Output
has comment: http://stackoverflow.com/comment/90960532
type: Answer
score: 2

http://stackoverflow.com/comment/91026101
type: QuestionComment
has text: Are you running the code on an Amazon EC2 instance, or on your own computer (not on EC2)?
score: 0
comment on: http://stackoverflow.com/q/52037563
type: Comment

http://stackoverflow.com/q/52050476
score: 2
upvote count: 2
type: Question
has answer: http://stackoverflow.com/a/52050590
has title: how to access members of another modules in python
has comment: http://stackoverflow.com/comment/91090941
has comment: http://stackoverflow.com/comment/91051191
answer count: 2
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/91090998
type: UnansweredQuestion
has body: Demo1.py -------- ph=10 def ph(): print("Phone") def email(): print("Email") Demo2.py --------- from Demo1 import ph,email print(email) print(ph) output: Email &lt;function ph at 0x0000021E81BC3158&gt; When I print variable ph in demo2.py module it will call function but not variable ph. How do I access the variable ph?
tagged with: python
tagged with: module
has answer: http://stackoverflow.com/a/52050611

http://stackoverflow.com/comment/91000977
type: QuestionComment
has text: You can use the VideoWriter() module and there is no reason to wait till the end, you could add the frames to the video as you process them.
type: Comment
comment on: http://stackoverflow.com/q/52024946
score: 0

http://stackoverflow.com/a/52045409
type: Answer
has body: random.choice expects a sequence as a parameter. So you might probably use: rightPath = random.choice(['North', 'East', 'South', 'West'])
upvote count: 3
score: 3
downvote count: 0
answers question: http://stackoverflow.com/q/52045352

http://stackoverflow.com/q/52044772
answer count: 1
has title: When executing thread, the first execution fails in try statement
tagged with: python
accepted answer: http://stackoverflow.com/a/52046056
tagged with: qthread
type: AnsweredQuestion
tagged with: pyqt5
type: Question
has body: from PyQt5.QtWidgets import QMainWindow, QApplication,QLineEdit, QPushButton, QWidget, QAction, QTabWidget,QVBoxLayout from PyQt5.QtCore import (QCoreApplication, QObject, QRunnable, QThread, QThreadPool, pyqtSignal) import sys import os from shutil import copy2 import _thread import time class AThread(QThread): def run(self): count = 0 while count &lt; 5: time.sleep(1) print("A Increasing") count += 1 class Example(QWidget): def __init__(self): super().__init__() self.setAcceptDrops(True) self.setWindowTitle('Learn') self.setGeometry(300, 300, 300, 150) self.layout = QVBoxLayout(self) # Initialize tab screen self.tabs = QTabWidget() self.tab1 = QWidget() self.tab2 = QWidget() self.tabs.resize(300,200) # Add tabs self.tabs.addTab(self.tab1,"Tab 1") self.tabs.addTab(self.tab2,"Tab 2") # Create first tab self.tab1.layout = QVBoxLayout(self) self.pushButton1 = QPushButton("PyQt5 button") self.pushButton1.clicked.connect(self.ON_PRESS) self.textbox = QLineEdit(self) self.tab1.layout.addWidget(self.textbox ) self.tab1.layout.addWidget(self.pushButton1) self.tab1.setLayout(self.tab1.layout) #Create Textbox inputs # Add tabs to widget self.layout.addWidget(self.tabs) self.setLayout(self.layout) def using_q_thread(self): app = Example() thread = AThread() thread.start() sys.exit(app.exec_()) def ON_PRESS(self): ###Here is the Issue try: self.using_q_thread() except: print ("Error: unable to start thread") ###Drag and Drop files to directory if __name__ == '__main__': app = QApplication(sys.argv) ex = Example() ex.show() Hoping I am asking this correctly, but whenever using QThread there appears to be a bit of a hiccup. the first attempt to access the threaded function causes the try statement to fail, but then it immediately works. Im just curious if this is part of the functionality or if there is any issue with my code.
tagged with: python-3.6
has answer: http://stackoverflow.com/a/52046056
score: 0
tagged with: pyqt

http://stackoverflow.com/a/51998635
type: Answer
upvote count: 1
has comment: http://stackoverflow.com/comment/90963718
score: 1
accepted answer of: http://stackoverflow.com/q/51998504
downvote count: 0
answers question: http://stackoverflow.com/q/51998504
has body: You can import matplotlib.pyplot and use the show function: from IPython.core.display import display import matplotlib.pyplot as plt ... for df in list_df: df.plot() plt.show() display(df)
type: AcceptedAnswer

http://stackoverflow.com/comment/91147770
type: Comment
comment on: http://stackoverflow.com/a/52085516
has text: numpy.randon.seed(10) should be sufficient. Two other thoughts, are you scaling your input data? Non-scaled input data can result in zero or NaN division in certain circumstances. see: https://machinelearningmastery.com/how-to-scale-data-for-long-short-term-memory-networks-in-python/. Secondly, Are you spliting your training/testing data the same way each time? I would test it on the same train/test split to see how consistent it is. May help narrow it down.
score: 0
type: AnswerComment

http://stackoverflow.com/comment/91073355
type: Comment
comment on: http://stackoverflow.com/a/52061407
has text: @Codevan Then shouldn't the roots be last, as if the tree is being traversed horizontally, then the roots will be the last to be counted?
score: 0
type: AnswerComment

http://stackoverflow.com/a/52025996
score: 2
type: AcceptedAnswer
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/91002596
upvote count: 2
has body: You have one colon too many in your connection string. If you also need to provide credentials, prepend them with @ (docs): engine = create_engine("postgresql://user:password@127.0.0.1:5432/lecture03")
accepted answer of: http://stackoverflow.com/q/52025871
answers question: http://stackoverflow.com/q/52025871

http://stackoverflow.com/comment/90931443
type: Comment
comment on: http://stackoverflow.com/a/51976383
has text: 2. The difficulty I think I am having is with how to define a many-to-one or a many-to-many RNN in Keras. I have seen diagrams where each time step of Y is evaluated, and then the activation is passed to the next time step. I want to be sure I am setting this up correctly.
score: 0
type: AnswerComment

http://stackoverflow.com/comment/91170628
type: Comment
has text: @JaskaranSinghPuri - Maybe some whitesapces? What is `print (A.columns.tolist())` and `print (B.columns.tolist())` with real data?
score: 0
comment on: http://stackoverflow.com/q/52109791
type: QuestionComment

http://stackoverflow.com/q/51991001
tagged with: python
has body: Please go easy on me as I'm still new to numpy and trying to wrap my head around some numpy concepts and I have this question: The problem I have a numpy array called boxes with boxes.shape = (2, 200, 4). There are 2 frames, with 200 boxes each, each box has 4 coordinate points. I have a boolean array called to_keep with to_keep.shape = (2, 200). For each frame, there is 200d array telling whether to keep that box or not. I want to filter out boxes and keep only those where to_keep is true. My resulting shape should be filtered_boxes.shape = (2, N, 4) The problem is that for the first frame, 25 boxes may be valid. But for second frame 100 boxes may be valid. How do I effectively filter out this structure in numpy?
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/90932333
has comment: http://stackoverflow.com/comment/90942282
has title: numpy boolean indexing of a matrix
has comment: http://stackoverflow.com/comment/90932040
has comment: http://stackoverflow.com/comment/90932605
score: 0
answer count: 1
has answer: http://stackoverflow.com/a/51994976
type: UnansweredQuestion

http://stackoverflow.com/comment/90886921
score: 0
has text: okay, sounds good :(
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51968221

http://stackoverflow.com/q/51995270
has comment: http://stackoverflow.com/comment/90940313
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90945207
type: Question
has comment: http://stackoverflow.com/comment/90940310
answer count: 2
has title: Python lookup dict and nested values in dict_keys and swap value
downvote count: 0
has answer: http://stackoverflow.com/a/51995440
has answer: http://stackoverflow.com/a/51995514
favorite count: 0
possible better answer: http://stackoverflow.com/a/51995440
tagged with: python
tagged with: dictionary
has body: I'm attempting to swap values in dictionary(dic_map) with values from dictionary(B), where dic_map[key] = B. to give me a new dict with the values from B e.g dic_map = { 'Name': 'name', 'Id': 'guid', 'address':{ 'address1': 'road', 'address2': 'road_nr', 'address3': 'zipcode', 'address4': 'city' }, 'tax': True, 'isValid': False, 'specific': 1, 'credit': 200 } B = { 'name': 'Michael Jackson', 'guid': '032-567-781', 'road': 'The greatest Dr', 'road_nr': 42, 'zipcode': 90210, 'city': 'Hollywood', 'country': 'USA' } And the final dict desired_result = { 'Name': 'Michael Jackson', 'Id': '032-567-781', 'address':{ 'address1': 'The greatest Dr', 'address2': 42, 'address3': 90210, 'address4': 'Hollywood', }, 'tax': True, 'isValid': False, 'specific': 1, 'credit': 200 } This is what I have so far def swap_values(dic_values, dic_map): d = {} for k1 in dic_values.keys(): for k2 in dic_map.keys(): if k1 == dic_map[k2]: d[k2]=dic_values[k1] else: d[k2]=dic_map[k2] return d There are 2 things that is not working as far as I can tell, 1. my values gets overwritten by the else statement, and 2. the nested dict is never evaluated. Any help would be appreciated.
tagged with: lookup
score: 1
accepted answer: http://stackoverflow.com/a/51995514
upvote count: 1

http://stackoverflow.com/comment/90912318
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51956657
has text: Hi bendaf, if you reply to people, use the `@` sign to notify them. Example: @Stein (do the same for mr snake if you think he would like to see the reply)
score: 0

http://stackoverflow.com/comment/90970178
has text: Can you show your results for when you rescale your target values? Something like `y /= y.max()`
comment on: http://stackoverflow.com/q/51994563
score: 1
type: QuestionComment
type: Comment

http://stackoverflow.com/q/52108009
has answer: http://stackoverflow.com/a/52108322
downvote count: 0
score: 1
has answer: http://stackoverflow.com/a/52108343
has body: When trying to download a file from a post on 4chan (through BASC_py4chan) and downloading it through wget, wget will download the file even if I make a if statement saying not to download it if the filename is the same as a filename in the current directory? Is this a wget-python problem or did I make a mistake? if 'ylyl' in subject or 'YLYL' in subject: for post in thread.all_posts: if post.has_file: print(post.filename) for filename in os.listdir(cwd): print(filename) if filename != post.filename: url = post.file_url wget.download(url) time.sleep(1.03)
type: Question
answer count: 2
has title: How to make the wget python module not download duplicates?
tagged with: wget
possible better answer: http://stackoverflow.com/a/52108322
upvote count: 1
favorite count: 0
accepted answer: http://stackoverflow.com/a/52108343
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/q/52101013
tagged with: python
has body: I suddenly got a lot of errors when importing libraries that i didn't have in the same script (exactly the same script) a few hours ago. This is what I import: import pandas as pd pd.core.common.is_list_like = pd.api.types.is_list_like from pandas_datareader import data as web import datetime import fix_yahoo_finance as yf import plotly from plotly import figure_factory as ff import os And this is the huge amount of errors: sh: module: line 1: syntax error: unexpected end of file sh: error importing function definition for `module' sh: switchml: line 1: syntax error: unexpected end of file sh: error importing function definition for `switchml' sh: scl: line 1: syntax error: unexpected end of file sh: error importing function definition for `scl' As I said, I didn't get any of those errors earlier, and can't find anything to fix it over the internet. I'm using the last version of atom editor on fedora28. Thanks for reading, guys! :)
answer count: 0
has comment: http://stackoverflow.com/comment/91153241
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91153942
has comment: http://stackoverflow.com/comment/91153086
tagged with: import
has title: Huge lots of errors when importing libraries
type: Question
score: 0
has comment: http://stackoverflow.com/comment/91153408

http://stackoverflow.com/q/52049009
tagged with: pandas
tagged with: datetime
answer count: 1
has body: I have a DataFrame with a DatetimeIndex, and I want to create a new column that is an aggregation of another column, aggregated by the Datetime at a slower frequency. For example, hourly values and the daily mean of the day they're a part of: [index] A A_daily_mean 2018-08-01 00:00:00 6 7.5 2018-08-02 01:00:00 7 7.5 2018-08-03 02:00:00 8 7.5 2018-08-04 03:00:00 9 7.5 Is there a one-liner for this? This is super easy for other groupby aggregations (on non-datetimes): df['groupby_mean'] = df.groupby([col1, col2]).mean() but grouping on the date of the DatetimeIndex fails miserably: df['mean_of_resampled'] = df.groupby(df.index.date).mean() or alternatively df['mean_of_resampled'] = df.resample('1d').mean() which both give: [index] A A_daily_mean 2018-08-01 00:00:00 6 7.5 2018-08-01 01:00:00 7 NaN 2018-08-01 02:00:00 8 NaN 2018-08-01 03:00:00 9 NaN I know I can add back the values by doing a merge or join, but I'm wondering if I'm missing some better, happier way.
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/52049123
type: Question
has comment: http://stackoverflow.com/comment/91048958
has title: For a DataFrame with a DatetimeIndex, how do I add a new column that is an aggregation of the resampled DatetimeIndex?
score: 0

http://stackoverflow.com/comment/91046590
type: Comment
has text: It seems this solution sometimes raises another exception when handling `asyncio.TimeoutError`, saying that `ignore_exc` is missing an argument `ctx` with traceback to the line `old_handler_fn(ctx)` withiin `ignore_exc` itself (so some kind of unexpected recursion).
type: AnswerComment
comment on: http://stackoverflow.com/a/52021212
score: 0

http://stackoverflow.com/a/52010492
type: AcceptedAnswer
downvote count: 0
has body: It's very simple if you analyze the website and it's working in the backend via chrome developer tools. Before diving into scraping you need to know about ajax requests in the web. Most websites use ajax requests, therefore, everything is loaded dynamically. Steps to follow: Open the website in a new tab in chrome Open the developer console of chrome Go to Network tab and refresh the page. You can see the calls being by the website as it is loaded dynamically. For the website - http://www.bmfbovespa.com.br/pt_br/servicos/market-data/cotacoes/mercado-de-derivativos/?symbol=DI1 ,here's the image. You can see the DL1 API being called. Go to the headers and see the url. Now you get to know the url. Therefore, it's very easy to get the data using python. Here's the code. import requests, json text = reuqests.get("http://cotacao.b3.com.br/mds/api/v1/DerivativeQuotation/DI1").text data = json.loads(text) print(data['Scty']) The output of the above program will be as follows [{'SctyQtn': {'avrgPric': 7.7862, 'bottomLmtPric': 7.01, 'curPrc': 7.78, 'maxPric': 7.79, 'minPric': 7.74, 'opngPric': 7.74, 'prvsDayAdjstmntPric': 7.684, 'topLmtPric': 8.525}, 'asset': {'AsstSummry': {'grssAmt': 111008714.5, 'mtrtyCode': '2019-06-03', 'opnCtrcts': 36655, 'tradQty': 141, 'traddCtrctsQty': 1175}, 'code': 'DI1'}, 'buyOffer': {'price': 7.64}, 'mkt': {'cd': 'FUT'}, 'sellOffer': {'price': 7.675}, 'symb': 'DI1M19'}, {'SctyQtn': {'avrgPric': 8.1758, 'bottomLmtPric': 7.49, 'curPrc': 8.19, 'maxPric': 8.3, 'minPric': 8.13, 'opngPric': 8.21, 'prvsDayAdjstmntPric': 8.237, 'topLmtPric': 9.2}, 'asset': {'AsstSummry': {'grssAmt': 417475320.0, 'mtrtyCode': '2019-10-01', 'opnCtrcts': 769684, 'tradQty': 167, 'traddCtrctsQty': 4550}, 'code': 'DI1'}, 'buyOffer': {'price': 8.16}, 'mkt': {'cd': 'FUT'}, 'sellOffer': {'price': 8.19}, 'symb': 'DI1V19'}, {'SctyQtn': {'avrgPric': 6.6549, 'bottomLmtPric': 6.125, 'curPrc': 6.7, 'maxPric': 6.71, 'minPric': 6.645, 'opngPric': 6.68, 'prvsDayAdjstmntPric': 6.669, 'topL…
has comment: http://stackoverflow.com/comment/90976853
type: Answer
score: 4
accepted answer of: http://stackoverflow.com/q/52010016
answers question: http://stackoverflow.com/q/52010016
upvote count: 4

http://stackoverflow.com/q/52027874
accepted answer: http://stackoverflow.com/a/52031761
score: -1
has body: I am attempting to make a game in python with the turtle module, I have the square moving towards the player (the circle) and the aim is for the circle to jump over the square and not get hit. The player can jump by pressing the spacebar, but every time you hit the space bar to jump the player jumps, but the square stops moving and you are unable to jump over. here is my code: import turtle import time wn = turtle.Screen() wn.bgcolor("white") wn.title("dinosaur run") wn.tracer(1,20) floor = turtle.Turtle() floor.fd(370) floor.bk(370*2) floor.ht() player = turtle.Turtle() player.shape("circle") player.penup() player.setpos(-370,14) def jump(): player.lt(90) player.fd(40) time.sleep(0.5) player.bk(40) player.rt(90) turtle.listen() turtle.onkey(jump, "space") class cactus(turtle.Turtle): turtle.shape("square") turtle.penup() turtle.speed(0) turtle.setpos(370,14) cactusspeed = 2 while True: x = turtle.xcor() x -= cactusspeed turtle.setx(x) Thanks a lot, all ideas welcome, I've tried wn.update() at the end
type: Question
has answer: http://stackoverflow.com/a/52031761
answer count: 1
downvote count: 1
favorite count: 0
has title: players not moving simultaneously
tagged with: python
upvote count: 0
tagged with: turtle-graphics
type: AnsweredQuestion

http://stackoverflow.com/comment/91077222
has text: Thank you for this example which demonstrates how to handle GET methods. Another part of the API should be able to handle the other http methods; how would we configure this to handle POST or DELETE methods?
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52023675

http://stackoverflow.com/comment/90892100
has text: https://learn.microsoft.com/en-us/dotnet/framework/wcf/feature-details/how-to-serialize-and-deserialize-json-data
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51970817
score: 0

http://stackoverflow.com/q/51991966
answer count: 3
tagged with: pandas
favorite count: 0
tagged with: python-3.x
upvote count: 2
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90933575
tagged with: python
has answer: http://stackoverflow.com/a/51992247
has comment: http://stackoverflow.com/comment/90933616
has answer: http://stackoverflow.com/a/51992041
score: 2
has body: My dataframe: df_all_xml_mfiles_tgther file_names searching_for everything 0 a.txt where Dave Ran Away. Where is Dave? 1 a.txt candy mmmm, candy 2 b.txt time We are looking for the book. 3 b.txt where where the red fern grows My problem: I am trying to filter for records that contain the words found in my search criteria. I need to go through 1 record at a time and return the actual record instead of just the word true. What I have tried: search_content_array = ['where', 'candy', 'time'] file_names_only = ['a.txt', 'b.txt'] for cc in range(0, len(file_names_only), 1): for bb in range(0, len(search_content_array), 1): stuff = `df_all_xml_mfiles_tgther[cc:cc+1].everything.str.contains(search_content_array[bb], flags=re.IGNORECASE, na=False, regex=True)` if not regex_stuff.empty: regex_stuff_new = pd.DataFrame([regex_stuff.rename(None)]) regex_stuff_new.columns = ['everything'] regex_stuff_new['searched_for_found'] = search_content_array[bb] regex_stuff_new['file_names'] = file_names_only[cc] regex_stuff_new = regex_stuff_new'file_names', 'searched_for_found', 'everything' ##This rearranges the columns df_regex_test = df_regex_test.append(regex_stuff_new, ignore_index=True, sort=False) The results I am getting are this: file_names searched_for_found everything 0 a.txt where True 1 a.txt candy True 2 b.txt where True The results I want are this: file_names searched_for_found everything 0 a.txt where Dave Ran Away. Where is Dave? 1 a.txt candy mmmm, candy 3 b.txt where where the red fern grows How do I get the actual value for returned results instead of just true/false?
type: Question
has comment: http://stackoverflow.com/comment/90933657
downvote count: 0
has comment: http://stackoverflow.com/comment/90933629
has answer: http://stackoverflow.com/a/51992322
has comment: http://stackoverflow.com/comment/90933610
has title: Pandas Filtering: Returning True/False vs the Actual Value

http://stackoverflow.com/a/52005493
accepted answer of: http://stackoverflow.com/q/52005234
has body: Must definitely ask clever guys at https://codereview.stackexchange.com/, but as a quick fix it appears you can just map() your transformation fucntion over a list of dictionaries as below: def clean_text(value: str)-&gt; str: # ... return value.replace("bad", "good") def clean_dict(d: dict): return {k:clean_text(v) for k,v in d.items()} json_data = [ {"key1":"some bad", "key2":"bad things", "key3":"extra bad"}, {"key1":"more bad stuff", "key2":"wow, so much bad", "key3":"who dis?"}, # a few million more dictionaries {"key1":"so much bad stuff", "key2":"the bad", "key3":"the more bad"}, ] x = list(map(clean_dict, json_data)) A thing that gets left out is your total counter, but it never seems to leave the get_json_data_clean() anyways. Not sure why @Daniel Gale proposed filter() as you are not throughing any values away, just transforming them.
has comment: http://stackoverflow.com/comment/90961108
upvote count: 2
answers question: http://stackoverflow.com/q/52005234
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/90960942
downvote count: 0
type: Answer
score: 2

http://stackoverflow.com/a/52012044
has comment: http://stackoverflow.com/comment/90990743
has comment: http://stackoverflow.com/comment/90975185
downvote count: 0
score: 1
accepted answer of: http://stackoverflow.com/q/52011244
answers question: http://stackoverflow.com/q/52011244
upvote count: 1
type: AcceptedAnswer
has body: As described by @abarnert in a comment to the question, the problem was that the library used for written the unicode strings didn't know that utf-8 should be used and therefor encoded the strings wrong. After adding charset='utf8mb4' as parameter to the mysql connection the string get written correctly in the intended encoding. All I had to change was conn = MySQLdb.connect(host, user, pass, db, port) to conn = MySQLdb.connect(host, user, pass, db, port, charset='utf8mb4') and after that my approach described in the question worked flawlessly. edit: after declaring the charset='utf8mb4' parameter on the connection object it is no longer necessary to encode the strings, as that gets now already successfully done by the mysqlclient library.
type: Answer
has comment: http://stackoverflow.com/comment/90986595

http://stackoverflow.com/q/52005877
has body: I'm using Authorization Backends in order to use my own database with username and password (our own encrypted techniques). Now when i run the sever, its giving me login button. using which i get logged in successfully. And in return i'm able to get user. Below is the code for that. from django.contrib.auth.models import User from workforce.models import GlobalUsers from rest_framework.response import Response from workforce.globalapiviews import hash_password class EmailAuthBackend(object): def authenticate(self, request, username=None, password=None): try: hashedpassword = hash_password(password) user = GlobalUsers.objects.get(username=username, password=hashedpassword) print(hashedpassword) if user: return user else: return None except GlobalUsers.DoesNotExist: return Response(status=status.HTTP_204_NO_CONTENT) def get_user(self, wf_user_id): try: print(wf_user_id) return GlobalUsers.objects.get(pk=wf_user_id) except GlobalUsers.DoesNotExist: print(wf_user_id) return None When comes to HTML, is always displaying 'LOGIN' button even in case of successful login. Observed that, user.is_authenticated is always returning false. Can any one please suggest me what i'm doing wrong. Thanks in Advance.
answer count: 2
has comment: http://stackoverflow.com/comment/90961798
has answer: http://stackoverflow.com/a/52006273
tagged with: django-rest-framework
has comment: http://stackoverflow.com/comment/90962325
has answer: http://stackoverflow.com/a/52006103
has comment: http://stackoverflow.com/comment/90961787
has comment: http://stackoverflow.com/comment/90961832
has title: Django Authorization Backends + always returning 'user.is_authenitcated' false
tagged with: python
has comment: http://stackoverflow.com/comment/90961713
has comment: http://stackoverflow.com/comment/90961982
has comment: http://stackoverflow.com/comment/90961900
has comment: http://stackoverflow.com/comment/90961860
score: 0
type: UnansweredQuestion
tagged with: django
type: Question
has comment: http://stackoverflow.com/comment/90962274
has comment: http://stackoverflow.com/comment/90961585

http://stackoverflow.com/comment/91011131
score: 0
type: AnswerComment
type: Comment
has text: @argo I ran this code and I didn't get a traceback error. I did, however, grab ALL the links even ones that didn't start with `/401k/`
comment on: http://stackoverflow.com/a/52023496

http://stackoverflow.com/a/52050334
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52050018
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/52050018
has body: data = '2018-03-10, 354687-56987-314, 2018123-02-10-2019, 10-20-20232316' re.findall(r'[^, ]*\d{5,}[^,]*',data) Out[847]: ['354687-56987-314', '2018123-02-10-2019', '10-20-20232316'] EDIT from the examples given the regex \S*\d{5,}[^,\s]* can be used
upvote count: 2
type: Answer
score: 2

http://stackoverflow.com/a/61442389
answers question: http://stackoverflow.com/q/52031952
has body: If you're using a bot, you must prefix your Authorization header token with 'Bot' i.e. headers = { 'authorization' : 'Bot asdhgaisudg7asd', } See https://github.com/discord/discord-api-docs/issues/602
upvote count: 17
score: 17
has comment: http://stackoverflow.com/comment/132717278
downvote count: 0
has comment: http://stackoverflow.com/comment/130806592
type: Answer

http://stackoverflow.com/a/51976456
answers question: http://stackoverflow.com/q/51970168
has body: You don't really need an RDS, just invoke your lambda synchronously from the browser. So Upload file to S3, using a randomized file name Invoke your lambda synchronously, passing it the file name Have your lambda read the file, convert it, and respond with either the file itself (binary responses aren't trivial), or a path to the converted file in S3.
type: Answer
has comment: http://stackoverflow.com/comment/93775576
score: 0

http://stackoverflow.com/comment/90943890
type: QuestionComment
comment on: http://stackoverflow.com/q/51997053
type: Comment
score: 1
has text: `a` is a list. `y=a` reassigns `y` to that list. It is no longer the `np.matrix` you started with.

http://stackoverflow.com/comment/91009937
type: QuestionComment
has text: For this function confirm is pointless. But I have a huge class which confirm will store in another file, if I solve this minimize program, I can do the following things in my big program: In Second class, I will use to trace all the windows user activity history, therefore, this part I will just use to get XXX text from a file dialog directory, which i already know the way to do that,just need to get from another class than should be no problem for me. If is pointless, I would not create this to help me solve bigger problem in my program...hope you understand.thank you
comment on: http://stackoverflow.com/q/52029320
score: 0
type: Comment

http://stackoverflow.com/comment/134902698
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52107646
score: 1
has text: Excellent response ! Lot of my questions that I had in my mind got cleared with this one detailed response. Thanks !

http://stackoverflow.com/q/52087336
upvote count: 4
answer count: 1
has title: Minimizing Least Squares with Algebraic Constraints and Bounds
downvote count: 0
favorite count: 0
has body: I'm attempting to minimize a sum of least squares based on some vector summations. Briefly, I'm creating an equation that takes ideal vectors, weights them with a determined coefficient, and then sums the weighted vectors. The sum of least squares comes in once this sum is compared to the actual vector measurements found for some observation. To give an example: # Observation A has the following measurements: A = [0, 4.1, 5.6, 8.9, 4.3] # How similar is A to ideal groups identified by the following: group1 = [1, 3, 5, 10, 3] group2 = [6, 3, 2, 1, 10] group3 = [3, 3, 4, 2, 1] # Let y be the predicted measurement for A with coefficients s1, s2, and s3: y = s1 * group1 + s2 * group2 + s3 * group3 # y will be some vector of length 5, similar to A # Now find the sum of least squares between y and A sum((y_i - A_i)** 2 for y_i in y for A_i in A) Necessary bounds and constraints 0 &lt;= s1, s2, s3 &lt;= 1 s1 + s2 + s3 = 1 y = s1 * group1 + s2 * group2 + s3 * group3 This sum of least squares for y and A is what I'd like to minimize to get the coefficients s1, s2, s3, but I'm having difficulties identifying what the proper choice in scipy.optimize might be. It doesn't seem like the functions there for minimizing sum of least squares can handle algebraic variable constraints. The data I'm working with is thousands of observations with these vectorized measurements. Any thoughts or ideas would be greatly appreciated!
tagged with: python-3.x
has answer: http://stackoverflow.com/a/52087719
tagged with: python
type: AnsweredQuestion
tagged with: mathematical-optimization
accepted answer: http://stackoverflow.com/a/52087719
type: Question
score: 4

http://stackoverflow.com/comment/90915396
type: AnswerComment
comment on: http://stackoverflow.com/a/51982517
type: Comment
score: 1
has text: Use a negative lookbehind: [`(?<![AaÄäEe])ue`](https://regex101.com/r/liazk6/1) instead.

http://stackoverflow.com/q/51963626
tagged with: eclipse
has comment: http://stackoverflow.com/comment/111759989
downvote count: 0
favorite count: 0
has title: Running a Python script with custom module import from Java
type: UnansweredQuestion
tagged with: python
tagged with: module
answer count: 0
tagged with: spacy
upvote count: 3
tagged with: java
type: Question
has body: I want to trigger the execution of some commands from a python module from Java. My script is executed without error messages, but it has no effect. The code I'm using from Java is as follows: ProcessBuilder pb = new ProcessBuilder("python", "nerDemoTP/python/spacy_test.py"); pb.redirectOutput(Redirect.INHERIT); Process p; try { p = pb.start(); p.waitFor(); } catch (IOException e1) { ... } It works if my .py file contains only print('hello world'), then I see it in the Eclipse console. But what my python script is supposed to do: from SpacyNER import SpacyNERExtractor ner_extractor = SpacyNERExtractor('medium', 'sentences_nyt_200.txt') annotated_df, entities_dict = ner_extractor.generate_extractions() ner_extractor.store_predictions('test.csv') print('spacy extractions done!') And my SpacyNER module is defined as follows: import pandas as pd import numpy as np import spacy import en_core_web_md import en_core_web_lg import operator import time import re class SpacyNERExtractor: def __init__(self, model, text_file): if model == 'medium': self.spacy_model = en_core_web_md.load() else: self.spacy_model = en_core_web_lg.load() self.sent_df = pd.read_csv(text_file, sep='\n', header=None, error_bad_lines = False) self.sent_df.columns=['sentence'] def set_new_sent_df(self, df_new): self.sent_df = df_new def store_predictions(self, file_name): self.df_predictions_spacy.to_csv(file_name,sep="#", index=False) ... It has to do something with the import of the custom module, but I don't know how to deal with this problem. Also when I execute the script from the command line, i.e. python3.6 spacy_test.py, it works. Any help is appreciated!
score: 3

http://stackoverflow.com/q/52069303
answer count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/91088608
has body: I can't figure out why this nested loop MPI won't stop (i.e. deadlock). I know that most MPI users are based on C++ / C / Fortran, and I'm using Python's mpi4py package here, but I suspect that it's not an issue of the programming language but my misunderstanding of MPI itself. Code #!/usr/bin/env python3 # simple_mpi_run.py from mpi4py import MPI import numpy as np comm = MPI.COMM_WORLD rank = comm.Get_rank() size = comm.Get_size() root_ = 0 # Define some tags for MPI TAG_BLOCK_IDX = 1 num_big_blocks = 5 for big_block_idx in np.arange(num_big_blocks): for worker_idx in (1+np.arange(size-1)): if rank==root_: # send to workers comm.send(big_block_idx, dest = worker_idx, tag = TAG_BLOCK_IDX) print("This is big block", big_block_idx, "and sending to worker rank", worker_idx) else: # receive from root_ local_block_idx = comm.recv(source=root_, tag=TAG_BLOCK_IDX) print("This is rank", rank, "on big block", local_block_idx) Batch job script The SGE batch job script that runs the above. For illustration purposes, I use -np 3 to allocate only three processes to the mpirun. In the actual application, I'll use far more than just three. #!/bin/bash # batch_job.sh #$ -S /bin/bash #$ -pe mpi 3 #$ -cwd #$ -e error.log #$ -o stdout.log #$ -R y MPIPATH=/usr/lib64/openmpi/bin/ PYTHONPATH=$PYTHONPATH:/usr/local/lib/python3.6/site-packages/:/usr/bin/ export PYTHONPATH PATH=$PATH:$MPIPATH export PATH LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/usr/lib/:/usr/lib64/ export LD_LIBRARY_PATH mpirun -v -np 3 python3 simple_mpi_run.py Output From stdout.log, I see the following output after running qsub batch_job.sh: This is big block 0 and sending to worker rank 1 This is rank 1 on big block 0 This is big block 0 and sending to worker rank 2 This is big block 1 and sending to worker rank 1 This is rank 1 on big block 1 This is big block 1 and sending to worker rank 2 This is big block 2 and sending to worker rank 1 This is rank 1 on big block 2 This is big block 2 and sending to worker rank 2 This is …
tagged with: parallel-processing
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91088614
has comment: http://stackoverflow.com/comment/91088669
type: Question
has comment: http://stackoverflow.com/comment/91088546
has answer: http://stackoverflow.com/a/52069707
accepted answer: http://stackoverflow.com/a/52069707
score: 0
tagged with: mpi
has title: Deadlock in nested loop MPI (Python mpi4py)

http://stackoverflow.com/comment/91160600
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52104577
has text: Yes, it works like previous solution but much shorter due to use of lambda expression, thank you very much.

http://stackoverflow.com/a/51997532
score: 1
has body: There are some ways to accelerate your Numpy code by getting ride of for loops, like using Numpy's ufuncs (+, -, *, **, &lt;...), aggregations (sum, max, min, mean...), broadcasting, masking, fancy indexing. The code below may give you some tips: dist = np.expand_dims(np.array([76, 150, 240]), axis=0) image[np.where(np.sum((image-dist)**2, axis=2) &lt; 12000)]=255
downvote count: 0
answers question: http://stackoverflow.com/q/51997022
type: Answer
has comment: http://stackoverflow.com/comment/90950904
upvote count: 1

http://stackoverflow.com/comment/90974619
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/52009769
score: 0
has text: Better use docker

http://stackoverflow.com/q/52024175
upvote count: 0
tagged with: pivot-table
type: UnansweredQuestion
downvote count: 1
type: Question
has title: python - pandas: output html table with cells that span several rows and columns
tagged with: dataframe
score: -1
has answer: http://stackoverflow.com/a/52024364
answer count: 1
favorite count: 0
tagged with: pandas
tagged with: grouping
tagged with: python
has body: Using pandas, how can I get an html table that looks like the attachment? (where empty cells are numeric values) table example Thanks a lot!

http://stackoverflow.com/a/52022510
upvote count: 6
answers question: http://stackoverflow.com/q/52022499
downvote count: 0
type: Answer
score: 6
has body: This will return the length of the longest list: max(map(len, values))

http://stackoverflow.com/comment/91144806
type: QuestionComment
score: 3
comment on: http://stackoverflow.com/q/52097306
has text: Possible duplicate of [How to change the datetime format in pandas](https://stackoverflow.com/questions/38067704/how-to-change-the-datetime-format-in-pandas)
type: Comment

http://stackoverflow.com/q/52026665
has answer: http://stackoverflow.com/a/52029010
has comment: http://stackoverflow.com/comment/91003663
type: UnansweredQuestion
tagged with: django
has comment: http://stackoverflow.com/comment/91003562
has comment: http://stackoverflow.com/comment/91004162
type: Question
has comment: http://stackoverflow.com/comment/91004277
tagged with: database
has body: This is the code that I have in my models.py. I'm trying to develop a small website using only the Django Admin. from django.db import models # Create your models here. from django.contrib.auth.models import User from django.db import models from django.core.mail import EmailMessage # Create your models here. class Project(models.Model): STATUS_CHOICE = ( ('Project Manager', 'Project Manager'), ('Technician', 'Technician'), ('Tester', 'Tester') ) STATUS_CHOICE_1 = ( ('Work Assigned', 'Work Assigned'), ('Work in Progress', 'Work in Progress'), ('Testing', 'Testing'), ('Completed', 'Completed') ) Project_Name = models.CharField(max_length=100) Project_Description = models.CharField(max_length=100) Admin_Name = models.CharField(max_length=100) Admin_Mail_ID = models.EmailField(max_length=50) Project_Manager_1 = models.ForeignKey(User, on_delete=models.CASCADE, related_name='Project_Manager_1_users') Project_Manager_1_Mail_ID = models.EmailField(max_length=50) Project_Manager_2 = models.ForeignKey(User, on_delete=models.CASCADE, related_name='Project_Manager_2_users') Project_Manager_2_Mail_ID = models.EmailField(max_length=50, blank=True, null=True) Technician_1 = models.ForeignKey(User, on_delete=models.CASCADE, related_name='Technician_1_users') Technician_1_Mail_ID = models.EmailField(max_length=50) Technician_2 = models.ForeignKey(User, on_delete=models.CASCADE, related_name='Technician_2_users') Technician_2_Mail_ID = models.EmailField(max_length=50, blank=True, null=True) Technician_3 = models.ForeignKey(User, on_delete=models.CASCADE, related_name='Technician_3_users') Technician_3_Mail_ID = models.EmailField(max_length=50, blank=True, null=True) Tester_1 = models.ForeignKey(User, on_delete=models.CASCADE, related_name='Tester_1_users') Tester_1_Mail_ID = models.EmailField(max_length=50, default='Example@gmail.com') Additional_User_1 = models.ForeignKey(User, on_delete=models.CASCADE, related_name='Ad_1_users') Additional_User_1_Type = models.CharField(max_lengt…
has comment: http://stackoverflow.com/comment/91003894
answer count: 1
score: 0
has title: Django Admin: Email Id Autofill and Related_name= Issue
tagged with: python
has comment: http://stackoverflow.com/comment/91004050
has comment: http://stackoverflow.com/comment/91003920
has comment: http://stackoverflow.com/comment/91003612

querying
type: Tag
tags question: http://stackoverflow.com/q/51990428
tag name: querying

http://stackoverflow.com/a/52070154
answers question: http://stackoverflow.com/q/52070098
has body: I think it is with obj which is passed as an argument for the Class Book. It is supposed to be object(Lower case) in Python 2.x. In Python 3.x, You can just leave it out!
score: 0
upvote count: 1
downvote count: 1
type: Answer

http://stackoverflow.com/comment/90961182
type: Comment
type: QuestionComment
score: 1
has text: Welcome tris. Can you elaborate a bit on what you're trying to accomplish? Perhaps an approach other than inner classes would be more appropriate.
comment on: http://stackoverflow.com/q/52005653

http://stackoverflow.com/comment/117263107
type: AnswerComment
type: Comment
has text: OP is aware of `decode_png`, he mentioned it in the question. The question is "why does `decode_jpeg` works?".
comment on: http://stackoverflow.com/a/66328524
score: 0

http://stackoverflow.com/a/52003988
downvote count: 0
type: Answer
has body: First read this : https://dirtsimple.org/2004/12/python-is-not-java.html and then this: https://docs.python.org/3/tutorial/classes.html Then rewrite your code the Python way: # employee.py (module names should be all lower) class Employee(object): # inheriting from `object` is only useful in python2 # but doesn't break anything in python3 def __init__(self, name="Brian", num=4000): self.name = name self.num = num def __str__(self): # this will be automagically called when trying # to make a string out of an Employee return "Name: {self.name}\nNum: {self.num}".format(self=self) # and that's all. You don't need private attributes nor # accessors, Python has a strong support for computed # attributes so you can turn plain attributes into # computed ones later if needed (without breaking # the client code of course). and the test code # test.py from employee import Employee def main(): # instanciating a class is done by calling it jane = Employee("Jane", 40000) brian = Employee() print(jane) print(brian) if __name__ == "__main__": main() I strongly suggest you at least follow the full Python tutorial before trying to write PHP or Java code in Python, it'll save everyone's time.
score: 1
answers question: http://stackoverflow.com/q/52003643
upvote count: 1

http://stackoverflow.com/q/51964325
has comment: http://stackoverflow.com/comment/90878821
has answer: http://stackoverflow.com/a/51964494
has comment: http://stackoverflow.com/comment/90879130
score: 0
answer count: 1
tagged with: python
accepted answer: http://stackoverflow.com/a/51964494
has title: Python Quiz using Tkinter
tagged with: tkinter
linked to: http://stackoverflow.com/q/48045401
type: AnsweredQuestion
has body: For a project, I need to create an educational program and I have chosen a quiz. I am having trouble making the program recognise that flag has been incremented to 3. Is it an issue with how I am incrementing flag or something else?. I am not too familiar with python (or tkinter for that matter) so please don't be too harsh. from tkinter import * from tkinter import ttk root = Tk() notebook = ttk.Notebook(root) frame1 = ttk.Frame(notebook) frame2 = ttk.Frame(notebook) frame3 = ttk.Frame(notebook) notebook.add(frame1, text="Q1") notebook.add(frame2, text="Q2") notebook.add(frame3, text="Q3") def displayscore(total): score = Tk() score.geometry("760x450") score.title("Score") score.configure(background="#000138") Label(score, text="Your score is:", fg="Black", font="Arial 36").pack() Label(score, textvariable=total, fg="Black", font="Arial 36").pack() def flagset(): flag.set(flag.get() + 1) if flag == 3: displayscore(total) def totalset(): total.set(total.get() + 1) def main(): #Question 1 def correct1(): clear1() totalset() flagset() def clear1(): list = frame1.grid_slaves() for l in list: l.destroy() Label(frame1, text="Where is the '7' in 1704?").grid(row=0) flagset() Label(frame1, text="Where is the '7' in 1704?").grid(row=0) Button(frame1, text="In the Thousands", command=clear1, width=15).grid(row=1, sticky=W) Button(frame1, text="In the Hundreds", command=correct1, width=15).grid(row=2, sticky=W) Button(frame1, text="In the Tens", command=clear1, width=15).grid(row=3, sticky=W) Button(frame1, text="In the Ones", command=clear1, width=15).grid(row=4, sticky=W) #Question2 def correct2(): clear2() totalset() flagset() def clear2(): list = frame2.grid_slaves() for l in list: l.destroy() Label(frame2, text="What is 1704 in words?").grid(row=0) flagset() Label(frame2, text="What is 1704 in words?").grid(row=0) Button(frame2, text="One Million, Seven thousand and Four", command=clear2, width=35).grid(row=1, sticky=W) Button(frame2, text="One Hundred and Seventy Four",…
type: Question

http://stackoverflow.com/a/52060523
has comment: http://stackoverflow.com/comment/91071862
score: 3
has comment: http://stackoverflow.com/comment/91071389
accepted answer of: http://stackoverflow.com/q/52060484
answers question: http://stackoverflow.com/q/52060484
has body: Check the type of the first element: isinstance(the_list[0], list) i.e: &gt;&gt;&gt; isinstance(list_1[0], list) False &gt;&gt;&gt; isinstance(list_2[0], list) True However, what do you mean by a list of lists? Is the following a list of lists? [1, [1, 2, 3], 1, 1] If so, then you can check if any of the elements are lists: any(isinstance(l) for l in the_list) What about the case when they are all list? Is the following the only true "list of lists"? [[1, 2], [1, 2]] If so, then you can check if all the elements are lists: all(isinstance(l) for l in the_list) However, although these questions are important, for your example, the first snippet will suffice.
has comment: http://stackoverflow.com/comment/91071831
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/91071451
type: Answer
upvote count: 3

http://stackoverflow.com/q/52064649
has title: Aggregate list of dictionary in bins by applying weighted average in Python
favorite count: 0
has comment: http://stackoverflow.com/comment/91082028
type: UnansweredQuestion
tagged with: python
tagged with: dictionary
has answer: http://stackoverflow.com/a/52064898
score: 2
tagged with: list
tagged with: weighted-average
has body: I have a list of dictionaries, which looks like this: _input = [{'cumulated_quantity': 30, 'price': 7000, 'quantity': 30}, {'cumulated_quantity': 80, 'price': 7002, 'quantity': 50}, {'cumulated_quantity': 130, 'price': 7010, 'quantity': 50}, {'cumulated_quantity': 330, 'price': 7050, 'quantity': 200}, {'cumulated_quantity': 400, 'price': 7065, 'quantity': 70}] I would like to group the dictionary in bins of quantity 100, where the price is calculated as a weighted average. The result should look like this: result = [{'cumulated_quantity': 100, 'price': 7003, 'quantity': 100}, {'cumulated_quantity': 200, 'price': 7038, 'quantity': 100}, {'cumulated_quantity': 300, 'price': 7050, 'quantity': 100}, {'cumulated_quantity': 400, 'price': 7060.5, 'quantity': 100}] The weighted averages, in the result dictionary are calculated as follows: 7003 = (30*7000+50*7002+20*7010)/100 7038 = (30*7010+70*7050)/100 7050 = 100*7050/100 7060.5 = (30*7050+70*7065)/100 I managed to receive the result, by utilising pandas dataframes, however their performance is way too slow (about 0.5 seconds). Is there a fast method to do this in python?
type: Question
upvote count: 2
has answer: http://stackoverflow.com/a/52065557
answer count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/91079973

http://stackoverflow.com/comment/91159416
has text: Possible duplicate of [How to run pip of different version of python using python command?](https://stackoverflow.com/questions/34803040/how-to-run-pip-of-different-version-of-python-using-python-command)
comment on: http://stackoverflow.com/q/52092668
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52097898
has answer: http://stackoverflow.com/a/52099983
score: 0
has comment: http://stackoverflow.com/comment/91146106
tagged with: python
type: UnansweredQuestion
tagged with: django
has body: I am overwriting clean method but when I do it like this: def clean(self): if "post_update_password" in self.data: print(self.cleaned_data) old_password = self.cleaned_data['old_password'] new_password1 = self.cleaned_data['new_password1'] new_password2 = self.cleaned_data['new_password2'] return super().clean() It returns this: {'old_password': 'Password,1.', 'new_password1': 'a'} which means that I am unable to get that new_password2 value. And when I change my clean method like this: def clean_new_password2(self): if "post_update_password" in self.data: print(self.cleaned_data) old_password = self.cleaned_data['old_password'] new_password1 = self.cleaned_data['new_password1'] new_password2 = self.cleaned_data['new_password2'] return super().clean() It magicaly works and returns: {'old_password': 'Password,1.', 'new_password1': 'PAssssad', 'new_password2': 'a'} I really don't understand what is happening. I know how to bypass this issue but I am really curious where is the problem. Thanks for any reply
type: Question
has title: Django form cleaning acting strangely
answer count: 1

http://stackoverflow.com/q/51973067
has answer: http://stackoverflow.com/a/51973174
accepted answer: http://stackoverflow.com/a/51973174
has comment: http://stackoverflow.com/comment/90896657
tagged with: python
tagged with: python-requests
has body: In Python's requests documentation, it suggests sending multipart form data like so: Requests makes it simple to upload Multipart-encoded files: &gt;&gt;&gt; url = 'http://httpbin.org/post' &gt;&gt;&gt; files = {'file': open('report.xls', 'rb')} &gt;&gt;&gt; r = requests.post(url, files=files) This question shows the same behavior. However, this question by the same author uses a with statement: with open('data','rb') as payload: headers = {'content-type': 'application/x-www-form-urlencoded'} r = requests.post('https://IP_ADDRESS/rest/rest/2', auth=('userid', 'password'), data=payload, verify=False, headers=headers) My intuition is that I should always use a with statement when using files; do I need it in this case or not? To be extra clear, I am not looking for advice as to whether or not to use with. I am specifically referring to the interaction with the requests library, and if I can omit the with statement as the docs imply.
tagged with: with-statement
has answer: http://stackoverflow.com/a/51973154
type: AnsweredQuestion
score: 1
possible better answer: http://stackoverflow.com/a/51973141
has comment: http://stackoverflow.com/comment/90898843
has title: Do I need to use a with statement when sending multipart form data in requests?
has comment: http://stackoverflow.com/comment/90899103
type: Question
upvote count: 2
has answer: http://stackoverflow.com/a/51973141
downvote count: 1
linked to: http://stackoverflow.com/q/16145116
has comment: http://stackoverflow.com/comment/90896808
answer count: 3
linked to: http://stackoverflow.com/q/22567306
favorite count: 0

http://stackoverflow.com/q/52074771
favorite count: 0
tagged with: python-3.x
has body: I have a Final.xlsx that contains multiple sheet - shee1, sheet2 ,sheet3 , each having some graphs and data. I have another file file5.xlsx that i want to add in Final.xlsx in tab . The below code is working but the Final.xlsx existing sheets data is getting missed(contents,formats, grpahs, and others) . need help to fix this. import pandas from openpyxl import load_workbook book = load_workbook('foo.xlsx') writer = pandas.ExcelWriter('foo.xlsx', engine='openpyxl') writer.book = book writer.sheets = dict((ws.title, ws) for ws in book.worksheets) df1=pd.read_excel('file5.xlsx') df1.to_excel(writer, "new",index=False) writer.save()
type: UnansweredQuestion
tagged with: python
has title: Data missing, format changed in .xlsx file having multiple sheets using pandas, openpyxl while adding new sheet in existing .xlsx file
tagged with: openpyxl
upvote count: 1
downvote count: 1
tagged with: excel
linked to: http://stackoverflow.com/q/46386143
type: Question
has answer: http://stackoverflow.com/a/52077406
has comment: http://stackoverflow.com/comment/91100944
score: 0
tagged with: pandas
answer count: 1
has comment: http://stackoverflow.com/comment/91099287
has comment: http://stackoverflow.com/comment/91101180

flask-bootstrap
tags question: http://stackoverflow.com/q/51972438
tag name: flask-bootstrap
type: Tag

http://stackoverflow.com/q/52092683
tagged with: calculated-columns
accepted answer: http://stackoverflow.com/a/52092973
upvote count: 2
tagged with: python
type: AnsweredQuestion
downvote count: 3
has comment: http://stackoverflow.com/comment/91135889
type: Question
has answer: http://stackoverflow.com/a/52092973
has body: I am trying to add 3 columns' values to come up with a new column as total value. Code is below: df3"Bronze","Gold","Silver" = df3"Bronze","Gold","Silver".astype("int") df3["Total Medal"]= df3.iloc[:, -3:0].sum(axis=1) df3"Total Medal".astype("int") I know that Bronze, Gold, Silver columns have 1 and 0 values and they are the last 3 columns in the dataframe. Their original types were "uint8" so I changed them to "int". Total Medal column after these lines come out as type "float" (instead of int) and yield only the value 0. How can I properly add these columns?
tagged with: sum
tagged with: dataframe
score: -1
has comment: http://stackoverflow.com/comment/91142385
has title: Summing columns in dataframe in python
possible better answer: http://stackoverflow.com/a/52092900
answer count: 2
has answer: http://stackoverflow.com/a/52092900
favorite count: 0

http://stackoverflow.com/comment/90894738
type: QuestionComment
comment on: http://stackoverflow.com/q/51971285
score: 0
has text: I just put the expected output from the book. Plus my version of python is 3.6 i think
type: Comment

http://stackoverflow.com/q/52079611
has comment: http://stackoverflow.com/comment/91109369
has comment: http://stackoverflow.com/comment/91109515
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52080010
score: 1
accepted answer: http://stackoverflow.com/a/52080010
has answer: http://stackoverflow.com/a/52079932
has title: loop multiple SQL queries and save output as single dataframe
type: Question
possible better answer: http://stackoverflow.com/a/52079932
upvote count: 2
answer count: 2
downvote count: 1
has body: I have a python script where I am trying to loop through multiple sql queries, take the outputs of those queries as simple count(*)'s, and concatenate them into one dataframe. def function(query): conn = ... sql_query = open(query, 'r').read() df_sql_output = pd.read_sql_query(sql_query,conn) concatenated_data = [] if not df_sql_output.empty: concatenated_data.append(df_sql_output) concatenated_data = pd.concat(concatenated_data, axis=1) print(concatenated_data) sqls = ['test1.sql','test2.sql','test3.sql'] for i in sqls: function(i)
favorite count: 0
tagged with: python

http://stackoverflow.com/q/52011191
has title: Kivy How to create widgets from dictionary in kivy
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/90974045
favorite count: 0
tagged with: python
has body: I am new to the library kivy for Python. I found the additional library kivy-md which has very good looking ui elements. At the moment I want to create many MDTextField widgets from a dictionary variable e.g. # text_fields.py text_fields = { "text_field1": { "key": 0, "self": "text_field1", "hint_text": "Textfield 1", "helper_text": "This is textfield 1", }, "text_field2": { "key": 1, "self": "text_field2", "hint_text": "Textfield 2", "helper_text": "This is textfield 2", } } From this variable, I want to create widgets in the kv file that look like GridLayout: MDTextField: id: text_field1 hint_text: text_fields["text_field1"]["hint_text"] helper_text: text_fields["text_field1"]["helper_text"] helper_text_mode: "on_focus" on_text_validate: app.on_text_validate(text_fields["text_field1"]["self"]) MDTextField: id: text_field2 hint_text: text_fields["text_field2"]["hint_text"] helper_text: text_fields["text_field2"]["helper_text"] helper_text_mode: "on_focus" on_text_validate: app.on_text_validate(text_fields["text_field2"]["self"]) I see two challenges in this problem that I am not able to solve. The first is how to parse the id values from the dictionary strings and the second problem is that I do not know how to loop over kivy widgets in a kv file. Is there a way to achieve what I want?
tagged with: kivy
has answer: http://stackoverflow.com/a/52012720
tagged with: dry
upvote count: 3
type: Question
type: AnsweredQuestion
score: 3
has comment: http://stackoverflow.com/comment/90973957
accepted answer: http://stackoverflow.com/a/52012720

http://stackoverflow.com/comment/91050101
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52049814
type: AnswerComment
has text: so a non-capture group basically makes sure that it exists, but won't return it? Absolutely nothing gets returned if the value the non-capturing group does not exist, correct?

http://stackoverflow.com/comment/91138164
type: Comment
score: 1
has text: The end of a range is not inclusive (exclusive). `range(1, 3)` will yield `(1, 2)`
comment on: http://stackoverflow.com/q/52094052
type: QuestionComment

http://stackoverflow.com/comment/90953592
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52001828
has text: @khelwood hmm, but how? Any pointers, possibly some link that describes the steps? Maybe I forgot, or didn't ever know it. It would definitely be better to know the steps specifically :P
score: 0

http://stackoverflow.com/comment/91140493
comment on: http://stackoverflow.com/a/52093408
has text: @Tasnuva - ya, sometimes if copy from So get syntact error, because bad copied some `''`. Try rewrite solution only.
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/q/52074701
has comment: http://stackoverflow.com/comment/91099332
score: 4
possible better answer: http://stackoverflow.com/a/52074853
upvote count: 4
has answer: http://stackoverflow.com/a/52074853
accepted answer: http://stackoverflow.com/a/52074865
downvote count: 0
has comment: http://stackoverflow.com/comment/91099154
favorite count: 0
has answer: http://stackoverflow.com/a/52074956
answer count: 3
has title: LEFT JOIN dictionaries in python based on value
tagged with: python
tagged with: dictionary
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91099242
has answer: http://stackoverflow.com/a/52074865
has body: #Input dict_1 = {"conn": {"ts":15,"uid":"ABC","orig_h":"10.10.210.250"}} dict_2 = {"conn": {"ts":15,"uid":"ABC","orig_h":"10.10.210.252"}} #Mapper can be modified as required mapper = {"10.10.210.250":"black","192.168.2.1":"black"} I am getting each dict in a loop, in each iteration I need to check a dict against the mapper and append a flag based on match between dict_1.orig_h and mapper.10.10.210.250 . I have the flexibility to define the mapper however I need. So the desired result would be: dict_1 = {"conn": {"ts":15,"uid":"ABC","orig_h":"10.10.210.250", "class":"black"}} dict_2 will remain unchanged since there is no matching value in mapper. This is kinda what I want, but it works only if orig_h is an int import collections result = collections.defaultdict(dict) for d in dict_1: result[d[int('orig_h')]].update(d) for d in mapper: result[d[int('orig_h')]].update(d)
type: Question

http://stackoverflow.com/comment/90900910
has text: Hm, ok it works. But it would be very helpful for me if you could explain why this happens! I would like to understand it.
type: AnswerComment
comment on: http://stackoverflow.com/a/51975228
type: Comment
score: 1

http://stackoverflow.com/a/51989250
has comment: http://stackoverflow.com/comment/90938122
score: 0
type: Answer
answers question: http://stackoverflow.com/q/51988363
has body: Why not try to use find_element_by_class_name("panelList").find_elements_by_tag_name('li') To collect all of the li elements. And using li.text to retrieve their text values. Its hard to tell what your actual output is besides you saying "returns null"

http://stackoverflow.com/q/52058768
score: -1
has title: After I deleted a file, why os.path.abspath() still shows its path?
answer count: 1
favorite count: 0
linked to: http://stackoverflow.com/q/10025863
tagged with: path
tagged with: python
duplicate of: http://stackoverflow.com/q/10025863
has answer: http://stackoverflow.com/a/52058806
type: AnsweredQuestion
tagged with: file
accepted answer: http://stackoverflow.com/a/52058806
downvote count: 1
type: Question
has body: print(os.path.exists("77.txt")) print(os.path.isfile("77.txt")) os.path.abspath("77.txt") ---------- False False '/home/nbuser/library/parent_dir/files_exercises/77.txt' I deleted a file, why the abspath still shows that it exists??
upvote count: 0

http://stackoverflow.com/q/51980038
type: AnsweredQuestion
has title: String storage in Python Class includes newline character
upvote count: 1
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/90909835
has comment: http://stackoverflow.com/comment/90910028
has answer: http://stackoverflow.com/a/51980157
has body: I have an output class that looks like the following (somewhat redacted): from colorclass import Color from colorclass import disable_all_colors, enable_all_colors, is_enabled from time import localtime, strftime from ApplicationFiles.lib.core.__version__ import __version__ from enum import IntEnum class OutputHelper(object): def __init__(self, arguments, app): if arguments.nocolor: disable_all_colors() self.domain = "undefined" self.severity_print = arguments.severity self.verbose = arguments.verbose self.silent = arguments.silent self.seperator = "==============================================" self.modules_count = app.modules_count() # this is here to allow easier redirection of output to other # interfaces later on in the project def write(self, severity, message): self.terminal(severity, message) def terminal(self, severity, message): if severity == 0 and not self.verbose: return if severity &lt; self.severity_print: return formatting = { 0: Color('{autoblue}[VERBOSE]{/autoblue}') } leader = formatting.get(severity, '[#]') format_args = { 'time': strftime("%H:%M:%S", localtime()), 'domain': self.domain, 'leader': leader, 'message': message, } template = '[{time}] [{domain}] {leader} {message}' print(template.format(**format_args)) class Level(IntEnum): VERBOSE = 0 I'm reading in a list of domains from a file, and passing it via this class to the following: for domain in arguments.domain_list: domains.append(domain) for domain in domains: output.domain = domain app.modules['example_module'].run(arguments, output) Which in turn then reads: def run(arguments, output): output.write(Level.VERBOSE, 'TEST DOMAIN') For whatever reason this is printing newlines after each print. For example: 1 modules loaded ============================================== [16:57:25] [testone.com ] [VERBOSE] TEST DOMAIN [16:57:25] [testtwo.com ] [VERBOSE] TEST DOMAIN [16:57:25] [testthree.com ] [VERBOSE] TEST DOMAIN This should read: 1 modules loaded ======================================…
score: 0
has comment: http://stackoverflow.com/comment/90909943
answer count: 1
accepted answer: http://stackoverflow.com/a/51980157
tagged with: string
favorite count: 0
tagged with: terminal
has comment: http://stackoverflow.com/comment/90909911
tagged with: python
has comment: http://stackoverflow.com/comment/90909974

http://stackoverflow.com/a/52060269
has comment: http://stackoverflow.com/comment/91072109
type: AcceptedAnswer
downvote count: 0
has body: Let us start from here, where you created the dataframe pd_df: print(pd_df) Output: 0 1 2 Document1 apple banana orange Document2 None orange banana Document3 banana apple None Document4 apple None None Now try this to create fruit_names columns (it does not matter how many columns you have in pd_df): for fruit_name in ['apple', 'orange', 'banana']: pd_df.loc[:, fruit_name] = pd_df.apply(lambda x: 'y' if fruit_name in x.values.tolist() else 'n', axis=1) print(df'apple', 'orange', 'banana') Output: apple orange banana Document1 y y y Document2 n y y Document3 y n y Document4 y n n
answers question: http://stackoverflow.com/q/52059654
has comment: http://stackoverflow.com/comment/91113236
type: Answer
accepted answer of: http://stackoverflow.com/q/52059654
upvote count: 2
has comment: http://stackoverflow.com/comment/91112756
has comment: http://stackoverflow.com/comment/91112350
has comment: http://stackoverflow.com/comment/91112587
score: 2

http://stackoverflow.com/q/52107545
tagged with: python
type: AnsweredQuestion
downvote count: 0
score: 1
type: Question
has title: Build a date vector using a "business day weekly" frequency.
possible better answer: http://stackoverflow.com/a/52107575
has body: The following line produces a date vector with a weekly frequency, using the sundays as the 'reported' date for each week. date_vector=pd.date_range(start='12/31/2006', end='01/31/2007', freq='W') The outcome is as follows: [Timestamp('2006-12-31 00:00:00', freq='W-SUN'), Timestamp('2007-01-07 00:00:00', freq='W-SUN'), Timestamp('2007-01-14 00:00:00', freq='W-SUN'), Timestamp('2007-01-21 00:00:00', freq='W-SUN'), Timestamp('2007-01-28 00:00:00', freq='W-SUN')] As you can tell, each date reported is for a sunday. But I want it to be for every friday (the end of the business week). Is something like that possible in pandas? I searched for the different frequencies available in the Pandas documentation for date_range (here) but couldn't find anything like that. My proposed solution would be a list comprehension in which for each element of this list I'd figure out if its sunday, and if that's the case apply a timedelta of -2 to lag it to fridays. But not sure if that's the most efficient out there and I wanted to see if anyone here could suggest something better. Thanks for your valuable time!
has answer: http://stackoverflow.com/a/52107575
answer count: 2
tagged with: pandas
upvote count: 1
tagged with: date-range
has answer: http://stackoverflow.com/a/52107574
accepted answer: http://stackoverflow.com/a/52107574
favorite count: 0
tagged with: python-3.x

http://stackoverflow.com/a/52058407
has comment: http://stackoverflow.com/comment/117912507
accepted answer of: http://stackoverflow.com/q/52056475
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/52056475
type: Answer
upvote count: 9
has body: Although @ralf-htp's answer is nice and clean and uses scatter, as far as I know the scale of the markers is expressed in points (see e.g. here). Moreover, if you zoom in, the custom markers will not change size. Maybe that is just what you are looking for. If not, using separate Rectangle objects also does the trick nicely. This allows you to specify width and height in data units instead of points, and you can zoom in. If necessary, it is easy to apply a rotation as well, by setting the angle attribute: from matplotlib import pyplot as plt from matplotlib.patches import Rectangle # Your data a = ([126, 237, 116, 15, 136, 348, 227, 247, 106, 5, -96, 25, 146], [117, 127, 228, 107, 6, 137, 238, 16, 339, 218, 97, -4, -105]) # Your scatter plot fig = plt.figure() ax = fig.add_subplot(111) ax.scatter(a[0], a[1], color = 'red', s=10) # Add rectangles width = 30 height = 20 for a_x, a_y in zip(*a): ax.add_patch(Rectangle( xy=(a_x-width/2, a_y-height/2) ,width=width, height=height, linewidth=1, color='blue', fill=False)) ax.axis('equal') plt.show() The result: Note: If necessary you can obtain the Rectangle instances via ax.get_children().
score: 9

http://stackoverflow.com/comment/91086436
has text: @user456 `df.sort_values('sum').drop_duplicates('Year-month',keep='last')['d']`
type: AnswerComment
type: Comment
score: 1
comment on: http://stackoverflow.com/a/52067953

http://stackoverflow.com/comment/91021358
type: QuestionComment
comment on: http://stackoverflow.com/q/52035388
has text: @KillPinguin PYTHONPATH is None for both, the difference is in PATH. QT has the following 2 more than the output of python: /opt/Qt/5.11.0/gcc_64/bin:/usr/bin
score: 0
type: Comment

http://stackoverflow.com/comment/90922344
type: QuestionComment
comment on: http://stackoverflow.com/q/51986060
has text: You haven't shown what `Email` is.
score: 0
type: Comment

http://stackoverflow.com/comment/91111484
comment on: http://stackoverflow.com/a/52080465
score: 0
has text: @schwobaseggl true, but I think it's fair to assume this is a beginners mistake and not a type check.
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/90965278
has text: What have you tried so far?
score: 1
comment on: http://stackoverflow.com/q/52007488
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91175493
has text: install the Build tools not the redist files: https://visualstudio.microsoft.com/visual-cpp-build-tools/
comment on: http://stackoverflow.com/q/52110485
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/52074547
downvote count: 0
score: 1
has body: You can use toolz.unique, or equivalently the unique_everseen recipe in the itertools docs, or equivalently @JoeIddon's explicit solution. Here's the solution using 3rd party toolz: x = "Hett, Agva, Delf, Agva, Hett," from toolz import unique res = ', '.join(filter(None, unique(x.replace(' ', '').split(',')))) print(res) 'Hett, Agva, Delf' I've removed whitespace and used filter to clean up a trailing , which may not be required.
upvote count: 1
type: Answer
answers question: http://stackoverflow.com/q/52074329

http://stackoverflow.com/a/52009783
has comment: http://stackoverflow.com/comment/90970575
has comment: http://stackoverflow.com/comment/90970531
upvote count: 2
has comment: http://stackoverflow.com/comment/90970979
has comment: http://stackoverflow.com/comment/90971040
type: Answer
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/90970439
answers question: http://stackoverflow.com/q/52009415
has body: There are two different things you could be asking about here. The second one will be faster just because of things like: Passing a single argument instead of 1000. (In recent versions of CPython, this doesn't actually mean passing 1000 values on the stack, but it does mean you have to go through CALL_FUNCTION_EX instead of going through the simpler CALL_FUNCTION, and in fact its optimized fast path.) Looping over the list elements inside the optimized list.__repr__, instead of with a generic iterator loop. The stuff print does between the __str__ of each element is slightly more complicated than the stuff list.__repr__ does between the __repr__ of each element (conditionally printing a local variable, as opposed to always tacking on a constant string). That should be a matter of microseconds—enough to measure, but not enough to notice. But the second one will also be faster because it's making fewer I/O calls. This is likely to swamp all those little differences. And if your terminal is something slow, like Windows cmd or the IDLE fake terminal, this could very easily be enough to notice. First let's try calling a function that does absolutely nothing: In [765]: def dummy(*args): pass In [766]: %timeit dummy(*range(1, 1001)) 19 µs ± 71.1 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each) In [767]: %timeit dummy([*range(1, 1001)]) 13 µs ± 609 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each) So, the second one is about 50% faster just because of argument passing, but that's only 6us. What if it iterates its arguments, effectively the way print does? In [768]: def dummy(*args): ...: for _ in args: pass In [769]: %timeit dummy(*range(1, 1001)) 22.8 µs ± 1.31 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each) In [770]: %timeit dummy([*range(1, 1001)]) 13.1 µs ± 148 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each) Now it's getting closer to 2:1, but it's still only 9us difference. Of course I'm cheating here a bit, because print is …
has comment: http://stackoverflow.com/comment/90970796

http://stackoverflow.com/comment/91109486
type: Comment
type: QuestionComment
has text: Can't you set `A = set() if not A else A` at the start of your function?
comment on: http://stackoverflow.com/q/52079704
score: 0

http://stackoverflow.com/comment/91031402
type: AnswerComment
comment on: http://stackoverflow.com/a/52040338
type: Comment
has text: By "You reached to the end of your file", Do you mean since 'row' contains the last row, the second for-loop is not giving the output.?. If so what about the change made to 'row' to be 'r'
score: 0

http://stackoverflow.com/q/52097119
upvote count: 2
type: UnansweredQuestion
score: -3
has answer: http://stackoverflow.com/a/52097197
type: Question
tagged with: numpy
tagged with: numpy-ndarray
has body: I want to create 5x5 numpy array. Declaration looks like: aa = np.array([[2.82842712, 2.23606798, 2.0, 2.23606798, 2.82842712], [2.23606798, 1.41421356, 1.0, 1.41421356, 2.23606789], [2.0, 1.0, 0.0, 1.0, 2.0], [2.23606789, 1,41421356, 1.0, 1.41421356, 2.23606789], [2.82842712, 2.23606789, 2.0, 2.23606798, 2.82842712]]) but when i check it's size is 5x1. Printed in console array looks like: MATRICE aa: [[2.82842712, 2.23606798, 2.0, 2.23606798, 2.82842712] [2.23606798, 1.41421356, 1.0, 1.41421356, 2.23606789] [2.0, 1.0, 0.0, 1.0, 2.0] [2.23606789, 1, 41421356, 1.0, 1.41421356, 2.23606789] [2.82842712, 2.23606789, 2.0, 2.23606798, 2.82842712]] Shape: (5,) Does anyone see where I'm wrong?
has title: Incorrect shape of 2D numpy array
downvote count: 5
answer count: 1
tagged with: python
favorite count: 0
tagged with: python-3.x

http://stackoverflow.com/a/66985053
type: Answer
accepted answer of: http://stackoverflow.com/q/51960766
score: 3
upvote count: 3
type: AcceptedAnswer
downvote count: 0
has body: Bit old, but hopefully this might help someone out. If you're using OpenCV2 for image processing. You might consider using OpenCV2's putText function to overlay text on the image. import cv2 as cv # Read image from file path or from a video or screenshot feed img = cv.imread(targetImgPathOrScreenshotFeed, cv.IMREAD_UNCHANGED) # Your detection method here to return either cat or dog result # Overlay text on this image # cv.putText(img, text, distanceFromOrgin(Top left), fontFace, fontScale, colour, thickness) cv.putText(img, 'Dog', (30, 70), cv.FONT_HERSHEY_SIMPLEX, .5, (255, 255, 255), 1) # Display result if necessary cv.imshow('Detection Result', img)
answers question: http://stackoverflow.com/q/51960766

http://stackoverflow.com/comment/91129538
type: QuestionComment
comment on: http://stackoverflow.com/q/52089716
has text: Is the value in exactly the same position in both sheets? If not, then you need another one or two nested for loops to walk through the other sheet.
score: 2
type: Comment

http://stackoverflow.com/q/52031590
answer count: 1
favorite count: 0
tagged with: python-3.x
tagged with: python
has comment: http://stackoverflow.com/comment/91013927
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52031636
has comment: http://stackoverflow.com/comment/91047990
has body: Sorry. I will modify the contents. I would like to load a widget inside def test by pressing Qbutton. Can not you use QStackedWidget to load the widget's configured functions? I've compiled the class and called it, but only a = QLineEdit ('Qline', self). I wonder what should be done to switch widgets. You can also create a table like html using pyqt5. import sys from PyQt5.QtWidgets import * class MainWindow(QMainWindow): def __init__(self): super().__init__() self.stacked = QStackedWidget(self) self.FirstpUI() def FirstpUI(self): self.btn1 = QPushButton('test1', self) self.btn1.move(50,50) self.btn1.clicked.connect(self.btn1_click) def test(self): a = QLineEdit('Qline', self) b = QLineEdit('Qline2', self) c = QPushButton('button', self) a.move(0, 0) b.move(100, 0) c.move(50,50) c.clicked.connect(self.btn2_click) def btn1_click(self): self.btn1.deleteLater() self.stacked.addWidget(self.test()) self.stacked.setCurrentIndex(self.stacked.currentIndex()+1) def btn2_click(self): QMessageBox.about(self,'hello','hello2') if __name__ == "__main__": app = QApplication(sys.argv) fream = MainWindow() fream.show() app.exec_()
tagged with: pyqt5
has comment: http://stackoverflow.com/comment/91048023
downvote count: 1
type: Question
score: -1
has title: I want to know how to use pyqt5 to load the created widget at once
accepted answer: http://stackoverflow.com/a/52031636
tagged with: pyqt
upvote count: 0

http://stackoverflow.com/comment/91074902
type: Comment
comment on: http://stackoverflow.com/a/52029002
has text: I think math of this exercise based on ---> https://en.wikipedia.org/wiki/Archimedean_spiral, but I don`t find all formulas for this
type: AnswerComment
score: 0

http://stackoverflow.com/q/52044857
type: UnansweredQuestion
tagged with: bigdata
type: Question
has body: This is my JSON file and I want to sum all values of number key. How can i do that with Python? { "took": 0, "timed_out": false, "_shards": { "total": 5, "successful": 5, "skipped": 0, "failed": 0 }, "hits": { "total": 7, "max_score": 1.0, "hits": [{ "_index": "test", "_type": "json", "_id": "5878", "_score": 1.0, "_source": { "data_type": "click", "number": 1, "date": "1397/05/14", "host_id": "1231" } }, { "_index": "test", "_type": "json", "_id": "1548", "_score": 1.0, "_source": { "data_type": "click", "number": 1, "date": "1397/05/14", "host_id": "1231" } }, { "_index": "test", "_type": "json", "_id": "2751", "_score": 1.0, "_source": { "data_type": "click", "number": 1, "date": "1397/05/14", "host_id": "1231" } }, { "_index": "test", "_type": "json", "_id": "8363", "_score": 1.0, "_source": { "data_type": "click", "number": 1, "date": "1397/05/14", "host_id": "1231" } }, { "_index": "test", "_type": "json", "_id": "551", "_score": 1.0, "_source": { "data_type": "click", "number": 1, "date": "1397/05/14", "host_id": "1231" } }, { "_index": "test", "_type": "json", "_id": "2195", "_score": 1.0, "_source": { "data_type": "click", "number": 1, "date": "1397/05/14", "host_id": "1231" } }, { "_index": "test", "_type": "json", "_id": "2990", "_score": 1.0, "_source": { "data_type": "click", "number": 1, "date": "1397/05/14", "host_id": "1231" } }] } }
answer count: 1
score: 0
has title: How to sum specific values of my json file in elasticsearch in python?
has answer: http://stackoverflow.com/a/52045718
tagged with: elasticsearch
tagged with: python
has comment: http://stackoverflow.com/comment/91041071

http://stackoverflow.com/comment/91067257
has text: so the second approach is not working in my case. can u help me with some other method
comment on: http://stackoverflow.com/a/52056180
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/q/52094370
linked to: http://stackoverflow.com/q/3503719
has answer: http://stackoverflow.com/a/52094480
has comment: http://stackoverflow.com/comment/91139277
favorite count: 0
has comment: http://stackoverflow.com/comment/91138857
has body: In order to declare a number of environment variables then call some python scripts using them, I create a myfile.sh file which is the on to run by bash myfile.sh . I have, however, plenty of scripts that should read these environment variables, but cannot create a myfile.sh for each one! So my idea is to create an environment variable file and access it by each of my python scripts. So my question is, how to access such a file with python 2.7 ? A most relevant question is the following: Where does os.environ read the environment variables from? It should be noted that I cannot install additional libraries such as dotenv. So a solution, if possible, should be based on standard libraries. Any help would be mostly appreciated!
has answer: http://stackoverflow.com/a/52094718
tagged with: python
type: AnsweredQuestion
upvote count: 0
has title: How to read environment variables from specific file with python 2.7
has comment: http://stackoverflow.com/comment/91138854
type: Question
score: -2
answer count: 2
downvote count: 2
possible better answer: http://stackoverflow.com/a/52094480
tagged with: environment-variables
accepted answer: http://stackoverflow.com/a/52094718
has comment: http://stackoverflow.com/comment/91139045

http://stackoverflow.com/comment/91081889
has text: Show the error and the code you used when you got that error.
comment on: http://stackoverflow.com/q/52065617
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91108152
type: Comment
comment on: http://stackoverflow.com/a/52078280
type: AnswerComment
has text: @NirvikalpaSamadhi it looks like the cell where you concat your dataframes was run at 103 and the plot was run at 11. Just re-run your cells in order and it should work. I am guessing the kernel was reset and the results variable is no longer defined
score: 0

http://stackoverflow.com/a/52034185
has comment: http://stackoverflow.com/comment/91022694
score: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/52032422
type: Answer
answers question: http://stackoverflow.com/q/52032422
has body: If i understood your question correctly, it's a problem of having the right data-structures. Let's have the following data-structures, 1. A dictionary from the line-polygons to points 2. Another dictionary from points to line-polygons (or equivalently a single bidirectional map from bidict instead of couple of dictionaries) 3. a boolean array visited with size equal to the number of points Now the following algorithm should solve your problem (can be implemented efficiently with the above data structures): For all the points initialize the visited array to be False. Find the nearest point to the query point first from the kd-tree, mark the matched point and all the points from the the corresponding polygon the matched point belongs to as visited and return that particular polygon (id) as the nearest polygon (if there are multiple such polygons, return all of them). Repeat step 2 until n such (distinct) polygons are returned. Consider a new point returned from the kd-tree as matched with the query point iff it's not yet visited (if a matched point returned by kd-tree is already visited, discard it and query the next nearest point matched). Once a point is visited, mark the point and all the points from the corresponding polygon(s) as visited and return the polygon(s).

http://stackoverflow.com/q/52062796
answer count: 0
has title: Confidence intervals for covariance in python
type: Question
has body: I'm using df['col1'].cov(df['col2']) to calculate the covariance between two columns in dataframe df. How can I get smth like p-value for this covariance value? Maybe there is smth similar to stats.pearsonr, which produces correlation coefficient and p-value?
score: 0
tagged with: covariance
has comment: http://stackoverflow.com/comment/91075957
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/25571882
tagged with: python
has comment: http://stackoverflow.com/comment/91076032

http://stackoverflow.com/comment/91028521
type: QuestionComment
comment on: http://stackoverflow.com/q/52038874
score: 0
has text: @G.Brown google 2.0.1 google-api-python-client 1.7.4 google-auth 1.5.1 google-auth-httplib2 0.0.3 google-cloud 0.34.0 google-search 1.0.2
type: Comment

http://stackoverflow.com/comment/90876887
score: 0
comment on: http://stackoverflow.com/q/51961513
has text: Remove last backslash from Url variable. It should be `'var Url = "/members" + params;'`
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52044949
score: 0
answer count: 1
has title: plt.colorbar ticks unequal between plots
tagged with: python
tagged with: heatmap
type: AnsweredQuestion
has body: I am using matplotlib to plot heat maps, as below: Note that the ticks on the colorbars differ. I want both of them to start at 0 and end at 1. I think the issue lies on the minimum values of each array (x_array is plotted on the left, and y_array on the right): np.min(x_array) 0.10800000000000001 np.min(y_array) 4.679256262324e-310 (full arrays are shown below) However, I am using the same specification for ticks in both plots: plt.colorbar(ticks = np.linspace(0, 1, num = 5)) Any help with fixing this appreciated. I am using Python 2.7 on Jupyter. Full code and arrays are: plt.figure(figsize = (12,5)) plt.subplots_adjust(left= 0, right= 1, top = .9, bottom = 0.1, wspace = 0.001) ticks = np.arange(0, 1, step = 0.1) # left plot plt.subplot(1, 2, 1) plt.xticks(ticks), plt.yticks(ticks) plt.imshow(x_array, cmap=plt.cm.gray, origin = "lower", extent = (0,.9,0,.9)) plt.colorbar(ticks = np.linspace(0, 1, num = 5)) # right plot plt.subplot(1, 2, 2) plt.xticks(ticks), plt.yticks(ticks) plt.imshow(y_array, cmap=plt.cm.gray, origin = "lower", extent = (0,.9,0,.9)) plt.colorbar(ticks = np.linspace(0, 1, num = 5)) x_array (array([[1. , 1. , 1. , 1. , 1. , 1. , 1. , 1. , 1. ], [1. , 1. , 1. , 1. , 1. , 1. , 1. , 1. , 1. ], [0.64 , 1. , 1. , 1. , 1. , 1. , 1. , 1. , 1. ], [0.37 , 1. , 1. , 1. , 1. , 1. , 1. , 1. , 1. ], [0.27 , 1. , 1. , 1. , 1. , 1. , 1. , 1. , 1. ], [0.21 , 0.47 , 1. , 1. , 1. , 1. , 1. , 1. , 1. ], [0.17 , 0.36 , 1. , 1. , 1. , 1. , 1. , 1. , 1. ], [0.108, 0.29 , 0.46 , 1. , 1. , 1. , 1. , 1. , 1. ], [0.108, 0.24 , 0.37 , 0.52 , 1. , 1. , 1. , 1. , 1. ]]), y_array array([[1.00000000e-002, 1.00000000e-002, 1.00000000e-002, 1.00000000e-002, 1.00000000e-002, 1.00000000e-002, 1.00000000e-002, 1.00000000e-002, 4.67925626e-310], [4.67925626e-310, 1.00000000e-002, 1.00000000e-002, 1.00000000e-002, 1.00000000e-002, 1.00000000e-002, 1.00000000e-002, 1.00000000e-002, 1.00000000e-002], [1.00000000e+000, 4.67925626e-310, 1.00000000e-002, 1.00000000e-002, 1.00000000e-002, …
type: Question
tagged with: matplotlib
has answer: http://stackoverflow.com/a/52046191
accepted answer: http://stackoverflow.com/a/52046191

http://stackoverflow.com/comment/91123109
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52086229
has text: I did, but once I click on the game window the mouse "disappears". It recognizes mouse clicks but not the movement
score: 0

http://stackoverflow.com/a/52946076
type: AcceptedAnswer
has body: For me adding this fixed it: error_bad_lines=False It just skips the last line. So instead of reviews = pd.read_csv('br.csv', engine='python', encoding='utf-8') reviews = pd.read_csv('br.csv', engine='python', encoding='utf-8', error_bad_lines=False)
type: Answer
score: 34
downvote count: 0
has comment: http://stackoverflow.com/comment/128898919
upvote count: 34
accepted answer of: http://stackoverflow.com/q/52105659
answers question: http://stackoverflow.com/q/52105659

union
type: Tag
tags question: http://stackoverflow.com/q/52073609
tags question: http://stackoverflow.com/q/51981723
tag name: union

mongodb
tags question: http://stackoverflow.com/q/52106412
tags question: http://stackoverflow.com/q/52061762
tags question: http://stackoverflow.com/q/52087994
tags question: http://stackoverflow.com/q/52020493
tag name: mongodb
tags question: http://stackoverflow.com/q/52089328
tags question: http://stackoverflow.com/q/52000763
tags question: http://stackoverflow.com/q/51965039
tags question: http://stackoverflow.com/q/52037219
tags question: http://stackoverflow.com/q/52056540
tags question: http://stackoverflow.com/q/52039592
tags question: http://stackoverflow.com/q/52103750
type: Tag
tags question: http://stackoverflow.com/q/52027761
tags question: http://stackoverflow.com/q/52079427
tags question: http://stackoverflow.com/q/52084428
tags question: http://stackoverflow.com/q/52078244
tags question: http://stackoverflow.com/q/51964375
tags question: http://stackoverflow.com/q/51979663
tags question: http://stackoverflow.com/q/52090474

http://stackoverflow.com/comment/90936717
type: QuestionComment
comment on: http://stackoverflow.com/q/51993428
score: 0
type: Comment
has text: I think so, especially when "the spacing is not the same".

http://stackoverflow.com/comment/91040196
comment on: http://stackoverflow.com/q/52044389
score: 0
has text: Interesting, is the `sleep` command all I need then? Where exactly does the `multiprocessing` tool come in? I've never used it before, and have been a bit confused on the examples I've read with it.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/90932312
type: AnswerComment
has text: God bless your family
type: Comment
comment on: http://stackoverflow.com/a/51989082
score: 0

http://stackoverflow.com/a/51967521
upvote count: 0
has body: I have never used PyGame but one can see that your update() method in the Projectiles class depends on key press while it should depend on elapsed time instead. Your projectile moves 5 units per key press, not 5 units per game tick once launched.
downvote count: 2
answers question: http://stackoverflow.com/q/51967307
has comment: http://stackoverflow.com/comment/90885303
score: -2
type: Answer

http://stackoverflow.com/comment/90869606
comment on: http://stackoverflow.com/q/51959575
has text: Oh. I get it. Should print `(*a).data()` from eigen array.
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/90935645
type: Comment
type: QuestionComment
has text: `df.set_index('people').sequence.idxmax()`
score: 3
comment on: http://stackoverflow.com/q/51993038

http://stackoverflow.com/comment/90934789
type: QuestionComment
comment on: http://stackoverflow.com/q/51989635
has text: `depth` isn't helping. I just tried it out. How can I debug this further?
score: 0
type: Comment

http://stackoverflow.com/q/52067828
has body: This is the relevant Fusion charts code for a pie chart. I want to display all the attributes in my database of all entries but according to 'name' dataSource2['data'] = [] # Iterate through the data in `Revenue` model and insert in to the `dataSource['data']` list. for key in all_books: data = {} data['label'] = key.name data['value'] = key.price dataSource2['data'].append(data) Elaboration: Following concept i want to achieve to display all single parameters for every entry data[value1]=key.printingcost data[value2]=key.papercost data[value3]=key.binding Is it possible(in pie charts) suing Fusion charts library?? Attached picture for reference
upvote count: 1
type: UnansweredQuestion
has title: Django - Fusion Charts to display all values in one pie chart
has answer: http://stackoverflow.com/a/77300945
tagged with: fusioncharts
downvote count: 0
score: 1
favorite count: 0
type: Question
tagged with: django
tagged with: python
has answer: http://stackoverflow.com/a/52139337
answer count: 2

http://stackoverflow.com/q/52019578
score: 1
type: Question
possible better answer: http://stackoverflow.com/a/52019604
accepted answer: http://stackoverflow.com/a/52019638
linked to: http://stackoverflow.com/q/312443
has answer: http://stackoverflow.com/a/52019651
has answer: http://stackoverflow.com/a/52019604
has title: Break list up into sublists given a desired list size in python
has answer: http://stackoverflow.com/a/52019638
answer count: 3
downvote count: 0
favorite count: 0
tagged with: python-3.x
has body: I have a list that looks like this: arr = [['3'], ['1', '0.0'], ['2', '0.05'], ['3', '0.1'], ['1', '1'], ['2', '1'], ['3', '1']] I would like to break this list up into smaller sublists that are of the size given in the first element of the original list (e.g. 3 here) and only consist of the second element. What is the most pythonic way of doing this? sublist1 = [0.0, 0.05, 0.1] sublist2 = [1, 1, 1] I've tried to use list comprehension, but I don't know how to prescribe the for loop to loop through the array (i.e. between indices 1 and 3 or between indices 4 and 6 in the example arr above). n_nodes = arr[0][0] # gets number of nodes, 3 first_section = [element[1] for element in arr]
upvote count: 1
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90989620

http://stackoverflow.com/q/51998631
has title: Hash of a function object in python
has comment: http://stackoverflow.com/comment/90946753
has comment: http://stackoverflow.com/comment/90946437
tagged with: python
has body: Let me explain why I need to do this: I'm developing a library, and have the need to serialize python functions. Here are the 2 utility functions I use: def serialize_func(fn: function) -&gt; Tuple[bytes, str]: return marshal.dumps(fn.__code__), fn.__name__ def deserialize_func(serialized_fn: Tuple[bytes, str]) -&gt; function: return types.FunctionType( marshal.loads(serialized_fn[0]), globals(), serialized_fn[1] ) Now, If somehow I could cache the serialized functions, and store them in a dict like this: Dict[function_hash, function] { &lt;function hash&gt;: &lt;function&gt;, &lt;function hash&gt;: &lt;function&gt;, ... } It would result in quite a performance improvement since I don't need to serialize (and transport) them repeatedly. Is there a reliable way to achieve this? EDIT: If I tried hashing a function, It's not exactly what I have in mind. In [1]: def x(): ...: pass In [2]: hash(x) Out[2]: 8745212393041 In [3]: def x(): ...: pass In [4]: hash(x) Out[4]: -9223363291642382793 I need 2 functions with the same body, signature, global scope (and something else, which I'm probably missing) to return the same hash. Here is the library in question. EDIT: Here is some in-depth explanation of why I want to do this. I am sending the function from a process ("Client") to another one ("Server"), and executing it on "Server". Sounds weird and complicated, but I have a good reason for it. This whole process makes the function strictly atomic across all "Client"s The "Server" is the "Actor". So one, and only one function can run at a time, making it easier for the programmer to avoid race conditions. Now, I if the "Client" has already sent the function to the "Server" once, then for the subsequent interactions, It sends only the hash of that function, and the "Server" can just look up that function in its table.
score: 2
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/72548807
has comment: http://stackoverflow.com/comment/90946714
downvote count: 0
has comment: http://stackoverflow.com/comment/90947087
has comment: http://stackoverflow.com/comment/90946477
type: Question
has comment: http://stackoverflow.com/comment/90946739
accepted answer: http://stackoverflow.com/a/51999037
has comment: http://stackoverflow.com/comment/90946815
has comment: http://stackoverflow.com/comment/90946331
upvote count: 2
has comment: http://stackoverflow.com/comment/90947040
possible better answer: http://stackoverflow.com/a/72548807
answer count: 2
has comment: http://stackoverflow.com/comment/90946713
has answer: http://stackoverflow.com/a/51999037
has comment: http://stackoverflow.com/comment/90946595
favorite count: 0
has comment: http://stackoverflow.com/comment/90946475

http://stackoverflow.com/a/51984885
has comment: http://stackoverflow.com/comment/90922220
has comment: http://stackoverflow.com/comment/90954773
has comment: http://stackoverflow.com/comment/90919324
score: 1
has comment: http://stackoverflow.com/comment/90923666
has comment: http://stackoverflow.com/comment/90955122
has body: Just use the .strip() method, which you call on a string, and which takes a single argument - the string sequence you want to remove from the left and right sides of a string. E.g. s = '$$cat$$' s.strip('$') # results in 'cat' Your example: import csv from csv import writer COLUMNS = 6 with open("Winning No - Sheet1.csv", "r") as input: with open("output_file.csv", "w") as f: output = writer(f, delimiter=";") output.writerow(["Col {}".format(i+1) for i in xrange(COLUMNS)]) for row in input: output.writerow(row.strip('"').split(','))
has comment: http://stackoverflow.com/comment/90919983
downvote count: 0
has comment: http://stackoverflow.com/comment/90919741
answers question: http://stackoverflow.com/q/51984799
type: Answer
upvote count: 1

http://stackoverflow.com/a/52009738
has body: You need to use glob module: import glob, os import pandas as pd path =r'C:\YourFolder' #path to folder with .csv files all = glob.glob(path + "/*.csv") d_frame = pd.DataFrame() list_ = [] for file_ in all: df = pd.read_csv(file_,index_col=None, header=0) if df['YourColumns'].tail(1).isin([6,7,8,9,10,16,17,18,19,20,26,27,28,29,30]) == True: #You can modify list with conditions you need list_.append(df) d_frame = pd.concat(list_)
type: Answer
has comment: http://stackoverflow.com/comment/90970644
answers question: http://stackoverflow.com/q/52009483
score: 0

http://stackoverflow.com/q/52085070
tagged with: jupyter-notebook
answer count: 0
has comment: http://stackoverflow.com/comment/91126790
has comment: http://stackoverflow.com/comment/91125207
type: Question
tagged with: dataframe
has comment: http://stackoverflow.com/comment/91126283
score: 0
has body: I have multiple SQL queries that I have written within Jupyter and saved them as df, df1, df2, df3, df4, df5, df6, df7 I have been able to take the unique names for the individual dataframes: names=df,df1,df2,df3,df4,df5,df6,df7['A'].unique().tolist() With that I then want to create individual workbooks for each of the individual names found in column A and on separate tabs (which I want to be able to name) have the data with name 1 from df on sheet 1, data with name 1 from df1 on sheet 2, etc. I currently have this right now, however, it is only able to capture df and it is not working as expected from pandas import ExcelWriter import os path="/name" os.chdir(path) for i in names: writer = ExcelWriter(str(i)+'.xlsx') i=pd.DataFrame(df.loc[df['A']==i]) i.to_excel(writer) Additional info: Code 1 Code 2 Current Results Updated with scenario Sample 1 Sample 2 So here, I have 2 dataframes, each has Name1 and Name2. I want an excel sheet named BOB + SAM, have that dataframes name as the sheet name and the one record that is it. Ryan Connor is in both dataframes, so I want to create an excel file named Ryan + Connor, have dataframe 1 record on sheet 1 (named something) and dataframe 2 record on sheet 2
tagged with: pandas
tagged with: jupyter
has title: Create Unique list from dataframes (1-7), Create individual excel files with data from dataframes 1-7 on different sheets?
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91125104
tagged with: python

http://stackoverflow.com/comment/90879297
type: Comment
comment on: http://stackoverflow.com/a/51964494
score: 0
type: AnswerComment
has text: Now that I've fixed 'flag', there seems to be an issue with displaying what score is. It just prints: "Your total is:" " ". Any help?

http://stackoverflow.com/comment/90883709
type: Comment
type: QuestionComment
score: 1
has text: Maybe `quoting=csv.QUOTE_NONE` is not the right option.
comment on: http://stackoverflow.com/q/51966824

http://stackoverflow.com/comment/90900358
comment on: http://stackoverflow.com/a/51974883
has text: Great answer (I guess it isn't that hard to explain…). But why `sorted` at the end? The OP didn't ask for sorting, and I think it's just going to confuse things given that these lines are supposed to be "numbers" and you're reading and sorting them as strings…
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/52099955
upvote count: 2
has title: Python dist-packages permissions
type: Question
has answer: http://stackoverflow.com/a/52100624
tagged with: chmod
tagged with: file-permissions
answer count: 1
downvote count: 0
has body: I've screwed up some permissions in my dist-packages folder for Python 2.7 and am worried it is going to cause issues. This stems from an entirely separate issue with imports, which caused me to change the permissions of this folder to test things out. I took the advice to run: chmod -R 775 /usr/local/lib/python2.7/dist-packages/. When this did not work I attempted to change it back to what it was originally with: chmod 765 /usr/local/lib/python2.7/dist-packages/ Notice the lack of recursive flag. Silly me. When I did an ls -l I saw I had permissions of drwxrwSr-x on the folder. It should be drwxrwsr-x . So I gave it execute permissions with chmod +x and then setgid - chmod g+s mydir Ok, so my folder permissions were now back to normal. However in the folder now I see most (not all) of the files are drwxrwSr-x. What should I do to fix this mess? Here is an excerpt from the messy folder contents: drwxrwSr-x 2 root staff 4096 Jul 19 12:48 wheel-0.30.0.dist-info drwxrwSr-x 12 root staff 4096 Jul 19 12:48 whoosh drwxrwSr-x 2 root staff 4096 Jul 19 12:48 Whoosh-2.7.4.dist-info drwxrwSr-x 2 root staff 4096 Jul 19 12:48 xmltodict-0.11.0.dist-info -rwxrw-r-x 1 root staff 17356 Jul 19 12:48 xmltodict.py -rwxrw-r-x 1 root staff 15128 Jul 19 12:48 xmltodict.pyc drwxrwSr-x 2 root staff 4096 Jul 19 12:48 yaml -rwxrw-r-x 1 root staff 1115503 Jul 19 12:48 _yaml.so
has comment: http://stackoverflow.com/comment/107329098
favorite count: 0
linked to: http://stackoverflow.com/q/9122200
tagged with: python
accepted answer: http://stackoverflow.com/a/52100624
type: AnsweredQuestion
score: 2
has comment: http://stackoverflow.com/comment/107604421

http://stackoverflow.com/a/51973694
score: 3
upvote count: 3
has body: You could go between all the values from one colour to the next by converting it into an int, increasing the number, and converting it back to hex. Then you just loop until you reach the next value with something like so: value1 = 0xff00ff value2 = 0xffffff increment = 1 # amount to decrease or increase the hex value by while value1 != value2: if value1 &gt; value2: if int(value1)-increment &lt; int(value2): # failsafe if the increment is greater than 1 and it skips being the value value1 = value2 else: value1 = hex(int(value1)-increment) else: if int(value1)+increment &gt; int(value2): value1 = value2 else: value1 = hex(int(value1)+increment) code_to_change_colour(value1) See the edit by Prune for a much more elegant implementation of this. Note that code_to_change_colour(value1) should be changed to however you change the colour in your program. The increment will let you change how many colours are skipped. Obviously this code would need to be edited into a manner it can be used easily: e.g a function like def fade(value1, value2). Edit from @Prune -- because code doesn't work well in comments. Note that most of what you've written is "merely" loop control. You have known start and stop values and a fixed increment. This suggests a for loop rather than a while. Consider this: value1 = int(0xff00ff) value2 = int(0xffffff) increment = 1 if value1 &lt; value2 else -1 for current in range(value1, value2, increment): code_to_change_colour(hex(value1)) value1 = value2
has comment: http://stackoverflow.com/comment/90899000
downvote count: 0
answers question: http://stackoverflow.com/q/51973441
type: Answer

http://stackoverflow.com/comment/91011518
has text: How are you running the code? That does not seem like a Python file, it does not end in .py
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52030496
score: 2

http://stackoverflow.com/q/51966624
tagged with: pandas
has body: I want to compute difference between rows based on some column by using python/pandas. I guess I can explain better by using small examples. So, I have the following data: Number of rows A B 1 4 NaN 2 2 NaN 3 2 1 4 3 NaN 5 2 NaN And I want to get following data: Number of rows A B C 3 2 1 2 So, lets me explain what I did here. Firstly, I need to identify the rows of Column B, which has a value of 1 (As you can row Number 3 has a value 1). Then, I need to find the difference between 2 rows prior to and following to this row (row Number 3) and show the result as a column C. In our example 2 rows prior to row Number 3 is row Number 1 and 2 rows following the row Number 3 is row Number 5. And the difference between the values of row Number 1 and row Number 5 of COLUMN A is 2 (4-2 = 2) (At the end, I will keep the rows only has value in Column C - this is an easy task and I do not need any help in that). I hope I can explain it. Thanks in advance for your help.
answer count: 1
favorite count: 0
tagged with: python
type: AnsweredQuestion
score: 1
has answer: http://stackoverflow.com/a/51966811
accepted answer: http://stackoverflow.com/a/51966811
upvote count: 1
type: Question
tagged with: numpy
has title: Calculate difference betweenrows based on another column_Pandas
downvote count: 0

http://stackoverflow.com/a/67677629
answers question: http://stackoverflow.com/q/51995182
score: 0
has body: @harryghgim You idea is great but I think that the point of this project was to unify all pictures to one size with the logo so combining Your solution I've resized logo added to pictures and than resided all using SQUARE_FIT_SIZE = 300 import os from PIL import Image SQUARE_FIT_SIZE = 300 LOGO_FILENAME = 'catlogo.png' logoIm = Image.open(LOGO_FILENAME) logoWidth, logoHeight = logoIm.size os.makedirs('withLogo', exist_ok=True) #TODO: loop over all files for filename in os.listdir('.'): if not (filename.endswith('.png') or filename.endswith('.jpg')) or filename == LOGO_FILENAME: continue im = Image.open(filename) width, height = im.size #TODO: Resize the logo. print(f'Resizing logo to fit {filename}...') sLogo = logoIm.resize((int(width / 5), int(height / 5))) sLogoWidth, sLogoHeight = sLogo.size #TODO: Add logo print('Dodanie logo do obrazu %s...' % (filename)) im.paste(sLogo, (width - sLogoWidth, height - sLogoHeight), sLogo) # TODO: check if there is a need to resize picture if width &gt; SQUARE_FIT_SIZE and height &gt; SQUARE_FIT_SIZE: # TODO: count new width and height if width &gt; height: height = int((SQUARE_FIT_SIZE / width) * height) width = SQUARE_FIT_SIZE else: width = int((SQUARE_FIT_SIZE / height) * width) height = SQUARE_FIT_SIZE # TODO: change image size print('Zmiana wielkości obrazu %s...' % (filename)) im = im.resize((width, height)) #TODO: save images im.save(os.path.join('withLogo', filename))
type: Answer

http://stackoverflow.com/comment/91162628
comment on: http://stackoverflow.com/q/52105332
score: 0
type: Comment
type: QuestionComment
has text: Welcome to Stack Overflow! Please take the tour and read through the help center, in particular [how-to-ask](https://stackoverflow.com/help/how-to-ask) Your best bet here is to do your research, search for related topics on SO, and give it a go. If you get stuck and can't get unstuck after doing more research and searching, post a [Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve) example of your attempt and say specifically where you're stuck. People will be glad to help.

http://stackoverflow.com/q/52031799
tagged with: django-rest-framework
has answer: http://stackoverflow.com/a/52049474
has comment: http://stackoverflow.com/comment/91016054
type: UnansweredQuestion
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/91016793
has comment: http://stackoverflow.com/comment/91015476
has comment: http://stackoverflow.com/comment/91015595
score: 0
has comment: http://stackoverflow.com/comment/91016106
type: Question
has title: Checking if relationship exists with query
has body: I am trying to check whether or not a following relationship exists using a query. First, I get all of the followers the user has and then I check whether or not the user follows those followers. Here are my models: class Following(models.Model): target = models.ForeignKey('User', related_name='followers', on_delete=models.CASCADE, null=True) follower = models.ForeignKey('User', related_name='targets', on_delete=models.CASCADE, null=True) created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return '{} is followed by {}'.format(self.target, self.follower) class User(AbstractBaseUser): username = models.CharField(max_length=15, unique=True) email = models.EmailField(max_length=100, unique=True) I am using the Django Rest-Framework so I go to the specific URL to get the information I need. After going to the URL, the output is expected. I get all the followers the user has. views.py class GetFollowersView(ListAPIView): serializer_class = FollowingSerializer def get_queryset(self): requested_user = get_requested_user(self) return User.objects.filter(targets__target=requested_user).order_by('-targets__created_at'). \ annotate(is_following=Count('followers__follower', filter=Q(followers__follower=requested_user), distinct=True)) def get_requested_user(self): filter_kwargs = {'username': self.kwargs['username']} return get_object_or_404(User.objects.all(), **filter_kwargs) serializers.py class FollowingSerializer(serializers.ModelSerializer): is_following = serializers.IntegerField() class Meta: model = User fields = ('id', 'username', 'follower_count', 'following_count', 'is_following') However, the problem is in the is_following annotation. I'd like to see whether or not the user follows each specific follower. If they follow that follower, then is_following should be 1 if not, then it is a 0. I'm getting incorrect results in is_following is there a way I can check if the user follows each specific follower?
has answer: http://stackoverflow.com/a/52049830
tagged with: django-models
answer count: 2

http://stackoverflow.com/comment/91150120
score: 1
has text: Wrap the result with `islice(result, 0, 2)`
type: QuestionComment
comment on: http://stackoverflow.com/q/52099650
type: Comment

http://stackoverflow.com/comment/130442471
type: Comment
comment on: http://stackoverflow.com/a/57991282
has text: This worked for me, followed ```pip install pyaudio```
type: AnswerComment
score: 0

http://stackoverflow.com/comment/91628481
score: 0
has text: Thanks! Will try over the weekend and will assign the score. One more question: X axes do not plot values (in this case like "1950-02". I tried many ways including xticks with np.arange(start, finish, stepwise) but can get those data labels displayed in a good way (either like in your case just says month or a date OR lists everything so it is unreadable). Any idea?
comment on: http://stackoverflow.com/a/52095244
type: AnswerComment
type: Comment

http://stackoverflow.com/a/52018952
answers question: http://stackoverflow.com/q/52018789
type: Answer
has body: In this way, b would be ["f", "e", "d"] and the indexes of that elements are 0,1,2. You can create b in this way, though: b = [a.index(a[5]), a.index(a[4]), a.index(a[3])] Otherwise, if you want indexes and values you can use a dictionary: b = {a[3]: a.index(a[3]), a[4]: a.index(a[4]),a[3]: a.index(a[3])}
score: 0

http://stackoverflow.com/a/52048179
score: 0
has body: If there are lots and lots of lines in your file, I believe you should consider using f.readline() (without an s) 27 times, and only save your lines starting wherever you want. :) Else, the other ones solution is what I would have done too (meaning : f.readlines()[23:28]. 28, because as far as I remember, outer range is excluded.
answers question: http://stackoverflow.com/q/52048125
type: Answer

pyalgotrade
tag name: pyalgotrade
tags question: http://stackoverflow.com/q/52083840
type: Tag

http://stackoverflow.com/comment/91047046
type: Comment
type: QuestionComment
has text: @DanMašek I would agree with you but my classifier picks the pixel that should be null up as white (255,255,255)
comment on: http://stackoverflow.com/q/52046064
score: 0

http://stackoverflow.com/comment/90941573
comment on: http://stackoverflow.com/a/51996037
type: AnswerComment
score: 0
has text: I've never tried it, but I would be surprised if these pretrained classification nets could get by without using color context. I'd be curious to see the accuracy difference on imagenet test data between the two cases (1) use rgb test data, and (2) use 3 channel test data resulting from converting rgb 3 channel test data to 1 channel gray, then stacking it to 3 channel gray like Djib and Prune suggested. If you weren't getting massive loss in accuracy on test data when you throw away the color info OP, I'd say it'll work without retraining
type: Comment

http://stackoverflow.com/a/69506793
answers question: http://stackoverflow.com/q/52045540
type: Answer
upvote count: 1
has body: It is in demo #6 in https://github.com/MIT-LCP/wfdb-python/blob/master/demo.ipynb. I tried and it works very well. # import library import wfdb # assign signals as ECG array from 0 to 1500 as your expected range, fields as other information signals, fields = wfdb.rdsamp(r"C:\folder\MIT\100", sampto=1500) # Plot with the array signals, fs as frequency (can be founds in fields['fs'], and title as an optional wfdb.plot_items(signal=signals, fs=fields['fs'], title='Huy Test') # Display it with the additional information display((signals, fields))
has comment: http://stackoverflow.com/comment/122855481
score: 1
downvote count: 0

http://stackoverflow.com/q/52048345
tagged with: python
has comment: http://stackoverflow.com/comment/91047727
type: Question
has comment: http://stackoverflow.com/comment/91081811
has title: df.set_index returns key error python pandas dataframe
tagged with: dataframe
has body: I have this Pandas DataFrame and I have to convert some of the items into coordinates, (meaning they have to be floats) and it includes the indexes while trying to convert them into floats. So I tried to set the indexes to the first thing in the DataFrame but it doesn't work. I wonder if it has anything to do with the fact that it is a part of the whole DataFrame, only the section that is "Latitude" and "Longitude". df = df_volc.iloc(axis = 0)[0:, 3:5] df.set_index("hello", inplace = True, drop = True) df and I get the a really long error, but this is the last part of it: KeyError: '34.50' if I don't do the set_index part I get: Latitude Longitude 0 34.50 131.60 1 -23.30 -67.62 2 14.50 -90.88 I just wanna know if its possible to get rid of the indexes or set them.
score: 0
tagged with: pandas
answer count: 1
has answer: http://stackoverflow.com/a/52048621
type: UnansweredQuestion

http://stackoverflow.com/a/52055467
answers question: http://stackoverflow.com/q/52055318
has body: Using ne of the emp_no column and using the slice of df1 dataframe. df1.loc[df1['emp_no'].ne(df2['emp_no']),:] emp_no no_children status 2 23 5 5
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/91061177
downvote count: 0
type: Answer
upvote count: 2
has comment: http://stackoverflow.com/comment/91061070
accepted answer of: http://stackoverflow.com/q/52055318
score: 2

http://stackoverflow.com/a/52062776
score: 5
type: Answer
has body: Django tags are surrounded with {% and %} (variables with {{ and }} but let us ignore that for now). But in your code, except for the first {% if ... %} statement, you consistently write: { % endif % } Notice the space between the { and the %, Django will not parse this as Django tags. You thus should remove the spaces such that the tag reads: {% endif %} You thus should fix the tags to: {% if tag.startup_set.all %} Startup Tag is associated with {{ tag.startup_set.count }} startup {% for startup in tag.startup_set.all %} { { startup.name } } {% endfor %} {% endif %} {% if tag.blog_posts.all %} Blog Post { { tag.blog_posts.count|pluralize } } {% for post in tag.blog_posts.all %} { { post.title|title } } {% endfor %} {% endif %} {% if not tag.startup_set.all and not tag.blog_posts.all %} This tag is not related to any content. {% endif %} I would also advice to avoid writing queries (and other business logic) into templates. Usually this is more the task of the view.
upvote count: 5
downvote count: 0
answers question: http://stackoverflow.com/q/52062691

http://stackoverflow.com/a/52084037
has body: Short answer: yes. Just tried a slightly modified version of your code with prints. class Parent: def method1(self): print("Parent method1") def method2(self): print("Parent method2") self.method1() class Child(Parent): def method1(self): print("Child method1") def method2(self): print("Child method2") super().method2() c = Child() c.method2() This is the output: Child method2 Parent method2 Child method1 As you can see, the method1 used is the child one.
downvote count: 0
answers question: http://stackoverflow.com/q/52083862
score: 6
type: Answer
upvote count: 6

http://stackoverflow.com/comment/90899201
type: QuestionComment
comment on: http://stackoverflow.com/q/51974341
type: Comment
score: 2
has text: Who is "someone", why are they appending these unwanted items to the list, and why do you want the list itself to be responsible for ignoring those items?

http://stackoverflow.com/comment/90971893
score: 0
has text: If we can't see the code in a context where it's a good idea to search for such performance gains, then such answers are just encouraging micro-optimization. **Not helpful for the site**. Do you want all beginners to start putting `seen_add = seen.add` everywhere because they heard that it was faster on stack overflow? Just my [unpopular] opinion.
type: Comment
comment on: http://stackoverflow.com/a/52010315
type: AnswerComment

http://stackoverflow.com/a/51989032
has body: You can use pandas: import pandas as pd indexList = [5,3,2,2,7,1] valueList = [1,2,3,4,5,6] s = pd.Series(valueList, index= indexList) s = s.groupby(s.index).sum().reindex(np.arange(s.index.min(), s.index.max()+1), fill_value=0) print(s.index.tolist()) print(s.tolist()) Output: [1, 2, 3, 4, 5, 6, 7] [6, 7, 2, 0, 1, 0, 5] Details Create a pandas series using valuesList as the data and indexList as the index of the series. Use groupby with sum to combine like indexes summing the value. Next, reindex the series from the min of the series index to the max of the series index and use fill_value parameter to fill missing indexes with 0 values. Print series index tolist. Print series values tolist.
answers question: http://stackoverflow.com/q/51988800
score: 3
upvote count: 3
has comment: http://stackoverflow.com/comment/90936575
downvote count: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/90936000
type: Answer
accepted answer of: http://stackoverflow.com/q/51988800

http://stackoverflow.com/comment/90939065
comment on: http://stackoverflow.com/q/51991891
score: 0
type: Comment
type: QuestionComment
has text: *\* ALPN, server did not agree to a protocol*. Maybe the server's *SSL* implementation doesn't know *ALPN*? Try building *OpenSSL* without *ALPN* support (if possible), or use an older version (e.g. *1.0.1* - which is no longer supported).

http://stackoverflow.com/comment/90974784
has text: I want to create a dictionary like like: my_dict={"Li":[[' phd.', 'Associate Professor of Biostats'], [' MPH','Professor of DCD']] 'Chiou': ' MD', 'Professor of ABC'
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/52011846

reserved-words
tag name: reserved-words
type: Tag
tags question: http://stackoverflow.com/q/51992442

http://stackoverflow.com/a/52133209
upvote count: 2
type: AcceptedAnswer
has body: The first step that I took was to create an object who can distribute a maximum of n coins every t ms. import time class CoinsDistribution: """Object that distribute a maximum of maxCoins every timeLimit ms""" def __init__(self, maxCoins, timeLimit): self.maxCoins = maxCoins self.timeLimit = timeLimit self.coin = maxCoins self.time = time.perf_counter() def getCoin(self): if self.coin &lt;= 0 and not self.restock(): return False self.coin -= 1 return True def restock(self): t = time.perf_counter() if (t - self.time) * 1000 &lt; self.timeLimit: return False self.coin = self.maxCoins self.time = t return True Now we need a way of forcing function to only get called if they can get a coin. To do that we can write a decorator function that we could use like that: @limitCalls(callLimit=1, timeLimit=1000) def uniqFunctionRequestingServer1(): return 'response from s1' But sometimes, multiple functions are calling requesting the same server so we would want them to get coins from the the same CoinsDistribution object. Therefor, another use of the decorator would be by supplying the CoinsDistribution object: server_2_limit = CoinsDistribution(3, 1000) @limitCalls(server_2_limit) def sendRequestToServer2(): return 'it worked !!' @limitCalls(server_2_limit) def sendAnOtherRequestToServer2(): return 'it worked too !!' We now have to create the decorator, it can take either a CoinsDistribution object or enough data to create a new one. import functools def limitCalls(obj=None, *, callLimit=100, timeLimit=1000): if obj is None: obj = CoinsDistribution(callLimit, timeLimit) def limit_decorator(func): @functools.wraps(func) def limit_wrapper(*args, **kwargs): if obj.getCoin(): return func(*args, **kwargs) return 'limit reached, please wait' return limit_wrapper return limit_decorator And it's done ! Now you can limit the number of calls any API that you use and you can build a dictionary to keep track of your CoinsDistribution objects if you have to manage a lot of them (to differr…
type: Answer
score: 2
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52004801
answers question: http://stackoverflow.com/q/52004801

http://stackoverflow.com/a/52031636
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/52031590
answers question: http://stackoverflow.com/q/52031590
type: Answer
has body: May be I don't know what you real want,because I know that little, I think You can use QtDesigner,it's very useful
score: 0

http://stackoverflow.com/comment/90994059
type: QuestionComment
comment on: http://stackoverflow.com/q/52021621
score: 1
has text: Please provide a **[mcve]**. Here that means fix your code indentation, provide some input data, show your current/desired output for that input data. No images/links, just text.
type: Comment

http://stackoverflow.com/q/52056943
score: 2
tagged with: python-3.x
type: UnansweredQuestion
tagged with: string-formatting
has answer: http://stackoverflow.com/a/52057589
type: Question
has title: Force 'general' string formatting in Python for low exponents
answer count: 1
downvote count: 1
has body: General formatting in Python rounds the number to p significant digits and prints as a float (%f) if the exponent exp is between -4 &lt;= exp &lt; p, otherwise it prints in scientific exponent notation (%e). For example: &gt; '{0:0.8G}'.format(10000000) '10000000' &gt; '{0:0.8G}'.format(0.000001) '1E-06' Why does this condition only allow you to specify the upper exponent limit precision, whereas the lower exponent limit is fixed at -4? Is there any way of forcing string formatting to print the full number for low exponents?
tagged with: string
tagged with: number-formatting
favorite count: 0
upvote count: 3
tagged with: python

http://stackoverflow.com/comment/91149165
type: Comment
has text: There is a situation in which it is failing though. If a number has a comma. Like '1,222'. How do we get around that?
comment on: http://stackoverflow.com/a/52097927
score: 0
type: AnswerComment

http://stackoverflow.com/comment/91111355
type: Comment
comment on: http://stackoverflow.com/a/52080465
has text: The statement "You also don't need `== True` in an `if` block" is true in many contexts, but given that we know little about `dig_sum` and `con_test`, it is rather bold. `if x:` and `if x == True:` test very different things.
type: AnswerComment
score: 0

http://stackoverflow.com/q/51993679
favorite count: 0
has comment: http://stackoverflow.com/comment/90937035
type: UnansweredQuestion
tagged with: python
has title: PyQt5 - Dynamically created widget doesn't show - No layout
tagged with: pyqt5
type: Question
has body: I have a widget that is an area where graphs will be created by the user, with the nodes being other widgets. The graph area code is roughly this: class GraphArea(QtWidgets.QFrame): def __init__(self, parent=None): super(GraphArea, self).__init__(parent) self.setObjectName('GraphArea') self.parent = parent self.add_widget = None There is a function called when the user adds a new node (I call them Entities): def create_widget(self, add_info, x, y): self.add_widget = Entity(self, add_info[1], add_info[2], 1) self.add_widget.move(x, y) Nothing special. Problem is, the created widget is invisible. It is there though, size and position, just not located in the GraphArea. When I tried to use a layout everything worked fine. Am I missing something obvious? Note that when I pasted the "create" code in the __init__ function, it worked properly. The problem seems to be when the UI has been initialized and trying to add the widget in the GraphArea at a random time.
has answer: http://stackoverflow.com/a/51994151
score: 0
upvote count: 1
tagged with: pyqt
answer count: 1
downvote count: 1

http://stackoverflow.com/comment/90899211
score: 1
has text: Have you tried subclassing `list?
comment on: http://stackoverflow.com/q/51974341
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/90877274
has text: Apologies, I misread the question. I've updated with a better answer.
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51963054

http://stackoverflow.com/comment/91014845
has text: Yeah, if I was using the threading, but it's not; the threading points are commented out: it's calling the submit function directly, and then writing the file, and then moving to the next piece. It happens on the last section: the 230 / 235 line(s).
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52032290
score: 1

http://stackoverflow.com/q/52097896
has comment: http://stackoverflow.com/comment/91146112
has title: Find indices of values in a list
tagged with: python
has body: I am trying to find the indices of the integers in a list. I have a following code that works but it takes over 45 seconds. Is there a faster way that I can use? My code looks like following: for i in range(0,len(output)) : indexes = [ii for ii,x in enumerate(Node1ID) if x == i].
has answer: http://stackoverflow.com/a/52098197
type: AnsweredQuestion
score: 3
upvote count: 3
has answer: http://stackoverflow.com/a/52099113
type: Question
possible better answer: http://stackoverflow.com/a/52099113
accepted answer: http://stackoverflow.com/a/52098197
tagged with: python-2.7
answer count: 2
downvote count: 0
favorite count: 0

webrtc
tags question: http://stackoverflow.com/q/52001578
type: Tag
tag name: webrtc

http://stackoverflow.com/comment/90990616
score: 0
type: Comment
has text: does np.matmul(a,b) also means the same thing ?
type: AnswerComment
comment on: http://stackoverflow.com/a/52017898

http://stackoverflow.com/comment/91026428
has text: Do you care about the order?
comment on: http://stackoverflow.com/q/52038053
type: Comment
type: QuestionComment
score: 1

http://stackoverflow.com/comment/91088103
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52066346
has text: I get what looks like a lot of errors when I try this command: `pip3 install hg+http://bitbucket.org/pygame/pygame` it's too long a message to include in here, how should I post it ?

http://stackoverflow.com/comment/91117224
type: Comment
type: QuestionComment
has text: To clarify, you aren't trying to delete the key "taxi_drivers" - just set the value to NULL?
comment on: http://stackoverflow.com/q/52081498
score: 0

http://stackoverflow.com/comment/91034362
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/52041668
has text: so when lists have a lot of items and don't know which one of the two lists has the extras that need to be removed how do we proceed for both lists with the filter operation?
score: 0

http://stackoverflow.com/q/52054905
tagged with: sqlite
answer count: 1
has comment: http://stackoverflow.com/comment/91061217
accepted answer: http://stackoverflow.com/a/52055967
tagged with: python
has comment: http://stackoverflow.com/comment/91061709
type: AnsweredQuestion
has title: Select in Sqlite3
tagged with: django
type: Question
has comment: http://stackoverflow.com/comment/91060289
has body: I am using the select in sqlite3 statement to get rows from django db (default db) p=connection.cursor().execute("SELECT * FROM webapp_information WHERE dat BETWEEN date('now', 'start of day') AND date('now', 'localtime');") a=p.fetchall() for i in a: print(i)` i get the dat(date field) from db but it returns nothing. I tried in different way- In [206]: p=connection.cursor().execute("SELECT * FROM webapp_information WHERE dat='2018-08-28';") It returns with a empty list, however I pretty sure the date are stored in the it. Any help? thank you in advance. Modules.py from __future__ import unicode_literals from django.db import models import datetime # Create your models here. class information(models.Model): login=models.CharField(max_length=100,) idd=models.CharField(max_length=100,) avatar_url=models.CharField(max_length=100,default='nll',null=True) gravatar_id=models.CharField(max_length=100,default='nll',null=True) url=models.CharField(max_length=100, default='nll',null=True) html_url=models.CharField(max_length=100,default='nll',null=True) followers_url=models.CharField(max_length=100,default='nll',null=True) following_url=models.CharField(max_length=100,default='nll',null=True) gists_url=models.CharField(max_length=100,default='nll',null=True) starred_url=models.CharField(max_length=100,default='nll',null=True) subscriptions_url=models.CharField(max_length=100,default='nll',null=True) organizations_url=models.CharField(max_length=100,default='nll',null=True) repos_url=models.CharField(max_length=100,default='nll',null=True) events_url=models.CharField(max_length=100,default='nll',null=True) received_events=models.CharField(max_length=100,default='nll',null=True) typ=models.CharField(max_length=100,default='nll',null=True) site_admin=models.CharField(max_length=100,default='nll',null=True) name=models.CharField(max_length=100,default='nll',null=True) company=models.CharField(max_length=100,default='nll',null=True) blog=models.CharField(max_length=100,default='nl…
linked to: http://stackoverflow.com/q/14972802
has comment: http://stackoverflow.com/comment/91060195
has answer: http://stackoverflow.com/a/52055967
has comment: http://stackoverflow.com/comment/91061535
tagged with: django-models
score: 0

http://stackoverflow.com/q/51981089
score: 3
tagged with: http://stackoverflow.com/tag/json
has comment: http://stackoverflow.com/comment/90915466
has comment: http://stackoverflow.com/comment/90914819
tagged with: python-2.7
answer count: 2
has body: I'm porting a Python 2 application to Python 3. Currently running Python2.7 but, updating code to pass pylint --py3k tests, I have run into a problem with this: def json_resource_file(baseurl, jsondata, resource_info): """ Return a file object that reads out a JSON version of the supplied entity values data. """ response_file = StringIO() json.dump(jsondata, response_file, indent=2, separators=(',', ': '), sort_keys=True) response_file.seek(0) return response_file It works fine with: from StringIO import StringIO but StringIO.StringIO doesn't exist in Python3 (according to pylint), so using: from io import StringIO I get an error: "TypeError: unicode argument expected, got 'str'" (This is running under Python 2 - I'm still preparing the ground, so to speak, and am not planning to use Python 3 until I have done as much preparation and testing as I can under Python 2.) By way of some experimentation, I tried using BytesIO from io, but that gives a different error "TypeError: 'unicode' does not have the buffer interface". Clearly, the Python2 version of json.dump is writing str values to the supplied file object. I think the Python3 version of json.dump also writes str (i.e. Unicode) values. So my question is: is there an easy way to dump JSON to a StringIO memory buffer that works with Python 2 and 3? Notes I realize I could use json.dumps and coerce the result to whatever type StringIO expects, but that all seems rather heavy-handed. I'm also using the following future imports as part of my porting process: from __future__ import (unicode_literals, absolute_import, division, print_function) Currently, a solution I'm thinking of is to test the python version and import a different version of StringIO accordingly, but that would violate the "Use feature detection instead of version detection" principle. In most of my code, using from io import StringIO appears to work fine for situations that I use StringIO. It's the specific case of using a StringIO with json.dump tha…
has comment: http://stackoverflow.com/comment/90915108
downvote count: 0
has comment: http://stackoverflow.com/comment/90914646
favorite count: 0
has answer: http://stackoverflow.com/a/55595468
possible better answer: http://stackoverflow.com/a/51981847
has comment: http://stackoverflow.com/comment/90915768
has answer: http://stackoverflow.com/a/51981847
has title: Porting json.dump into StringIO code to python 3
tagged with: python
type: AnsweredQuestion
tagged with: python-3.x
tagged with: stringio
upvote count: 3
has comment: http://stackoverflow.com/comment/90913333
has comment: http://stackoverflow.com/comment/90912327
accepted answer: http://stackoverflow.com/a/55595468
type: Question

http://stackoverflow.com/comment/90922191
type: QuestionComment
comment on: http://stackoverflow.com/q/51986378
score: 0
type: Comment
has text: I found decorators but i cant find a way with them to call the second part (self.csn(1)) with a decorator. As i understood them they wil call a function in the end but maybe i just didnt understand them right

http://stackoverflow.com/q/52028288
type: UnansweredQuestion
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/91007037
has comment: http://stackoverflow.com/comment/91006990
has comment: http://stackoverflow.com/comment/91006964
type: Question
has comment: http://stackoverflow.com/comment/91006938
has title: Passing per_page values dynamically for each page in Paginator class
upvote count: 1
has body: how can I pass per_page_count=[8,10,9,10,10] to Paginator class . I have a sorted_query_list which is passed to Paginator class but for per_page value each query can have different per_page_count. So a list is generated for each query (i.e per_page_count) containing number of rows to be shown in each page in sequential manner So result should have 8 rows for 1st page , 10 rows for 2 , 9 rows for 3 page , 10 rows for 4 page and so on . per_page_count=[8,10,9,10,10] for rows_per_page in per_page_count : result = Paginator(sorted_query_list, rows_per_page ) ^ Obviously this doesn't works ! Note: per_page_count can have different value for different sorted_query_list
downvote count: 1
tagged with: paginator
favorite count: 0
has comment: http://stackoverflow.com/comment/91007225
score: 0
answer count: 0

http://stackoverflow.com/comment/91140117
score: 1
comment on: http://stackoverflow.com/q/52094979
type: Comment
has text: Have you tried google?
type: QuestionComment

http://stackoverflow.com/q/52026191
tagged with: python
accepted answer: http://stackoverflow.com/a/52049174
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91025937
tagged with: pyside
has comment: http://stackoverflow.com/comment/91003077
type: Question
has body: I am learning Python/PySide for Maya from time to time and today I tried to make a class with PySide. I am trying to make a window with an empty list inside. I have done the same code structure with usual Maya commands for UI and it worked. But when I tried to do same with PySide, I got AttributeError: 'VL_Test' object has no attribute 'ui_fk' error. What am I missing? Code: import maya.cmds as cmds import maya.OpenMayaUI as omui try: from PySide import QtCore, QtWidgets, QtGui from shiboken import wrapInstance except: from PySide2 import QtCore, QtWidgets, QtGui from shiboken2 import wrapInstance def getMayaWindow(): pointer = omui.MQtUtil.mainWindow() if pointer is not None: return wrapInstance(long(pointer), QtWidgets.QWidget) class VL_Test(object): def showUI(cls): win = cls() win.create() return win def __init__(self): self.window = 'vl_test' self.title = 'Test Remastered' self.size = (1000,650) self.supportsToolAction = False self.actionName = 'Create and Close' self.applyName = 'Create' self.closeName = 'Close' def create(self): if cmds.window(self.window, exists= True): cmds.deleteUI(self.window ,window= True) self.parentWindow = getMayaWindow() self.mainWindow = QtWidgets.QMainWindow(self.parentWindow) self.mainWindow.setObjectName(self.window) self.mainWindow.setWindowTitle(self.title) self.mainWidget = QtWidgets.QWidget() self.mainWindow.setCentralWidget(self.mainWidget) QtWidgets.QStyleFactory.create('Windows') self.mainLayout = QtWidgets.QHBoxLayout(self.mainWidget) self.ui_fk() self.mainWindow.show() def ui_fk(self): self.fkStrandGroupBox = QtWidgets.QGroupBox('FK Joints:') self.fkStrandLayout = QtWidgets.QHBoxLayout() self.mainLayout.addWidget(fkStrandGroupBox) self.fkStrandGroupBox.setLayout(fkStrandLayout) self.fkListWidget = QtWidgets.QListWidget() self.fkStrandLayout.addWidget(fkListWidget) testWindow = VL_Test() testWindow.create()
has title: Class can't find attribute I am specifying(PySide, Maya)
score: 0
has answer: http://stackoverflow.com/a/52049174
tagged with: pyqt
answer count: 1
tagged with: maya
has comment: http://stackoverflow.com/comment/91002702

http://stackoverflow.com/comment/91200843
comment on: http://stackoverflow.com/q/51962001
has text: I was doing a course on ML on GCP, so one of the challenge was this question ...
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91151595
comment on: http://stackoverflow.com/a/52100343
score: 0
type: AnswerComment
has text: That was my first thought, and tried using time.sleep(1). Maybe It wasnt enough. Your approach is much better, I Will try It later thanks :)
type: Comment

http://stackoverflow.com/q/51974293
upvote count: 6
accepted answer: http://stackoverflow.com/a/51974867
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90899134
tagged with: methods
type: Question
has answer: http://stackoverflow.com/a/51974509
downvote count: 0
has comment: http://stackoverflow.com/comment/90899074
possible better answer: http://stackoverflow.com/a/51974494
has answer: http://stackoverflow.com/a/51974494
has comment: http://stackoverflow.com/comment/90899378
answer count: 3
has answer: http://stackoverflow.com/a/51974867
has comment: http://stackoverflow.com/comment/90899108
favorite count: 0
has body: I am new to Python from R. I have recently spent a lot of time reading up on how everything in Python is an object, objects can call methods on themselves, methods are functions within a class, yada yada yada. Here's what I don't understand. Take the following simple code: mylist = [3, 1, 7] If I want to know how many times the number 7 occurs, I can do: mylist.count(7) That, of course, returns 1. And if I want to save the count number to another variable: seven_counts = mylist.count(7) So far, so good. Other than the syntax, the behavior is similar to R. However, let's say I am thinking about adding a number to my list: mylist.append(9) Wait a minute, that method actually changed the variable itself! (i.e., "mylist" has been altered and now includes the number 9 as the fourth digit in the list.) Assigning the code to a new variable (like I did with seven_counts) produces garbage: newlist = mylist.append(9) I find the inconsistency in this behavior a bit odd, and frankly undesirable. (Let's say I wanted to see what the result of the append looked like first and then have the option to decide whether or not I want to assign it to a new variable.) My question is simple: Is there a way to know in advance if calling a particular method will actually alter your variable (object)?
score: 6
has title: How do you know in advance if a method (or function) will alter the variable when called?
tagged with: python

http://stackoverflow.com/a/52086746
answers question: http://stackoverflow.com/q/52086658
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/91124655
accepted answer of: http://stackoverflow.com/q/52086658
type: Answer
upvote count: 2
score: 2
has body: Looks like a simple assign will do it. A1 = df.assign(Vega=df['Gamma']) print (A1) Alpha Beta Gamma Delta Vega 2012-01-01 -2.695081 -1.934733 0.892127 -0.895014 0.892127 2012-01-02 -0.911289 0.714030 0.531698 1.435397 0.531698 2012-01-03 -1.374162 1.517784 0.321945 1.268438 0.321945 2012-01-04 -0.103294 -0.483923 -0.661366 -0.829013 -0.661366 2012-01-05 -2.700309 0.601139 1.940421 -0.489158 1.940421
has comment: http://stackoverflow.com/comment/91124022

http://stackoverflow.com/comment/91328910
type: Comment
comment on: http://stackoverflow.com/a/52100502
has text: If row is a list then you need to pass in the index of the list that contains the datetime object. So if the list only contains one thing, i.e. `[datetime.datetime(2003, 6, 3, 0, 0)]` then you would use `row[0]`. So then your code would be `dtm = row[0].strftime('%Y/%m/%d %H:%M')`
type: AnswerComment
score: 0

http://stackoverflow.com/q/52010639
answer count: 3
tagged with: flask
has title: Flask Flash message not showing after redirecting to the same page
favorite count: 0
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/html
tagged with: python
has answer: http://stackoverflow.com/a/64237356
downvote count: 1
type: Question
has answer: http://stackoverflow.com/a/52010968
upvote count: 5
has answer: http://stackoverflow.com/a/52106775
score: 4
has body: I have a simple web page where the user selects a file from their computer and then presses an "Upload" button, after which a python script will be initiated with that file as an input. However, I'm trying to get it so that if the user is uploading a file that will throw an error, a Flash message will show on the same page (without any redirection). In my current attempt, the flash message isn't showing when I choose to upload a purposefully erroneous file. Also, as another question, is it possible to (within app.py) check for certain backend python error messages that will arise once I initiate the script (the ones that will show in the terminal)? Anyways, here is the relevant code: app.py: @app.route("/", methods=['GET', 'POST']) def upload(): if request.method == 'POST': if 'file' not in request.files: flash("No file chosen", 'danger') return redirect(request.url) file = request.files['file'] if file.filename == '': flash('No selected file', 'danger') return redirect(request.url) elif not allowed_file(file.filename): flash('Incorrect file extenstion. Must be .TXT!', 'danger') return redirect(request.url) elif file: filename = secure_filename(file.filename) file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename)) # # Process the file (omitted here) # proc = subprocess.Popen('python author_script.py {} -p {} -s {} -m {}'.format(file.filename, period, space, affiliation), shell=True, stdout=subprocess.PIPE) time.sleep(0.5) return redirect(url_for('results')) else: # THIS PART IS NOT WORKING! return redirect(request.path) flash('There is an affiliation missing from your Place list.', 'danger') return render_template('index.html', template_file=app.config['TEMPLATE_FILE']) html template (layout.html): Author Script {% include 'includes/_navbar.html' %} {% block body %}{% endblock %} {% with messages = get_flashed_messages(with_categories=true) %} {% if messages %} {% for category, message in messages %} {{ message }} {% endfor %} {% endif %} {% endwith %}

signal-processing
tags question: http://stackoverflow.com/q/51992154
type: Tag
tags question: http://stackoverflow.com/q/52029864
tags question: http://stackoverflow.com/q/52047639
tags question: http://stackoverflow.com/q/51985853
tag name: signal-processing

http://stackoverflow.com/q/52015673
type: Question
has body: I am trying to return the selected choice value from a dropdown menu in django. The option (in html) is dynamically populated from the database's model primary key. HTML Select student ID {% for student_data in students_data %} {{ student_data.pk }} {% endfor %} views.py students_data = Student.objects.all() search_result = NewStudentSearchForm(request.POST) if 'search_result' in request.POST: test_print_to_screen = search_result['student_select'] print(test_print_to_screen) args = {'students_data': students_data} return render(request, 'static/html/new_coach_schedule.html', args) else: return render(request, 'static/html/new_coach_schedule.html', args) forms.py class NewStudentSearchForm(forms.Form): search_field = forms.CharField(max_length=50) # This is for something else. student_select = forms.ModelChoiceField(queryset=Student.objects.all(), empty_label=None) When I make use of ModelChoiceField, test_print_to_screen does not print out the selected choice that I chose in the html select box.. It prints out everything instead. EG: Student object (5) Student object (6) Student object (7) Student object (8) Student object (9) Student object (10) Student object (11) Student object (12) Student object (13) How can I go about in my forms.py so that when i select the value in my browser, it will return / print out the selected choice back to me? Update As per the comments, I updated my views.py file to include cleaned_data as follows: if 'search_result' in request.POST: search_result = NewCoachSearchForm(request.POST) print(search_result) if search_result.is_valid(): test = search_result.cleaned_data['student_select'] print(test) else: print(search_result.errors) However, this produces a stacktrace error: student_select This field is required.
has comment: http://stackoverflow.com/comment/90981717
has comment: http://stackoverflow.com/comment/90981641
score: 0
has answer: http://stackoverflow.com/a/52015750
answer count: 1
has title: django forms print select values
tagged with: django
tagged with: python
accepted answer: http://stackoverflow.com/a/52015750
type: AnsweredQuestion

http://stackoverflow.com/q/52012667
has answer: http://stackoverflow.com/a/52039686
type: Question
score: 0
has comment: http://stackoverflow.com/comment/90976449
answer count: 1
tagged with: keras
has title: Cannot install keras-pandas on Ubuntu due to error message
tagged with: python
type: UnansweredQuestion
tagged with: pip
has body: I am able to download Keras through pip easily, but it didn't come with keras-pandas and when I run pip install -U keras-pandas I get the following error message: Complete output from command python setup.py egg_info: Traceback (most recent call last): File "&lt;string&gt;", line 1, in &lt;module&gt; File "/tmp/pip-req-build-lw952foh/setup.py", line 12, in &lt;module&gt; with open('requirements.txt') as f: FileNotFoundError: [Errno 2] No such file or directory: 'requirements.txt' I looked for the file, and didn't find anything, I've upgraded pip which didn't help, I just keep getting the same error code. How do I fix this bug?
tagged with: ubuntu

http://stackoverflow.com/q/52048331
has title: Removing Duplicate Tuple Pairs by Condition
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/52048447
has comment: http://stackoverflow.com/comment/91071309
score: 2
downvote count: 0
has answer: http://stackoverflow.com/a/52048358
has comment: http://stackoverflow.com/comment/91047523
favorite count: 0
has answer: http://stackoverflow.com/a/52048366
type: Question
tagged with: python
has comment: http://stackoverflow.com/comment/91047450
has body: How do you remove duplicate tuples from a list based on the condition that if (Y, Z) and (Z, Y) are part of the list, then we only keep the match where Y &lt; Z? For example, if we start with the following list of Car ID pairs: CarID1 = [(100, 500), (100, 600), (100, 700), (500, 100), (500, 200)], then we should remove the (500, 100 entry and end up with: CarID2 = [(100, 500), (100, 600), (100, 700), (500, 200)] I tried the following code to grab unique tuples, but it did not do what I described. y = np.unique(x, axis=0) z = [] for i in y: z.append(tuple(i))
upvote count: 2
has comment: http://stackoverflow.com/comment/91047537
answer count: 3
tagged with: numpy
has comment: http://stackoverflow.com/comment/91047625

lemmatization
type: Tag
tags question: http://stackoverflow.com/q/51958973
tag name: lemmatization

http://stackoverflow.com/comment/91097477
type: QuestionComment
has text: please properly indent your code. insert code of `optimize` function.
score: 1
comment on: http://stackoverflow.com/q/52069454
type: Comment

http://stackoverflow.com/comment/91291568
type: AnswerComment
comment on: http://stackoverflow.com/a/52083948
has text: If you have free time do look at it. Thank you :)
type: Comment
score: 0

http://stackoverflow.com/a/51977538
has comment: http://stackoverflow.com/comment/90905596
type: AcceptedAnswer
downvote count: 0
has body: You can just use .find() instead of .findAll() to get the first match: soup.find('tr', {'class': 'last'}).get_text() Or, if you need to get to the first inner td element of the first tr: soup.find('tr', {'class': 'last'}).td.get_text() where .td is a shorthand for .find("td"). Or, you can enforce the current class check (assuming you are going after the contents of the inner td element): soup.select_one("tr.last td.current").get_text() where tr.last td.current is a CSS selector that would match a td element having current class inside the tr element having last class.
upvote count: 2
type: Answer
score: 2
answers question: http://stackoverflow.com/q/51977501
accepted answer of: http://stackoverflow.com/q/51977501

http://stackoverflow.com/comment/91012210
has text: If you are getting an exception, you should post the full exception, it helps people to help you. If this is `csv` data use the `csv` module, it would make it much easier to read. Did you try printing `value`?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52030861

http://stackoverflow.com/comment/91516330
has text: Thanks for your answer!
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52276457
type: AnswerComment

http://stackoverflow.com/comment/91100250
type: QuestionComment
comment on: http://stackoverflow.com/q/52074171
score: 0
type: Comment
has text: @Denziloe I have modified the code a bit, can you have a look at the post once again?

http://stackoverflow.com/comment/117245646
comment on: http://stackoverflow.com/a/56928895
type: AnswerComment
has text: It says "Operation not permitted." for `sudo cp libssl.1.1.dylib libcrypto.1.1.dylib /usr/lib/`
type: Comment
score: 1

http://stackoverflow.com/a/52055080
downvote count: 0
has body: Use groupby and apply in combination with ffill and bfill: df['identity'] = df.groupby(['hid', 'hospital'])['identity'].apply(lambda x: x.ffill().bfill()) This will fill NaNs forward and backwards while separating the values for the specified groups.
score: 1
has comment: http://stackoverflow.com/comment/91060638
upvote count: 1
has comment: http://stackoverflow.com/comment/91060504
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/52055014
answers question: http://stackoverflow.com/q/52055014
type: Answer

http://stackoverflow.com/a/52115232
has comment: http://stackoverflow.com/comment/91190058
score: 0
answers question: http://stackoverflow.com/q/52107909
type: Answer
has body: Show the complete stack trace and some reproducible code and data so that we can check this. This seems like an easy to solve problem and can be done if you provide how you intend to solve it. Other than that, there are multiple issues here: 1) OneHotEncoder cannot be used directly on strings directly. First you need to convert your string features to integers, (maybe using LabelEncoder) 2) One-hot encoding will transform your single column into multiple columns (depending on unique values in them), so you cannot assign it directly to a single column of your dataframe. 3) If you are able to successfully transform using OneHotEncoder, even then the data returned is a sparse matrix, which again does not go well with pandas dataframe. 4) You are assigning the same data to the same dataframe twice. Once inside method you are doing this: repair[field]=oe.transform(repair[field]) And then you call the method like this: repair['SALES_ORG_ID']=OneHotEncoder(repair,'SALES_ORG_ID') This is un-necessary. 5) You are first fitting (or trying to fit) all the data in the field. So the oe.classes_ will contain all the unique categories. So after that, doing repair[field] = repair[field].map(lambda s: 'Other' if s not in oe.classes_ else s) dont make any sense. Can you show how you are doing this successfully for labelencoder as you said in the question? Now even if you somehow sucessfully do this, the next line: repair[field]=oe.transform(repair[field]) will throw error because, 'Other' is a string which the OneHotEncoder dont handle. You need to add the extra category ('Other' in this case before fitting the data. 6) I would suggest you to save the transformers using joblib or pickle instead of numpy. Note: As mentioned in changelog here, from next version (0.20.0), OneHotEncoder will be able to handle strings in passed data: String or pandas Categorical columns can now be encoded with OneHotEncoder or OrdinalEncoder.

http://stackoverflow.com/a/51980640
has body: Are you actually trying to inherit http.controller? If so, the default 0Auth module in Odoo can perhaps show you how that is arranged (since it also inherits this class). If you are just trying to add a new class to Odoo, note that it has it's own inheritance system, which is described in the documentation (and works vastly different from default python): Odoo inheritance documentation for version 11.0 Note that although I have no personal experience with inheriting anything anything other than Odoo objects within Odoo, I found a lot of examples in the standard addons that should help you on your way.
score: 0
type: Answer
has comment: http://stackoverflow.com/comment/90914918
has comment: http://stackoverflow.com/comment/90917791
answers question: http://stackoverflow.com/q/51979928

http://stackoverflow.com/q/52010388
has title: Value_counts on multiple columns with groupby
type: Question
type: AnsweredQuestion
upvote count: 5
accepted answer: http://stackoverflow.com/a/52010499
has body: I need some help with Pandas. I have following dataframe: df = pd.DataFrame({'1Country': ['FR', 'FR', 'GER','GER','IT','IT', 'FR','GER','IT'], '2City': ['Paris', 'Paris', 'Berlin', 'Berlin', 'Rome', 'Rome','Paris','Berlin','Rome'], 'F1': ['A', 'B', 'C', 'B', 'B', 'C', 'A', 'B', 'C'], 'F2': ['B', 'C', 'A', 'A', 'B', 'C', 'A', 'B', 'C'], 'F3': ['C', 'A', 'B', 'C', 'C', 'C', 'A', 'B', 'C']}) screenshot I am trying to do a groupby on first two columns 1Country and 2City and do value_counts on columns F1 and F2. So far I was only able to do groupby and value_counts on 1 column at a time with df.groupby(['1Country','2City'])['F1'].apply(pd.Series.value_counts) How can I do value_counts on multiple columns and get a datframe as a result?
possible better answer: http://stackoverflow.com/a/52010513
answer count: 2
score: 5
has answer: http://stackoverflow.com/a/52010513
downvote count: 0
favorite count: 0
tagged with: pandas-groupby
tagged with: pandas
tagged with: python
has answer: http://stackoverflow.com/a/52010499

http://stackoverflow.com/q/51970426
tagged with: python
has comment: http://stackoverflow.com/comment/90891631
has body: I need one or more hints to get over the first pain in transfer-learning. The following code is a stripped-down version of what I am actually trying to do, but it shows the issues even with one the fake image (A: empty / B: empty + little square) I use there. In the final version, the input will be much more complex images (which justifies the complexity of the applied base model). The problem looks simple. Input: two types of images, output: binary classification ("square present yes/no"). The modified ResNet50 model is fed with prepared training data via ImageDataGenerator. As I can create any amount of fake data, there is no data augmentation step in the code. Anyway, when I run the code the displayed loss (for both the Adam and the SDG optimizer) doesn't seem to improve and the accuracy quickly tends to approach the ratio of the number of the examples in the two image classes (i.e. B/A). (Note: during the weekend, I even tried for 500 epochs ... no change.) For both (most likely connected) issues I haven't been able to spot the reason yet ... could you? Is it one of the hyper-parameters, is there an obvious glitch in the model setup or any other part of the implementation? Probably it's just something stupid, but after chasing it and playing around with different and more and more simplified versions, I am about to run out of ideas regarding what to try next. import cv2 import matplotlib.pyplot as plt import numpy as np from tqdm import tqdm from random import randint from keras.layers import Dense, GlobalAveragePooling2D from keras.optimizers import Adam from keras.models import Model from keras.applications import ResNet50 from keras.preprocessing.image import ImageDataGenerator def modified_resnet_model(): # load ResNet50 model excluding classification layers basemodel = ResNet50(weights='imagenet', include_top=False, input_shape=(224, 224, 3)) # freeze model weights for layer in basemodel.layers: layer.trainable = False # add new classification head x = Glob…
has title: ResNet50 transfer learning fails
answer count: 0
tagged with: tensorflow
type: Question
tagged with: keras
has comment: http://stackoverflow.com/comment/90913380
score: 0
tagged with: transfer-learning
type: UnansweredQuestion

http://stackoverflow.com/q/52096549
upvote count: 1
downvote count: 1
tagged with: tensorflow
type: Question
has body: I am new to neural networks. I am getting error on the below line in my code net = tflearn.input_data(shape=[None, len(train_x[0])]) Below is the error , I am getting" TypeError: object of type 'numpy.float64' has no len() I tried below syntax and it still give me an error net = tflearn.input_data(shape=[None, len(train_x)]) The error that I got: ValueError: Cannot feed value of shape (8,) for Tensor 'InputData/X:0', which has shape '(?, 19579)' Can you please help suggest what should I do? Also, below is the complete syntax, if required import numpy as np # linear algebra import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv) # Input data files are available in the "../input/" directory. # Any results you write to the current directory are saved as output. #from subprocess import check_output #print(check_output(["ls", "../input"]).decode("utf8")) train = pd.read_csv('C:/Users/gunjit.bedi/Desktop/Tensor Flow/input/train.csv') print(train.head()) import nltk as nl train['tokens'] = [nl.word_tokenize(sentences) for sentences in train.text] words = [] for item in train.tokens: words.extend(item) stemmer = nl.stem.lancaster.LancasterStemmer() words = [stemmer.stem(word) for word in words] filtered_words = [word for word in words if word not in nl.corpus.stopwords.words('english')] import gensim # let X be a list of tokenized texts (i.e. list of lists of tokens) model = gensim.models.Word2Vec(filtered_words, size=100) w2v = dict(zip(model.wv.index2word, model.wv.syn0)) print(w2v['h']) training = [] for index, item in train.iterrows(): vec = np.zeros(100) token_words = [stemmer.stem(word) for word in item['tokens']] token_words = [word for word in token_words if word not in nl.corpus.stopwords.words('english')] for w in token_words: if w in w2v: vec += w2v[w] norm = np.linalg.norm(vec) if norm != 0: vec /= np.linalg.norm(vec) training.append(vec) training_new = np.array(training) from numpy import array from sklearn.preprocessing import LabelEncoder from …
has answer: http://stackoverflow.com/a/52096869
accepted answer: http://stackoverflow.com/a/52111358
score: 0
answer count: 2
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/52111358
tagged with: python
possible better answer: http://stackoverflow.com/a/52096869
has title: when using tensor flow i am getting error TypeError
type: AnsweredQuestion

http://stackoverflow.com/a/52028502
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52028438
type: Answer
answers question: http://stackoverflow.com/q/52028438
score: 4
upvote count: 4
has body: You don't need to make tkinter try-except its own call; just try-except your call to tkinter: try: self.image = PhotoImage(file="cat.png") except tkinter.TclError: # do whatever you wanted to do instead For example: try: self.image = PhotoImage(file="cat.png") except tkinter.TclError: self.cat = Label(text="Sorry I have no cat pictures") else: self.cat = Label(image=self.image)
type: AcceptedAnswer

http://stackoverflow.com/a/51976040
has comment: http://stackoverflow.com/comment/90902591
has comment: http://stackoverflow.com/comment/91062752
answers question: http://stackoverflow.com/q/51960287
score: 0
has comment: http://stackoverflow.com/comment/91081803
has comment: http://stackoverflow.com/comment/90910075
has body: To make the user session accessible to your Android clients all you need to do is make sure the session cookie is sent with the Socket.IO connection request. Sadly, this client does not appear to have the option to send extra headers or cookies (this limitation is referenced in an issue). I'm not sure you have a lot of options here. You can modify this client to allow extra headers to be passed, or else you can use a different auth mechanism. The only way this client supports custom arguments is via the query string, so you can pass a token that way.
has comment: http://stackoverflow.com/comment/90909948
type: Answer
has comment: http://stackoverflow.com/comment/91052064

http://stackoverflow.com/a/51971440
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/51971096
accepted answer of: http://stackoverflow.com/q/51971096
type: Answer
upvote count: 2
has body: Help page for pandas append states: "Append rows of other to the end of this frame, returning a new object. Columns not in this frame are added as new columns." https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.append.html in your case, you do not any supply column name(s), so new is(are) created. Many ways to append a new row. One way: df5 = df5.append({'Q':'Q', 'R':'Q', 'S':'Q'}, ignore_index=True)
score: 2

http://stackoverflow.com/comment/91106196
type: Comment
has text: Ok I forgot to tell that I have 3000+ test functions and I cannot edit every tests.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52077658

http://stackoverflow.com/q/52037461
has title: How to scale CoreNLP + Flask?
downvote count: 1
type: Question
tagged with: stanford-nlp
answer count: 1
tagged with: flask
has comment: http://stackoverflow.com/comment/91029445
score: 0
tagged with: nlp
favorite count: 0
has answer: http://stackoverflow.com/a/52039497
has body: I want to use CoreNLP on production so it should be scalable enough. (5000 requests between 9am to 5pm) I am using Python wrapper pycorenlp and using Flask framework as API an endpoint. This Flask API endpoint is hosted on Elastic Beanstalk (AWS). Reason: http://flask.pocoo.org/docs/dev/deploying/ I know it's possible to run the Stanford CoreNLP server multithreaded-ly. But is this enough? Should I be running multiple coreNLP servers? What are the best practices to make this combination scalable enough? I am assuming that coreNLP server should be running on the same server where Flask endpoint is hosted.
type: UnansweredQuestion
upvote count: 1
tagged with: python

http://stackoverflow.com/comment/91264755
type: Comment
comment on: http://stackoverflow.com/q/52102437
score: 0
has text: Perhaps the error relates to availability of c compoler on a system?
type: QuestionComment

http://stackoverflow.com/comment/90945344
comment on: http://stackoverflow.com/q/51997881
score: 0
type: QuestionComment
type: Comment
has text: key 0 , value: ('NAME': 'Apple'), ('Colour': 'red'), ('Type': 'Fruit'), ('COMMENT': 'Fuji')

http://stackoverflow.com/q/51960770
has title: Getting started with automating web activities
tagged with: web
type: Question
tagged with: python
score: 0
answer count: 1
tagged with: phantomjs
tagged with: automation
has answer: http://stackoverflow.com/a/51960891
has body: I'm trying to automate a few tasks and learn a new skill at the same time. I figured this would be a good one to start with. I'd like to enter a range of data into this online calculator to save me manually doing it. https://www.rba.gov.au/calculator/financialYearDecimal.html I figure PhantomJS is a tool I could use, but I'm not really sure where to start. Can anyone please point me in the right direction? Thank you
type: UnansweredQuestion

http://stackoverflow.com/comment/90934244
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51992254
has text: Get started here https://stackoverflow.com/questions/2792650/import-error-no-module-name-urllib2

http://stackoverflow.com/comment/91034054
score: 0
type: Comment
has text: You could put the condition in its own method so you could call something like `if outOfRange() and itemEquals(matrix[row,col-2], 0)`
type: QuestionComment
comment on: http://stackoverflow.com/q/52041637

http://stackoverflow.com/q/52025186
has body: I am trying to install scrapy on my window 10 laptop. I have installed " Build Tools for Visual Studio 2017" on my PC. I am still getting below error: python version: 3.6, 64bit OS: Windows 64 bit Thanks!
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/52028388
has title: error: Microsoft Visual C++ 14.0 is required. Get it with "Microsoft Visual C++ Build Tools" scrapy
tagged with: web-scraping
upvote count: 1
tagged with: scrapy
downvote count: 1
type: Question
linked to: http://stackoverflow.com/q/44951456
score: 0
has comment: http://stackoverflow.com/comment/114114248
answer count: 1
has answer: http://stackoverflow.com/a/52028388
favorite count: 0
tagged with: python-3.x
tagged with: python

http://stackoverflow.com/comment/91150037
has text: That's not a good example. You can simply remove it from your `Animal` class and it will work fine.
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52099729

http://stackoverflow.com/a/51997715
answers question: http://stackoverflow.com/q/51995857
has body: It is better to do group by after merging the data frame,it works well even index is not same. df1 = pd.DataFrame({"Country": ['A', 'B', 'C', 'D', 'E',"F"], "life_expectency": [60, 70, 80, 50, 100,80]}) df2 = pd.DataFrame({"Country": ['E', 'D', 'C', 'B', 'A'], "region": ['region1', 'region1', 'region2', 'region2', 'region2']}) pd.merge(df1,df2,how="left").groupby("region")[2010].mean() note-taken same dataframes from ALollz answer.
score: 0
type: Answer

http://stackoverflow.com/a/52130032
upvote count: 1
has comment: http://stackoverflow.com/comment/91210765
has body: Since your main issue is finding the links, here is a generator that will find all of the category and sub-category links using the sitemap krflol pointed out in his solution: from bs4 import BeautifulSoup import requests def category_urls(): response = requests.get('https://www.courts.com.sg/sitemap') html_soup = BeautifulSoup(response.text, features='html.parser') categories_sitemap = html_soup.find(attrs={'class': 'xsitemap-categories'}) for category_a_tag in categories_sitemap.find_all('a'): yield category_a_tag.attrs['href'] And to find the product names, simply scrape each of the yielded category_urls.
downvote count: 0
answers question: http://stackoverflow.com/q/52065009
type: Answer
has comment: http://stackoverflow.com/comment/91210830
score: 1

http://stackoverflow.com/q/52079180
score: 1
favorite count: 0
tagged with: python-3.x
has title: When importing elements from Selenium writes to multiple lines on CSV instead of one
type: Question
upvote count: 1
tagged with: python
tagged with: excel
has comment: http://stackoverflow.com/comment/91115468
tagged with: selenium
has comment: http://stackoverflow.com/comment/91115144
answer count: 0
downvote count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91144345
has body: I can pull the code and it writes to the CSV but when imported to excel only the first line of the html shows in the excel file. It does work properly in Google Sheets. I am sure an imported line break is in there but I do not know how to strip it before writing to CSV. Thanks for any and all help. My code. def grabAddress(): element = browser.find_elements(By.XPATH, '//*[@id="memberDetail"]/section/div/div[1]/div[3]/p[2]/strong') strings = [] for x in element: strings.append(x.text) splitstrings = "".join(strings) address.append(splitstrings) return 0 with open(r"C:\bnicsv\compiled.csv", "w", newline ="") as compiledCSV: writecompiledtoCSV = csv.writer(compiledCSV, delimiter=",") writecompiledtoCSV.writerows(compiled_list) HTML I am pulling... &lt;strong&gt; Jack Jackson&lt;br&gt; Jacks Jewelers&lt;br&gt; 1985 East End Blvd.&lt;br&gt; St. Paul Park, MN 55555 &lt;/strong&gt;
tagged with: http://stackoverflow.com/tag/csv

http://stackoverflow.com/comment/90904174
type: QuestionComment
type: Comment
has text: no, i do not want to modify the filename variable.
comment on: http://stackoverflow.com/q/51976517
score: 0

http://stackoverflow.com/a/52104647
has comment: http://stackoverflow.com/comment/91160501
has body: After testing my comment it seems that multi-lining your regex is likely causing you an issue import re from urllib.parse import urlparse data = 'https://google.com/#resource' url_regex = r'''((http|https)\:\/\/)?[a-zA-Z0-9\.\/\?\:@\-_=#]+\.([a-zA-Z]){2,6}([a-zA-Z0-9\.\&amp;\/\?\:@\-_=#])*''' regex = re.compile(url_regex) url = regex.match(data).group() print('http://' + urlparse(url).netloc) the above code works for me.
has comment: http://stackoverflow.com/comment/91160662
answers question: http://stackoverflow.com/q/52103906
score: 0
has comment: http://stackoverflow.com/comment/91160537
has comment: http://stackoverflow.com/comment/91160787
has comment: http://stackoverflow.com/comment/91160753
type: Answer

http://stackoverflow.com/comment/91084029
score: 1
type: QuestionComment
type: Comment
has text: I guess you did activate the venv before calling pip, but just notice it's trying to install on python2.7 dist lib, but you have a venv for python3.
comment on: http://stackoverflow.com/q/52066816

http://stackoverflow.com/a/52013739
has body: You can put variable positional arguments before keyword arguments: Change: def foo(arg1, def_par="yes", *args,**kwargs): to: def foo(arg1, *args, def_par="yes", **kwargs): With this change, your code would output: Hello yes smell,funky 1 2 If for some reason you can't or don't want to change the function signature of foo, you can obtain the default value of a parameter with inspect.signature: import inspect foo("Hello", inspect.signature(foo).parameters['def_par'].default, 1, 2, smell="funky")
has comment: http://stackoverflow.com/comment/90979281
accepted answer of: http://stackoverflow.com/q/52013716
type: Answer
answers question: http://stackoverflow.com/q/52013716
upvote count: 2
score: 2
has comment: http://stackoverflow.com/comment/90981471
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/90978143

http://stackoverflow.com/comment/90974732
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52011430
has text: Java's `int`/`Integer` distinction is completely different. Python has no concept of primitives; an int is already an object. In Java, you can't even put an int in a list. The wrappers are near-mandatory. Also, your code is prone to Integer + Integer or Integer + int TypeErrors, which are essentially impossible in the Java type system.
score: 0

http://stackoverflow.com/comment/91039727
type: QuestionComment
score: 0
has text: Well then you are going to need to create a [mcve] to get a real answer. It's extremely difficult to know what is going on without having access to the underlying data.
comment on: http://stackoverflow.com/q/52043999
type: Comment

http://stackoverflow.com/comment/90945011
type: AnswerComment
comment on: http://stackoverflow.com/a/51997781
has text: code-only answers are considered harmful in the long term, they don't explain anything hence don't help
type: Comment
score: 0

http://stackoverflow.com/a/52007505
answers question: http://stackoverflow.com/q/52007401
type: Answer
has comment: http://stackoverflow.com/comment/90965582
has comment: http://stackoverflow.com/comment/90965692
score: 1
upvote count: 1
has body: Where to start? You're editing a list while iterating over it. That is generally ill advised -- weird bugs can come of it. You increment num no matter what happens in your condition -- this is your main issue you're checking every number between the first and last primes you've found, not just the primes here is a fix of your code def print_primes_to(n): primes = [2,3] for prime in primes: print(prime) for num in range(5, n, 2): isprime = True for prime in primes: if num % prime == 0: #not prime isprime = False break if isprime: # could replace with for/else primes.append(num) print(num) test case &gt;&gt;&gt; print_primes_to(30) 2 3 5 7 11 13 17 19 23 29 There are better algorithms, here is one I have lying around: import itertools as _itertools def primelist(n): """Returns a list of all primes less than n.""" if n &lt;= 2: return [] nums = [True]*(n - 2) for num in range(2, _rootp1(n)): for counter in _itertools.count(num): product = counter * num if product &gt;= n: break nums[product - 2] = False return [index for index, val in enumerate(nums, 2) if val] def _rootp1(n: float) -&gt; int: """returns the truncated square root of n plus 1 for use in range""" return int(n**0.5) + 1 See how long it takes to generate all primes less that 1 million %timeit primelist(1_000_000) 1.33 s ± 30.6 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52007401

http://stackoverflow.com/q/52038053
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/52038362
has comment: http://stackoverflow.com/comment/91026536
type: Question
has answer: http://stackoverflow.com/a/52038116
has title: Creating a matrix in Python storing the rightmost index of the string character
has body: I'm trying to create a matrix where it stores the rightmost index of the string character. For example, if i have the string: "baby" i want to generate a matrix as such: [['b',2],['a',1],['y',3]] where the index 0 represents the non-duplicate character in the string and index 1 represents the rightmost index occurence of the character in the string. Example, the first character 'b' occurs at index 0 but another occurs at index 2, hence, it will be 2. I tried something like: def str_matrix(string): matrix = [[]] for i in range(len(pattern)): if pattern[i] not in matrix: matrix.append([pattern[i],i]) else: matrix[i][1].append(i) print(matrix) but I'm getting: [[], ['b', 0], ['a', 1], ['b', 2], ['y', 3]] Would appreciate some help on this.
has comment: http://stackoverflow.com/comment/91026627
has comment: http://stackoverflow.com/comment/91026495
has comment: http://stackoverflow.com/comment/91026560
score: 0
has answer: http://stackoverflow.com/a/52038383
answer count: 3
tagged with: python
has comment: http://stackoverflow.com/comment/91026428
has comment: http://stackoverflow.com/comment/91026475

http://stackoverflow.com/q/51957295
favorite count: 0
upvote count: 0
has title: If statement to take input and accept integer
type: UnansweredQuestion
score: -3
has comment: http://stackoverflow.com/comment/90865165
has comment: http://stackoverflow.com/comment/90865168
linked to: http://stackoverflow.com/q/19440952
has comment: http://stackoverflow.com/comment/90865188
has body: I need to write an if statement that will take user input and accept integers. Here is the code, but it is only taking the specified integers. next = raw_input("&gt; ") if "0" in next or "1" in next: how_much = int(next)
type: Question
has answer: http://stackoverflow.com/a/51958289
answer count: 1
has comment: http://stackoverflow.com/comment/90865831
downvote count: 3
has comment: http://stackoverflow.com/comment/90865744
duplicate of: http://stackoverflow.com/q/19440952
tagged with: python

http://stackoverflow.com/comment/91077404
score: 0
comment on: http://stackoverflow.com/q/52063354
type: QuestionComment
has text: Please open this link `https://www.magicbricks.com/property-for-sale/residential-real-estate?bedroom=1,2,3,4,5,%3E5&proptype=Multistorey-Apartment,Builder-Floor-Apartment,Penthouse,Studio-Apartment,Residential-House,Villa,Residential-Plot&cityName=Mumbai` and here you will get more than 50000 property details and click first one `https://www.magicbricks.com/propertyDetails/2-BHK-1182-Sq-ft-Multistorey-Apartment-FOR-Sale-Kandivali-East-in-Mumbai&id=4d423336313032373731` and then you will see some data like bedrooms, Bathroom etc.
type: Comment

http://stackoverflow.com/q/52037604
has comment: http://stackoverflow.com/comment/91025986
type: UnansweredQuestion
tagged with: animation
tagged with: python
has body: I have a c++ program which outputs position versus time (trajectory), and I am going to generate animation from it. Till now I generated images then produced animation from it. But I am going to do real time animation, i.e. running c++ code and generating animation at the same time. I know the basic python/c++ linking like the bellow code, #include &lt;cstdlib&gt; #include &lt;iostream&gt; #include &lt;cstdio&gt; #include &lt;python2.7/Python.h&gt; int main() { char filename[] = "pyemb.py"; FILE* fp; Py_Initialize(); for (int istep = 0; istep &lt; 20; istep++) { PyObject* PyFileObject = PyFile_FromString(filename, "r"); PyRun_SimpleFileEx(PyFile_AsFile(PyFileObject), filename, 1); } Py_Finalize(); return 0;} and I wrote a basic code by mpl.animation to produce live animation in python, import numpy as np import matplotlib.pyplot as plt import matplotlib.animation as animation np.random.seed(0) N = 10 L = 4.0 init_state = np.random.random((N, 2)) fig = plt.figure() fig.subplots_adjust(left=0, right=1, bottom=0, top=1) ax = fig.add_subplot(111, aspect='equal', autoscale_on=False, xlim=(0., L), ylim=(0., L)) particles, = ax.plot([], [], 'bo', ms=6) particles.set_data([], []) def animate(i): """perform animation step""" ran_angle = np.random.random((N,)) ran_cos = np.cos(ran_angle*2.*np.pi) ran_sin = np.sin(ran_angle*2.*np.pi) init_state[:, 0] += ran_cos init_state[:, 1] += ran_sin for ind in range(N): for ii in range(2): if (init_state[ind,ii] &gt; L): init_state[ind,ii] -= L if (init_state[ind,ii] &lt;= 0): init_state[ind,ii] += L particles.set_data(init_state[:, 0], init_state[:, 1]) return particles ani = animation.FuncAnimation(fig, animate, frames=20, interval=1, blit=False, repeat = False) ani.save('particle_box.mp4', fps=3, extra_args=['-vcodec', 'libx264']) but I don't know how to link them dynamically. I googled a lot, but with no success, partly because I didn't know what to exactly search for.
tagged with: c++
score: 3
answer count: 0
has title: c++ live animation using matplotlib
type: Question
downvote count: 0
has comment: http://stackoverflow.com/comment/91026053
upvote count: 3
favorite count: 0

http://stackoverflow.com/comment/90915498
type: Comment
type: QuestionComment
score: 0
has text: Cannot access the data
comment on: http://stackoverflow.com/q/51981872

http://stackoverflow.com/comment/90970255
score: 0
has text: yes sorry about that.
type: QuestionComment
comment on: http://stackoverflow.com/q/52009543
type: Comment

http://stackoverflow.com/comment/90944018
score: 0
type: Comment
has text: I have updated a new one above regarding my findings.
type: AnswerComment
comment on: http://stackoverflow.com/a/51965149

http://stackoverflow.com/q/51974680
linked to: http://stackoverflow.com/q/21811464
has title: Embedding IPython console in Tkinter frame
favorite count: 0
tagged with: tkinter
answer count: 0
type: UnansweredQuestion
upvote count: 1
tagged with: python
has body: I was working on a PyQt application that had an embedded JupyterWidget that would allow a user to use an IPython console to interact with certain variables that were being displayed. However, it was recently suggested that we switch to Tkinter graphics instead of Qt because of Tkinter's out of the box support in Python. Is there a Tkinter equivalent implementation of the JupyterWidget in PyQt? The best I can seem to find is https://github.com/ipython/ipython/wiki/Trash:-Old-Embedding-Tkinter but this uses a very old version of IPython where almost all of the function calls are deprecated or removed entirely. I had also tried this but was unable to make it so that changes in the subprocess' variables were reflected in the overall program.
score: 1
tagged with: ipython
type: Question
downvote count: 0

http://stackoverflow.com/comment/91043197
has text: It's not Django that doesn't work like that, but the web. If you want to send data by Ajax, you need to do something in your JS with the response. But I don't understand why you don't just wrap those input fields in a form.
score: 0
comment on: http://stackoverflow.com/q/52044065
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/90869027
score: 0
comment on: http://stackoverflow.com/a/51959353
type: AnswerComment
has text: Thanks, but now I am getting this error: AttributeError: 'str' object has no attribute 'get' Dunno why it worked for you?
type: Comment

http://stackoverflow.com/q/51983774
tagged with: python
has title: Running modern Python on legacy Windows
has body: I have some code developed in Python, which makes heavy use of Python 3 language features, such as f-strings (which require Python 3.6 or later). Due to a customer commission I have found myself in the situation that this code needs to run on Windows Server 2003. Python has officially dropped support for legacy versions of Windows sometime around the release of Python 3.5. Is there a "port" (I guess this would be the best way to call it) of Python 3.6 to legacy Windows, or does anyone have a good idea of how to get my code to run without doing too much heavy lifting?
answer count: 0
has comment: http://stackoverflow.com/comment/90968314
type: Question
tagged with: legacy
score: 0
has comment: http://stackoverflow.com/comment/90961430
tagged with: python-3.x
type: UnansweredQuestion
tagged with: windows

http://stackoverflow.com/comment/91113585
score: 1
has text: Okay, I am not getting this error because I was using names parameter in pd.read_csv https://github.com/pandas-dev/pandas/issues/10496 https://github.com/pandas-dev/pandas/issues/9424
comment on: http://stackoverflow.com/a/52063389
type: AnswerComment
type: Comment

http://stackoverflow.com/q/51988458
type: Question
answer count: 3
linked to: http://stackoverflow.com/q/682504
downvote count: 0
favorite count: 0
has title: Classmethod: Using a function within a function
has body: I have a situation where I'm using @classmethod to create a constructor for a class. Within this constructor, a function gets called, which then in turn calls another function. But either this doesn't work or (more probably) I'm doing something to make it not work. Here's an example in miniature: class testclass: def __init__(self, x): self.x = x @classmethod def constructor(cls, x): adj_x = cls.outer_adjust(cls, x) return testclass(adj_x) def outer_adjust(self, x): return self.inner_adjust(x) def inner_adjust(self, x): return x + 1 test_instance = testclass.constructor(4) This produces an error message: inner_adjust() missing 1 required positional argument: 'x' I can make it work by explicitly passing self to inner_adjust, eg def outer_adjust(self, x): return self.inner_adjust(self, x) But this then means that the outer_adjust method can't be used outside of the constructor, which is not what I want. Any assistance gratefully received. Here's a more detailed example, with two constructors shown. I'm trying to follow the approach to constructors described in What is a clean, pythonic way to have multiple constructors in Python? Which is essentially that the constructors do some processing to figure out what variables they should pass to init when instantiating the class. Both constructors give the same error: if_char_is_z_make_it_a() missing 1 required positional argument: 'char_input' As before, I need to be able to use the if_char_is_make_it_a function outside of the constructor (ie, when using the class normally). class testclass: def __init__(self, char): self.char = char @classmethod def constructor_from_int(cls, int_input): as_char = chr(int_input) char = cls.process_char(cls, as_char) return testclass(char) @classmethod def constructor_from_char(cls, char_input): char = cls.process_char(cls, char_input) return testclass(char) def process_char(self, char_input): processed_char = '(' + char_input + ')' output_char = self.if_char_is_z_make_it_a(processed_char) r…
tagged with: python
has answer: http://stackoverflow.com/a/51988499
upvote count: 3
type: UnansweredQuestion
score: 3
has answer: http://stackoverflow.com/a/51988571
has answer: http://stackoverflow.com/a/51988535

http://stackoverflow.com/comment/91000229
score: 1
has text: Returning `[1,1,1]` sounds good, not you just need to `join` them to a `str` (hint hint). (BTW, make sure the digits are in the right order, which can not easily be inferred from this example, maybe try with another one?)
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52024914

http://stackoverflow.com/comment/90882007
comment on: http://stackoverflow.com/q/51959205
score: 0
type: Comment
type: QuestionComment
has text: @Sraw - thanks for your response. I suspect it's my confusion, not yours. First of all, until you asked, I was convinced that the the key (owned by root) and had perms of 600 and so only root could read it. I've now found that in fact it's got perms of 644 so that anyone can read it ? Which I don't think is right . I'm puzzled by this because the files were created by an automated process (acme.sh) and I assumed the perms were optimal . Judging by your response I guess you would expect the key to be owned by some user other than root and that whoever owned it would run the process ?

http://stackoverflow.com/q/52001567
has answer: http://stackoverflow.com/a/52001853
has answer: http://stackoverflow.com/a/52001732
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/52001853
downvote count: 3
type: Question
has comment: http://stackoverflow.com/comment/90952524
has title: Give the number and fill the xth (x is the number) item in a list with '1',keep others empty
upvote count: 0
has comment: http://stackoverflow.com/comment/90952494
accepted answer: http://stackoverflow.com/a/52001732
answer count: 3
has answer: http://stackoverflow.com/a/52001786
has comment: http://stackoverflow.com/comment/90952421
has comment: http://stackoverflow.com/comment/90952325
favorite count: 0
has body: for example, I have a list of data like this: ['81', '88', '99', '124', '144', '145', '216', '223', '225', '227', '231', '232', '233', '236', '238', '239', '240', '241', '242', '244', '245', '246', '247', '248', '249', '250', '251', '253', '254', '256', '257', '259', '260', '261', '264', '265', '266', '267', '268', '269', '270', '271', '272', '273', '274', '275', '276', '278', '279', '280', '281', '284', '285', '288', '296', '299', '304'] and I created a list, which contains 365 of ' ' by using julianList=[" "] *365 Now, what I need to do is change the xth(x is number) of item in juLianList into '1' I use the following code julianList=[" "] *365 EjulianList=list(enumerate(julianList)) ## print(EjulianList) print(julianList[2]) for i in range(len(julian)): for j in range(len(EjulianList)): if julian[i]==EjulianList[j][0]: julianList[j]='1' print(julianList) but still get a list with 365 ' ' like [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '] what's wrong with it?
score: -3
has comment: http://stackoverflow.com/comment/90952567
tagged with: python

http://stackoverflow.com/q/52043224
type: AnsweredQuestion
has title: MS Graph/assignLicense: primitive 'null' value was expected
downvote count: 0
score: 1
tagged with: microsoft-graph-api
has answer: http://stackoverflow.com/a/52046154
accepted answer: http://stackoverflow.com/a/52046154
type: Question
has body: From python, I'm trying to assign a license to a user in Office365 using MS Graph API. request_url = "https://graph.microsoft.com/v1.0/users/myuser@mydomain.ca/assignLicense" headers = { 'Authorization' : 'Bearer ' + token, 'Content-Type' : 'application/json', } response = requests.post(url = request_url, headers = headers, json={'addLicenses': 'testGUID'}) However, I am getting the following error message: { "error": { "code": "Request_BadRequest", "innerError": { "date": "2018-08-27T15:56:45", "request-id": "9ddde6c8-5fe1-4425-ba84-bc49fa35e2b8" }, "message": "When trying to read a null collection parameter value in JSON Light, a node of type 'PrimitiveValue' with the value 'test' was read from the JSON reader; however, a primitive 'null' value was expected." } } How can I call assignLicense from python?
has comment: http://stackoverflow.com/comment/108883775
upvote count: 1
answer count: 1
favorite count: 0
tagged with: python

http://stackoverflow.com/a/78282594
type: Answer
answers question: http://stackoverflow.com/q/52035673
has body: Your conda base environment has the latest version of python at the time you downloaded the anaconda executable. Meaning, if you want to upgrade your base anaconda python, say from Python 3.7 to Python 3.10, you have two options: Uninstall your current version and install the newest version of anaconda. Create an environment with a python version higher than the python version of the conda base environment Why? For example, if your base anaconda environment has python 3.7, the max python you can get is 3.7.13.final as reflected in the log output below (VM sandbox environment). Run in terminal: conda activate base Run in terminal (approx. max supported for conda environments with python 3.7): conda install -n base conda=23.1.0 Run in terminal: conda info Output: active environment : base active env location : xxxxxxxxxxxxxxxxxx shell level : 1 user config file : xxxxxxxxxxxxxxxxxx populated config files : xxxxxxxxxxxxxxxxxx conda version : 23.1.0 conda-build version : 3.23.3 python version : 3.7.13.final.0 virtual packages : xxxxxxxxxxxxxxxxxx xxxxxxxxxxxxxxxxxx base environment : xxxxxxxxxxxxxxxxxx conda av data dir : xxxxxxxxxxxxxxxxxx conda av metadata url : None channel URLs : xxxxxxxxxxxxxxxxxx package cache : xxxxxxxxxxxxxxxxxx envs directories : xxxxxxxxxxxxxxxxxx platform : xxxxxxxxxxxxxxxxxx user-agent : conda/23.1.0 requests/2.28.1 CPython/3.7.13 administrator : False netrc file : None offline mode : False What if you try to install a higher conda version? If you try, for instance, to install a conda version thinking it will upgrade your python version too, you will receive errors like the below (please note the date this answer is being posted; error message may vary as the anaconda software evolves). Run in terminal: conda install -n base conda=23.7.4 Output: Collecting package metadata (current_repodata.json): done Solving environment: failed with initial frozen solve. Retrying with flexible solve. Collecting package metadata (repodata.json): done Solvin…
score: 0

http://stackoverflow.com/comment/91029361
type: AnswerComment
has text: Oh you are very true! This help me alot and I can confirm that this was the solution, so well as pekapa under was good said aswell! thanks to you both!
type: Comment
comment on: http://stackoverflow.com/a/52031169
score: 0

http://stackoverflow.com/comment/91109860
has text: Presumably you need to pass `self` to the functions? It's not clear what you're trying to do
score: 1
comment on: http://stackoverflow.com/q/52079895
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51958196
upvote count: 1
type: Question
has title: Pymysql and Microsoft Azure Mysql Database 'Lost connection to MySQL server during query'
linked to: http://stackoverflow.com/q/47067378
has body: Im trying to connect to a Mysql Azure Server and Im getting the error: (2013, 'Lost connection to MySQL server during query') On the connect command. I've read several similar questions here: Error 2013 - Lost Connection to MySQL server during query Error 2013 - Lost Connection to MySQL server during query pymysql,Lost connection to MySQL server during query But according to the traceback my error is occurring on the connect(), and the questions above are more related to big queries being made to the DB. This is the traceback: File "updateStock.py", line 125, in &lt;module&gt; main() File "updateStock.py", line 65, in main db = connection.connect() File "updateStock.py", line 22, in connect db="mydb") File "/usr/local/lib/python2.7/dist-packages/pymysql/__init__.py", line 94, in Connect return Connection(*args, **kwargs) File "/usr/local/lib/python2.7/dist-packages/pymysql/connections.py", line 327, in __init__ self.connect() File "/usr/local/lib/python2.7/dist-packages/pymysql/connections.py", line 598, in connect self._request_authentication() File "/usr/local/lib/python2.7/dist-packages/pymysql/connections.py", line 852, in _request_authentication auth_packet = self._read_packet() File "/usr/local/lib/python2.7/dist-packages/pymysql/connections.py", line 656, in _read_packet packet_header = self._read_bytes(4) File "/usr/local/lib/python2.7/dist-packages/pymysql/connections.py", line 702, in _read_bytes CR.CR_SERVER_LOST, "Lost connection to MySQL server during query") pymysql.err.OperationalError: (2013, 'Lost connection to MySQL server during query') And this is my code for connecting: class DB: conn = None def connect(self): self.conn = pymysql.connect(host="myserver.database.azure.com", user="usert@myserver.mysql.database.azure.com", passwd="****", port=3306, db="mydb") return self def get_cursor(self): return self.conn.cursor(buffered=True) def main(): # try: connection = DB() db = connection.connect() cursor = db.get_cursor() Can anyone help me spot the pro…
tagged with: pymysql
has comment: http://stackoverflow.com/comment/90968509
downvote count: 0
favorite count: 0
linked to: http://stackoverflow.com/q/45742940
has comment: http://stackoverflow.com/comment/90939259
type: UnansweredQuestion
tagged with: python
answer count: 0
score: 1
tagged with: mysql

http://stackoverflow.com/q/51998050
tagged with: turtle-graphics
type: UnansweredQuestion
tagged with: python
has body: In the interface design section in "Think Python" I need help understanding the approach to the circle and arc functions, like this: import turtle import polygon bob = turtle.Turtle() print(bob) def polygon(t, n, length): angle = 360 / n for i in range(n): t.fd(length) t.lt(angle) And after that, the book introduces another approach to drawing a circle by using a polygon function: def circle(t, r): circumference = 2 * math.pi * r n = int(circumference / 3 ) + 1 length = circumference / n polygon(t, n, length) What I don't understand: I have no idea why they define circumference to draw circle and how it works to draw a circle. If I call the function like circle(bob, 100) then it only draws a fraction of circle not the whole circle. I don't understand why n is needed, and how that procedure can make a circle.
score: 1
has title: Understanding turtle circle, and arc in "Think Python"
upvote count: 1
type: Question
has answer: http://stackoverflow.com/a/51999357
answer count: 1
downvote count: 0
favorite count: 0
tagged with: geometry

http://stackoverflow.com/comment/90922503
comment on: http://stackoverflow.com/q/51986128
has text: We don't need to see the code or errors in image form. But it'd be nice if you supplied the "bubble.png" image.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/52078569
has comment: http://stackoverflow.com/comment/91107607
score: 1
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/52078431
downvote count: 0
has comment: http://stackoverflow.com/comment/91107547
type: Answer
accepted answer of: http://stackoverflow.com/q/52078431
has comment: http://stackoverflow.com/comment/91107077
has body: I suspect your code looks a bit like: &gt;&gt;&gt; def x(): ... input = input() ... print(input) ... &gt;&gt;&gt; x() Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "&lt;stdin&gt;", line 2, in x UnboundLocalError: local variable 'input' referenced before assignment &gt;&gt;&gt; The problem is that you've created a variable called 'input', and then trying to get something from it before it exists. &gt;&gt;&gt; def y(): ... val = input() ... print(val) ... &gt;&gt;&gt; y() Would work a bit better. In python (and most dynamic languages) functions are kind of values too - so you can use the name of a function just like you would any other variable. So a good idea is to not name a variable the same as a function. Does that help?
upvote count: 1

http://stackoverflow.com/comment/91167033
type: Comment
score: 0
has text: `TIME` is actually of type `timedelta64[ns]`. I imagine that the ability to perform calculations on the times is more important than literally being `datetime`, but if that's wrong, OP will need to try a different approach.
comment on: http://stackoverflow.com/a/52108182
type: AnswerComment

http://stackoverflow.com/q/51997619
has title: Easy way to replace pip packages with conda-forge packages
favorite count: 0
tagged with: python-3.x
has body: I have been using anaconda 64-bit python v3.6 on Windows 10 for quite some time but only recently discovered conda-forge. I discovered there are many python packages which I installed using pip are actually available on conda-forge. I would like to replace the pip packages with conda-forge packages. I have been doing this manually but it is too tedious because they are many pip packages. Is there an easy way to replace the pip packages with conda-forge packages automatically with a single command line? I am open to using any other convenient method instead of doing it manually.
score: 6
tagged with: pip
tagged with: python
upvote count: 6
has answer: http://stackoverflow.com/a/51998260
has comment: http://stackoverflow.com/comment/91035828
type: AnsweredQuestion
tagged with: anaconda
type: Question
answer count: 2
accepted answer: http://stackoverflow.com/a/51998260
tagged with: conda
possible better answer: http://stackoverflow.com/a/51998671
has answer: http://stackoverflow.com/a/51998671
downvote count: 0
has comment: http://stackoverflow.com/comment/128350365

http://stackoverflow.com/a/52011883
upvote count: 2
type: Answer
has body: As other answers have explained, this probably isn't a great design. First, a "number" could be an int, or some user-defined subclass of int, or a float, or some user-defined Quaternion type. Normally, you just use duck-typing: it x ** 2 works, then x is quacking like a number, and that's good enough. But a list of ints doesn't quack like an int. So, what can you do? Well, usually, you'll want to explicitly loop over them: &gt;&gt;&gt; xs = [1, 2, 3] &gt;&gt;&gt; sqs = [square(x) for x in xs] … or write a function that does that: &gt;&gt;&gt; def squares(xs): return [square(x) for x in xs] &gt;&gt;&gt; sqs = squares(xs) … or use a type that knows how to vectorize mathematical operators: &gt;&gt;&gt; xs = np.array([1, 2, 3]) &gt;&gt;&gt; sqs = square(xs) In fact, even when you do want to handle two different types, you can often rely on duck typing: def square(x): try: return x**2 except ValueError: return [i**2 for i in x] This will square anything that's number-like enough to be squarable, and iterate over squaring all of the elements of anything that isn't, and raise a reasonable exception for anything that fails (either because it's not iterable, or because its elements aren't squarable). Occasionally, you really do need to type-switch. But you still want to keep as close to duck-typing as possible, and that means using isinstance (so that, e.g., a user subtype of int still counts as a number) and, usually, using abstract base classes (so that, e.g., a user Quaternion type still counts as a number). In this case, that means either treating numbers specially and assuming anything else is an iterable: def square(x): if isinstance(x, numbers.Number): return x**2 else: return [i**2 for i in x] … or treating iterables specially and assuming everything else is a number: def square(x): if isinstance(x, collections.abc.Iterable): return [i**2 for i in x] else: return x**2 Or maybe treating both specially and calling everything else an error: def square(x): if isinstance(…
score: 2
answers question: http://stackoverflow.com/q/52011435
downvote count: 0

http://stackoverflow.com/q/51972610
has answer: http://stackoverflow.com/a/51972671
has answer: http://stackoverflow.com/a/51972725
accepted answer: http://stackoverflow.com/a/51972725
tagged with: python
has answer: http://stackoverflow.com/a/51972935
has comment: http://stackoverflow.com/comment/90895961
has body: I'm trying to print a simple game board. places = [" "] * 9 board = (places[8] + "|" + places[7] + "|" + places[6] + "\n", places[5] + "|" + places[4] + "|" + places[3] + "\n", places[2] + "|" + places[1] + "|" + places[0] + "\n") print(board) But instead of a board I get this: (' | | \n', ' | | \n', ' | | \n') I want to print it without the parentheses and with new lines instead of \n. How can I do this?
answer count: 4
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51972851
has title: New line being printed as "\n" instead of actual new line
type: Question
score: -1
downvote count: 2
upvote count: 1
has comment: http://stackoverflow.com/comment/90895785
favorite count: 0
tagged with: python-3.x
possible better answer: http://stackoverflow.com/a/51972671
has comment: http://stackoverflow.com/comment/90895905

custom-exceptions
type: Tag
tag name: custom-exceptions
tags question: http://stackoverflow.com/q/52037383

http://stackoverflow.com/q/51969906
type: AnsweredQuestion
downvote count: 2
has title: Import variable from another script
upvote count: 1
type: Question
has answer: http://stackoverflow.com/a/51970147
has body: I am creating a personal assisstant. I would like to import a variable from another file. Despite there are many questions releated to my problem I can't find an answer that works. Example of how the system works Script with a function always listening I say a word (ex: 'hello') and it runs another function I say sthg (ex: 'time in Barcelona') It takes the last part (ex: 'Barcelona') and stores it into a variable (ex: loc) It runs another script (ex: time.py) main.py def googlecheck(): attempts = 0 # Importar fitxers - config.py = variables globals import config # Salutació de l'assistent a partir de la funció hi = ['Gerard'] tts('Hola ' + random.choice(hi)) while True: print(1) r = sr.Recognizer() with sr.Microphone() as msg: r.adjust_for_ambient_noise(msg) audio = r.listen(msg, phrase_time_limit=5) try: # Inicia la variable global mainvr config.init() config.mainvr = r.recognize_google(audio, language='es-ES') print(config.mainvr) except: # Si no es detecta cap paraula, suma 1, si s'arriba a 3, (3 vegades error), torna a la función principal. attempts += 1 if attempts &gt;= 3: activ() break continue hora = ['hora', 'en'] exit = ['salir', 'adiós', 'hasta pronto', 'vete', 'cállate'] if all(a in config.mainvr for a in hora): loc = config.mainvr[8:] print(loc) import hora if any(b in config.mainvr for b in exit): break else: # Si no es detecta cap paraula, suma 1, si s'arriba a 3, (3 vegades error), torna a la función principal. attempts += 1 if attempts &gt;= 3: activ() break PD: There is another part of code that calls this function when I say 'hello'. time.py def f(): from main.googlecheck() import loc print(loc) f() At this point, I would like to get the loc variable in the time.py file. If I have two files with a variable already defined (ex: loc = Valls), and no functions, it works. I am using the import method to do it, I think it might be something I do wrong as the method should be working despite the variable is not strictly defined. Any help is really appre…
answer count: 1
accepted answer: http://stackoverflow.com/a/51970147
favorite count: 0
tagged with: python-3.x
tagged with: python
score: -1

http://stackoverflow.com/q/52017456
has title: building data using dataframe with python 3.7
answer count: 0
has body: hi i tried to write some data about students using dataframe this is my code: import pandas as pd data={"students":["aj","mark","bob","rachel","steven"], "math":[98,50,23,72,87], "science":[96,45,76,54,1], "sports":["base","swim","tt","bad","tae"]} students=pd.DataFrame(data,columns= ["students","math","science","sports"]) print(students) but i keep getting this eror : result = Series(result, index=obj.index, name=obj.name, copy=False) TypeError: 'list' object is not callable whats is the prolem with my code? thanks for the help :)
type: Question
has comment: http://stackoverflow.com/comment/90984980
tagged with: dataframe
score: 0
tagged with: pandas
has comment: http://stackoverflow.com/comment/90985592
has comment: http://stackoverflow.com/comment/90984909
has comment: http://stackoverflow.com/comment/90985562
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/comment/91002097
comment on: http://stackoverflow.com/q/52025938
type: Comment
type: QuestionComment
has text: @Bazingaa how do i put it?
score: 0

http://stackoverflow.com/comment/90900821
comment on: http://stackoverflow.com/q/51974905
score: 0
has text: You don't need OpenCV for that at all. The offset for `x` is `(150-imagewidth)/2` and for `y` is `(150-imageheight)2`.
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51992375
has answer: http://stackoverflow.com/a/60696886
accepted answer: http://stackoverflow.com/a/51992497
favorite count: 0
linked to: http://stackoverflow.com/q/52283840
score: 35
has answer: http://stackoverflow.com/a/79351010
has answer: http://stackoverflow.com/a/56692971
has answer: http://stackoverflow.com/a/70140244
has body: I am having issues installing PyAudio and portaudio. When I do python -m pip install pyaudio I get this error: src/_portaudiomodule.c(29): fatal error C1083: Cannot open include file: 'portaudio.h': No such file or directory error: command 'C:\\Program Files (x86)\\Microsoft Visual Studio\\2017\\Community\\VC\\Tools\\MSVC\\14.14.26428\\bin\\HostX86\\x86\\cl.exe' failed with exit status 2 ---------------------------------------- Command ""C:\Users\This PC\AppData\Local\Programs\Python\Python37-32\python.exe" -u -c "import setuptools, tokenize;__file__='C:\\Users\\THISPC~1\\AppData\\Local\\Temp\\pip-install-3ock7jqh\\pyaudio\\setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record C:\Users\THISPC~1\AppData\Local\Temp\pip-record-14pe9p6y\install-record.txt --single-version-externally-managed --compile" failed with error code 1 in C:\Users\THISPC~1\AppData\Local\Temp\pip-install-3ock7jqh\pyaudio\ So after looking that error up, I read I need to install portaudio. So I did python -m pip install portaudio and got this error: Collecting portaudio Could not find a version that satisfies the requirement portaudio (from versions: ) No matching distribution found for portaudio I have no idea where to go from here now.
tagged with: python
has answer: http://stackoverflow.com/a/73007969
has answer: http://stackoverflow.com/a/70815588
tagged with: pip
has title: How to fix installation issues for PyAudio, PortAudio: "fatal error C1083: Cannot open include file: 'portaudio.h': No such file or directory"
downvote count: 1
type: Question
has answer: http://stackoverflow.com/a/51992497
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/59594881
has answer: http://stackoverflow.com/a/52191687
has answer: http://stackoverflow.com/a/59594881
has answer: http://stackoverflow.com/a/58964710
has answer: http://stackoverflow.com/a/57042714
answer count: 11
tagged with: portaudio
tagged with: pyaudio
upvote count: 36

http://stackoverflow.com/q/52067118
upvote count: 1
answer count: 1
tagged with: variables
favorite count: 0
tagged with: python
type: UnansweredQuestion
has title: Python variable is not changing
score: -1
has answer: http://stackoverflow.com/a/52067209
tagged with: pyautogui
type: Question
downvote count: 2
has body: I have a variable that should be changing that is named "scrolldown". It will not change from 0 but I dont know why. Here is my code. Any help is appreciated. For some reason, whenever python prints the variable "scrolldown" it is always 0 no matter how many times it should have gone through 0 + 1. I have tried changing the variable from int(scrolldown) to scroll down and +1 to + 1 but neither works. The variable is defined at the start as '0' but I don't see why that would be causing issues. Why isnt this variable chaning when the script runs? scrolldownunits = int(903 - 553) scrolldown = 0 Test2 = True def movelisting(): print(scrolldown) for i in range(scrolldown): scrolldowncalc = scrolldown * int(scrolldownunits) * -1 pyautogui.scroll(scrolldowncalc) pyautogui.click() time.sleep(5) movelisting1 = 1 Test2 = False listingcheck() def listingcheck(): if Test2 == True: movelisting1 = 0 scrolldown = 0 if movelisting1 != 1: pyautogui.moveTo(914, 499) ##CLICK ON EBAY LISTING pyautogui.click() time.sleep(5) if pyautogui.locateOnScreen('NoClothing.png') != None: ###something not working here i = True o = pyautogui.locateOnScreen('BackArrow.png') print(o) p = pyautogui.center(o) pyautogui.click(p) time.sleep(5) pyautogui.moveTo(914, 499) time.sleep(2) scrolldown = scrolldown +1 movelisting() elif pyautogui.locateOnScreen('NoBikes.png') != None: ###SEARCHES FOR THINGS WE DONT WANT h = True c = pyautogui.locateOnScreen('BackArrow.png') d = pyautogui.center(c) pyautogui.click(d) time.sleep(5) pyautogui.moveTo(914, 499) time.sleep(2) scrolldown = scrolldown +1 movelisting() elif pyautogui.locateOnScreen('NoSelections.png') != None: g = True e = pyautogui.locateOnScreen('BackArrow.png') f = pyautogui.center(e) pyautogui.click(f) time.sleep(5) pyautogui.moveTo(914, 499) time.sleep(2) scrolldown = scrolldown +1 movelisting() listingcheck1 = True ##USED FOR VAR DELETE listingcapture() ###CONTINUES ONTO NEXT STEP

http://stackoverflow.com/q/52076323
has comment: http://stackoverflow.com/comment/91103375
tagged with: volume
tagged with: python
has answer: http://stackoverflow.com/a/52077149
accepted answer: http://stackoverflow.com/a/52077149
tagged with: mayavi
type: AnsweredQuestion
has body: I am trying to flip Z-axis in the mayavi volumetric 3D plot. I figured how to rotate the camera etc, but that is not what I want. I just want to flip the direction of Z-axis. Without manipulating the data itself #Minimum working example import numpy as np from mayavi import mlab x, y, z = np.ogrid[-5:5:64j, -5:5:64j, -5:5:64j] #Generate XYZ data = np.arange(x.shape[0]) x = x.ravel() y = y.ravel() z = z.ravel() mlab.points3d(x, y, z, data) #Produce volumetric plot mlab.axes(xlabel='X', ylabel='Y', zlabel='Z') #Display axis mlab.orientation_axes() mlab.show()
has comment: http://stackoverflow.com/comment/91105328
has title: Mayavi: How can I flip the Z-axis of a scene?
has comment: http://stackoverflow.com/comment/91102592
has comment: http://stackoverflow.com/comment/91102418
has comment: http://stackoverflow.com/comment/91102637
type: Question
score: 0
tagged with: 3d
has comment: http://stackoverflow.com/comment/91102534
tagged with: axis
answer count: 1
linked to: http://stackoverflow.com/q/2051744

http://stackoverflow.com/comment/91097471
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52073273
has text: tem_list = [] for x in list_7: if ('1'in x[0]) & ('4'in x[1]) & ('4'in x[2] or'1'in x[3]): tem_list.append('Engage') else: tem_list.append(None)
type: AnswerComment

http://stackoverflow.com/q/52021372
tagged with: python-decorators
tagged with: jupyter-notebook
upvote count: 2
type: UnansweredQuestion
tagged with: python
has body: I am writing a class that sends slack messages to users when processes have finished. I thought it would be useful to provide a Jupyter magic so that users can be notified when the cell is executed. The class already provides a decorator, so I figured I'd just wrap a cell execution in a decorated function. from IPython.core.magic import register_cell_magic from IPython import get_ipython import functools class MyClass(object): def decorate(self, f): @functools.wraps(f) def wrapped(*args, **kwargs): r = f(*args, **kwargs) print('Send a message here!') return r return wrapped @register_cell_magic def magic(self, line, cell): ip = get_ipython() @self.decorate def f(): return ip.run_cell(cell) return f() So then I'd do: obj = MyClass() # ----- NEW CELL %%obj.magic '''do some stuff''' But I get &gt;&gt; UsageError: Cell magic `%%obj.magic` not found. I found out that the magic is registered under its name (above, magic), so %%magic works. But then the arguments are all messed up because there is no self in the mix. I want the magic to be an instance method so that config (set in __init__ can be used). Is there any way to do this? Here are a couple hacky solutions I don't want to implement unless I really have to: Register a regular function with the instance as an argument. I don't want to add that line of code to the notebook, I want to use an instance method. Register a regular function that constructs an instance on the fly.
score: 2
has answer: http://stackoverflow.com/a/52021515
tagged with: methods
type: Question
downvote count: 0
answer count: 1
favorite count: 0
has title: Jupyter magic defined from instance method

http://stackoverflow.com/comment/91087582
comment on: http://stackoverflow.com/q/52068724
type: Comment
type: QuestionComment
has text: @DYZ Fair point
score: 0

http://stackoverflow.com/comment/91192405
type: AnswerComment
comment on: http://stackoverflow.com/a/52112494
type: Comment
has text: Oh, I forgot it, I have been able to solve it by making a simple trick that I read by there: repeating the same action n times (in this case n=4). I arrive to an average cumulative reward of ~40. Still, I want to understand why it diverges. Thanks so much.
score: 0

http://stackoverflow.com/q/52026877
accepted answer: http://stackoverflow.com/a/52027146
answer count: 1
has title: How to iterate over a tensor in Tensorflow?
favorite count: 0
tagged with: python
type: AnsweredQuestion
upvote count: 3
tagged with: tensorflow
type: Question
downvote count: 0
tagged with: neural-network
has answer: http://stackoverflow.com/a/52027146
has body: Say we got a tensor like thisx = [[[1,2],[3,4]],[[5,6],[7,8]]]. I want a tensorflow operation such that it returns adding 1 to every element of first nested tensor. i.e. the result the operation will return [[[2,3],[3,4]],[[6,7],[7,8]]]. I know the tf.map_fn operation, but I don't find a way to implement using this operation. How to solve this problem?
score: 3

http://stackoverflow.com/comment/91126114
comment on: http://stackoverflow.com/a/52087832
type: Comment
score: 0
type: AnswerComment
has text: @Julien Of course, but then I wouldn't demonstrate how to concatenate strings. In his real application there's likely to be variables involved.

http://stackoverflow.com/comment/99258610
type: QuestionComment
has text: I like how it's done in #django_rest_framework - a resource class has list() for getting the collection and retrieve() for getting just a single resource. I think it makes more sense, though flask-restful uses different approach as it seems
comment on: http://stackoverflow.com/q/51967215
score: 0
type: Comment

http://stackoverflow.com/comment/91091975
type: Comment
score: 0
has text: I can confirm that the actual file containing the source code is not empty. For some reason on clearing the cache now I am able to view the source code.
type: AnswerComment
comment on: http://stackoverflow.com/a/52052355

http://stackoverflow.com/a/51990193
score: 4
upvote count: 4
accepted answer of: http://stackoverflow.com/q/51990080
type: AcceptedAnswer
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/51990080
has body: This is expected behavior of rstrip: The chars argument is a string specifying the set of characters to be removed It is not just stripping the string _V2, it will strip any of the contained characters, including the 2 at the end of your second row. Instead, you may use a regular expression to replace a trailing _V2: df.assign(Subj_ID=df.Subj_ID.str.replace(r'_V2$', '')) Subj_ID lh_bankssts_area_base_V2 0 SILVA001 861 1 SILVA002 1051 2 SILVA004 1127 3 SILVA005 1346 4 SILVA007 1209

http://stackoverflow.com/comment/90884548
has text: Do you have installation permissions on the computer you are using?
type: QuestionComment
comment on: http://stackoverflow.com/q/51967269
score: 1
type: Comment

http://stackoverflow.com/a/51984419
has comment: http://stackoverflow.com/comment/90920413
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/90918725
has body: numbers[middle] is slicing of the list, which returns the element at middle position. It returns a single element, which is at the middle index, starting from 0.
type: Answer
accepted answer of: http://stackoverflow.com/q/51984344
answers question: http://stackoverflow.com/q/51984344
upvote count: 1
score: 1

http://stackoverflow.com/comment/91052238
comment on: http://stackoverflow.com/q/52050934
score: 0
has text: Do you know which byte positions are Latin-1 strings and which are binary data? If so, it's pretty easy.
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52003490
tagged with: list
has answer: http://stackoverflow.com/a/52003649
tagged with: join
possible better answer: http://stackoverflow.com/a/52003596
has answer: http://stackoverflow.com/a/52004087
has answer: http://stackoverflow.com/a/52003596
type: Question
score: 5
has answer: http://stackoverflow.com/a/52003637
upvote count: 5
accepted answer: http://stackoverflow.com/a/52003573
has answer: http://stackoverflow.com/a/52004213
has title: How to join list of integers into one integer python
has answer: http://stackoverflow.com/a/58695180
tagged with: byte
downvote count: 0
answer count: 7
tagged with: integer
favorite count: 0
tagged with: python
has comment: http://stackoverflow.com/comment/90956290
has answer: http://stackoverflow.com/a/52003573
has body: Given a list of hex integers, I want to end up with one hex integer where the integers are treated as most-significant first and least-significant last. For example, given... [0x1A, 0xF3, 0x74, 0xA3] ...I want to end up with 0x1AF374A3 In another programming language that I'm familiar with this is a fairly simple operation called "join", but apparently "join" means something else in Python. I know I can iterate through the list multiplying each subsequent element by 2^something and adding them. I also know I can convert the elements to strings, concatenate them and then convert back to integer. But both those approaches seem clunky. Seems like there should be a simpler / more elegant way. Is there? Thanks in advance for any help!
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/133918982

http://stackoverflow.com/a/52094151
type: Answer
score: 2
downvote count: 0
answers question: http://stackoverflow.com/q/52094131
upvote count: 2
has body: Instead of using pip install pygame, try to use python -m pip install pygame, it should work.

http://stackoverflow.com/q/51977418
answer count: 1
downvote count: 1
has answer: http://stackoverflow.com/a/51978977
tagged with: optimization
upvote count: 4
type: AnsweredQuestion
score: 3
accepted answer: http://stackoverflow.com/a/51978977
favorite count: 0
has title: Coordinate descent in Python
tagged with: python-3.x
type: Question
has body: I want to implement Coordinate Descent in Python and compare the result with that of Gradient Descent. I wrote the code. But it does not work well. GD is maybe ok, but CD is not good. This is the reference to Coordinate Descent. --- LINK And I expected this result Gradient Descent vs Coordinate Descent import pandas as pd import matplotlib.pyplot as plt import numpy as np x = np.linspace(10, 100, 1000) y = np.linspace(10, 100, 1000) def func(x, y, param): return param[0] * x + param[1] * y def costf(X, y, param): return np.sum((X.dot(param) - y) ** 2)/(2 * len(y)) z = func(x, y, [5, 8]) + np.random.normal(0., 10.) z = z.reshape(-1, 1) interc = np.ones(1000) X = np.concatenate([interc.reshape(-1, 1), x.reshape(-1, 1), y.reshape(-1, 1)], axis=1) #param = np.random.randn(3).T param = np.array([2, 2, 2]) def gradient_descent(X, y, param, eta=0.01, iter=100): cost_history = [0] * iter for iteration in range(iter): h = X.dot(param) loss = h - y gradient = X.T.dot(loss)/(2 * len(y)) param = param - eta * gradient cost = costf(X, y, param) #print(cost) cost_history[iteration] = cost return param, cost_history def coordinate_descent(X, y, param, iter=100): cost_history = [0] * iter for iteration in range(iter): for i in range(len(param)): dele = np.dot(np.delete(X, i, axis=1), np.delete(param, i, axis=0)) param[i] = np.dot(X[:,i].T, (y - dele))/np.sum(np.square(X[:,i])) cost = costf(X, y, param) #print(cost) cost_history[iteration] = cost return param, cost_history ret, xret = gradient_descent(X, z, param) cret, cxret = coordinate_descent(X, z, param) plt.plot(range(len(xret)), xret, label="GD") plt.plot(range(len(cxret)), cxret, label="CD") plt.legend() plt.show() Thank you in advance.
tagged with: gradient-descent
tagged with: python

linux
tags question: http://stackoverflow.com/q/52076262
tags question: http://stackoverflow.com/q/52090833
tags question: http://stackoverflow.com/q/52066816
tags question: http://stackoverflow.com/q/52096297
tags question: http://stackoverflow.com/q/51991089
tags question: http://stackoverflow.com/q/51973372
tags question: http://stackoverflow.com/q/52052649
type: Tag
tags question: http://stackoverflow.com/q/52054973
tags question: http://stackoverflow.com/q/52072144
tags question: http://stackoverflow.com/q/52059197
tags question: http://stackoverflow.com/q/52098616
tags question: http://stackoverflow.com/q/52046178
tags question: http://stackoverflow.com/q/51974294
tag name: linux
tags question: http://stackoverflow.com/q/52074241
tags question: http://stackoverflow.com/q/52022950
tags question: http://stackoverflow.com/q/52096669
tags question: http://stackoverflow.com/q/52060833
tags question: http://stackoverflow.com/q/52022551
tags question: http://stackoverflow.com/q/51973437
tags question: http://stackoverflow.com/q/51996068
tags question: http://stackoverflow.com/q/52013452
tags question: http://stackoverflow.com/q/52110942
tags question: http://stackoverflow.com/q/51967444
tags question: http://stackoverflow.com/q/52104308
tags question: http://stackoverflow.com/q/52043041
tags question: http://stackoverflow.com/q/52008104
tags question: http://stackoverflow.com/q/52105383

http://stackoverflow.com/comment/90974042
comment on: http://stackoverflow.com/a/52011235
type: AnswerComment
score: 0
type: Comment
has text: @user2179795 Can you [edit] your question to give us a complete example, with sample data? Also, do you get 1970 even when running exactly the code in this answer, or only with your sample data? If so, what versions of Python and Pandas (and, while we're at it, dateutil) do you have?

http://stackoverflow.com/a/51990487
score: 1
upvote count: 1
has body: Use .findNext("td").text Ex: from bs4 import BeautifulSoup soup = BeautifulSoup(html, "html.parser") for tr in soup.find_all("tr"): print(tr.td.findNext("td").text) Output: Michael Clara Lisa Joe John Francesca Carlos
has comment: http://stackoverflow.com/comment/90935334
type: Answer
answers question: http://stackoverflow.com/q/51990272
downvote count: 0

http://stackoverflow.com/comment/91029348
has text: @Mathieu I am very new to multithreading/processing any help is great.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52039134

http://stackoverflow.com/a/52054780
score: 0
has body: You can read more about form.is_valid() here. A Form instance has an is_valid() method, which runs validation routines for all its fields. When this method is called, if all fields contain valid data, it will: 1) return True 2) place the form’s data in its cleaned_data attribute. def some_create_view(request, category_id): if request.method == 'POST': form = CategoryFieldsForm(category_id, request.POST) if form.valid(): # you should be able to access the form cleaned data here ....
type: Answer
answers question: http://stackoverflow.com/q/52054446

http://stackoverflow.com/comment/90902506
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51973529
score: 1
has text: @WiktorStribiżew Happy to and upvoted. You gave a nice comprehensive answer.

http://stackoverflow.com/a/54281076
upvote count: 7
answers question: http://stackoverflow.com/q/52051996
score: 7
downvote count: 0
type: Answer
has body: This is an issue that has been annoying me, so I took a look at the pyautogui source code and was able to solve the problem. This will probably be quite a long answer; I'll try to explain every step in detail. Note that this only works for Mac. (scroll to the bottom if you want the answer, not the explanation) First, here is the source code for the scroll function: def _scroll(clicks, x=None, y=None): _vscroll(clicks, x, y) def _vscroll(clicks, x=None, y=None): _moveTo(x, y) clicks = int(clicks) for _ in range(abs(clicks) // 10): scrollWheelEvent = Quartz.CGEventCreateScrollWheelEvent( None, # no source Quartz.kCGScrollEventUnitLine, # units 1, # wheelCount (number of dimensions) 10 if clicks &gt;= 0 else -10) # vertical movement Quartz.CGEventPost(Quartz.kCGHIDEventTap, scrollWheelEvent) scrollWheelEvent = Quartz.CGEventCreateScrollWheelEvent( None, # no source Quartz.kCGScrollEventUnitLine, # units 1, # wheelCount (number of dimensions) clicks % 10 if clicks &gt;= 0 else -1 * (-clicks % 10)) # vertical movement Quartz.CGEventPost(Quartz.kCGHIDEventTap, scrollWheelEvent) Let's break this down: 1. def _scroll(clicks, x=None, y=None): _vscroll(clicks, x, y) This is just a wrapper for the _vscroll function, simple enough. 2. The main thing to realise is that pyautogui, for Mac, uses Quartz Core Graphics, all it does is provide a simpler, more readable wrapper for the Quartz code. With the scroll function, what it is doing is creating a scroll event: scrollWheelEvent = Quartz.CGEventCreateScrollWheelEvent And then posting it: Quartz.CGEventPost(Quartz.kCGHIDEventTap, scrollWheelEvent) Ignore the details of the posting, we won't be changing any of that. To me, it seems as if this code repeats itself, and I have no clue why any of the code after the for loop is included. I deleted this from my source code and everything works; If anyone knows why this code is included, please comment below and correct me. 3. So we are left with the following code (ignoring the mouse move…

http://stackoverflow.com/comment/91071707
has text: Your code seems okay. Probably your data is unbalanced e.g: number of negative tweets is much more than positive/neutral.
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/52060555

http://stackoverflow.com/q/51961513
has title: How to get a flask end point with user selected variables?
tagged with: python
tagged with: jinja2
has comment: http://stackoverflow.com/comment/90876174
has comment: http://stackoverflow.com/comment/90873634
has comment: http://stackoverflow.com/comment/90877199
type: Question
has comment: http://stackoverflow.com/comment/90876887
has comment: http://stackoverflow.com/comment/90874036
tagged with: javascript
tagged with: flask
score: 0
has body: I am building a web page to show all member account information in a data table. So I made a "members" end point with GET method for this. The web page have 2 selection fields to choose a region and member type to filter out members that display in the data table. The members end point is like this @members.route('/members/<int:region_id> <string:member_type>', defaults={'page': 1}) def members(page, region_id=0, member_type='basic'): member_accounts = MemberModel.query .filter_by(region_id=region_id)\ .filter_by(member_type=member_type)\ .paginate(page, 25, True) return render_template('members.html', member_accounts=member_accounts， region_choices=region_choices, type_choices=type_choices) // region_choices and type_choices are dict type data So, the default url is domain/members/0%20basic, which showing members from region 0 and type is basic. In members.html, I made 2 selection fields for filtering data. Also has a script to make GET request to the end point with selected variables by clicking submit button. {% for value, text in region_choices.items() %} {{ text }} {% endfor %} {% for value, text in mem_type_choices.items() %} {{ text }} {% endfor %} Submit When I select region_id to 1 and member_type to 'admin', then click the submit button. I expect the website will direct to my desired url (domain/members/1%20admin). But this is fail to direct to my desired url. How can I do such filter function properly? Does constructing a GET request url by javascript a preferred method to do this? cause I have to hard code the domain in the javascript. Should I build another end point for filtering? Update modified end point to '/member/' added request.get.args('region_id') added request.get.args('member_type') Also modified the url in javascript as, 'var params = "?" + "region_id=" + region_id_selected + "&member_type=" + mem_type_selected";' and 'var Url = "/members/" + params;'
tagged with: http://stackoverflow.com/tag/html
answer count: 0
has comment: http://stackoverflow.com/comment/90873783
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90873753

http://stackoverflow.com/q/52010473
score: 1
type: Question
has comment: http://stackoverflow.com/comment/90972030
has comment: http://stackoverflow.com/comment/90972068
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/90974880
upvote count: 1
has comment: http://stackoverflow.com/comment/90972002
answer count: 1
accepted answer: http://stackoverflow.com/a/52012245
favorite count: 0
tagged with: tkinter
linked to: http://stackoverflow.com/q/10214701
has body: I'm trying to make a Tkinter based GUI for an Arduino printing sensors value and responding to user input. The code I'm trying to use to eliminate while loops is this, which doesn't print any sensor information, the only output is "Trying.../dev/ttyACM0" followed by the tkinter window opening. import serial import time from Tkinter import * connected = False write_to_file_path = "output.txt" output_file = open(write_to_file_path, "w+") locations=['/dev/ttyACM0','/dev/ttyACM1','/dev/ttyACM2','/dev/ttyACM3'] for device in locations: try: print "Trying...",device ser = serial.Serial(device, 9600) break except: print "Failed to connect on",device ## loop until the arduino tells us it is ready while not connected: serin = ser.read() connected = True time.sleep(0.1) ser.flushInput() time.sleep(1) def serialRead(): if ser.inWaiting(): line = ser.readline() data = line.decode("utf-8").split('\t') print(data) output_file.write(line) root.after(1000, serialRead) root = Tk() root.title("Temperature Control") serialRead() root.mainloop() This, on the other hand, works perfectly with the exception of not having a tkinter window. But it removes old input from the buffer and reads in the new input. import serial import time connected = False write_to_file_path = "output.txt" output_file = open(write_to_file_path, "w+") serial_port = '/dev/ttyACM0' baud_rate = 9600 ser = serial.Serial(serial_port, baud_rate, timeout=5) time.sleep(0.1) ser.flushInput() time.sleep(1) while True: if ser.inWaiting(): line = ser.readline() data = line.decode("utf-8").split('\t') #ser.readline returns a binary, convert to string print data[0] + '\t' + data[1] output_file.write(line) This was inspired by a different stackoverflow post from a while ago: Run an infinite loop in the backgroung in Tkinter I've seen some example using threading but I don't know much about python nor threading so I'd really like to get it to work with root.after() if that's possible. I've also tried the example using root.after…
tagged with: python
has comment: http://stackoverflow.com/comment/90971826
has answer: http://stackoverflow.com/a/52012245
type: AnsweredQuestion
has title: Reading serial input and printing to Tkinter GUI
downvote count: 0

http://stackoverflow.com/comment/91069231
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52055979
type: AnswerComment
has text: You're onto something here but since you gave me this answer I have discovered another problem. I have 2 plots in separate cells in one Jupyter notebook. One has "%matplotlib inline" and one has "%matplotlib notebook" and I can't find a way to switch between them without the error on the first run of the cell, second run it works fine.

http://stackoverflow.com/q/52079246
tagged with: hyperlink
has comment: http://stackoverflow.com/comment/91108724
type: Question
answer count: 1
has comment: http://stackoverflow.com/comment/91113545
has answer: http://stackoverflow.com/a/52079676
score: 0
linked to: http://stackoverflow.com/q/3582671
tagged with: http://stackoverflow.com/tag/html
tagged with: python
has comment: http://stackoverflow.com/comment/91108689
has comment: http://stackoverflow.com/comment/91223988
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91113501
has title: Run a python program from browser
has body: I want to run a python program (kinda like this) from a browser Anyway, as you see it has a few inputs, and i would like to "translate" that into a kind of form def addNew(): appendBase = open('dBase.cfg','a') uname = input('Username: ') pword = input('Password: ') appendBase.write(uname+','+pword+'\n') print('\nAdded new profile: \n'+uname+','+pword) appendBase.close() Also i dont know how to get the print to the page, so it can show it I've just started learning, so go easy on me, please

http://stackoverflow.com/comment/90876225
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51962392
has text: can't really understanding without seeing the data. What happens when you run `x[1][0] in y[1] and x[1][2] in y[1]`? This code assumes that y is a list of lists. If y is only a list of strings, what happens when you run `x[1][0] in y and x[1][2] in y`?

http://stackoverflow.com/a/52106333
answers question: http://stackoverflow.com/q/52106273
type: Answer
has body: Loop over items(). You can use comprehension (no need to use [ ] as it is in parenthesis already): print(k for k,v in humans.items() if v &gt; 20) or really loop: for k,v in humans.items(): if v &gt; 20: print(k)
score: 3
downvote count: 0
upvote count: 3

http://stackoverflow.com/q/52094075
has answer: http://stackoverflow.com/a/52094308
type: AnsweredQuestion
tagged with: performance
has answer: http://stackoverflow.com/a/52094193
accepted answer: http://stackoverflow.com/a/52094193
score: 4
type: Question
answer count: 2
has title: Difference in foreign key lookup through object.fk.id and object.fk_id
has body: I have not found this question on SO. Is there a speed difference between the following two variants of doing foreign key lookup in django's object model? I only need the foreign key. class A(models.Model): x = models.PositiveIntegerField(null=True) class B(models.Model): a = models.ForeignKey(A, null=True, on_delete=models.CASCADE) y = models.PositiveIntegerField(null=True) b = b.objects.last() Which is faster or are they the same? b.a_id b.a.id edit: Actually I think I can answer it myself... the second variant should be slower since it creates the whole object from the db, right?
favorite count: 0
has comment: http://stackoverflow.com/comment/91138391
tagged with: python
upvote count: 4
possible better answer: http://stackoverflow.com/a/52094308
downvote count: 0
tagged with: django

http://stackoverflow.com/q/51968769
tagged with: naivebayes
type: UnansweredQuestion
has title: Getting feature importance in Naive bayes
score: 2
tagged with: scikit-learn
has answer: http://stackoverflow.com/a/52254391
favorite count: 0
has comment: http://stackoverflow.com/comment/90910876
type: Question
tagged with: python
has body: My problem is exactly similar to this, How to get feature Importance in naive bayes? but when I run the code neg_class_prob_sorted = NB_optimal.feature_log_prob_[0, :].argsort() pos_class_prob_sorted = NB_optimal.feature_log_prob_[1, :].argsort() print(np.take(count_vect.get_feature_names(), neg_class_prob_sorted[:10])) print(np.take(count_vect.get_feature_names(), pos_class_prob_sorted[:10])) it always prints words with same initials ['aafco' 'misfit' 'misfir' 'miseri' 'miser' 'misconcept' 'miscarriag' 'misc' 'mirin' 'minuscul'] ['aafco' 'metrx' 'meticul' 'methood' 'metaplus' 'metaphor' 'mestemach' 'messiest' 'mesmer' 'mesa'] Is there any better way I can print the important features corrosponding to positive and negative class?
upvote count: 3
tagged with: machine-learning
answer count: 1
downvote count: 1
linked to: http://stackoverflow.com/q/50526898
tagged with: feature-selection

peewee
tag name: peewee
type: Tag
tags question: http://stackoverflow.com/q/52096473
tags question: http://stackoverflow.com/q/51969803
tags question: http://stackoverflow.com/q/52104374
tags question: http://stackoverflow.com/q/52059108

http://stackoverflow.com/q/51998753
type: Question
has title: Get Logging Output of another Script
tagged with: python
tagged with: logging
has comment: http://stackoverflow.com/comment/90947070
has comment: http://stackoverflow.com/comment/90949137
score: 0
has comment: http://stackoverflow.com/comment/90952373
has comment: http://stackoverflow.com/comment/90946867
has comment: http://stackoverflow.com/comment/90946712
has comment: http://stackoverflow.com/comment/90947167
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90952651
has body: So basicly I want to start a Script from my Flask Webservice and want to get the Logging output of that Script. Problem is that the called script does not have a class only for logging, logging always happens at the end of a script which is doing something. Is it possible to catch that Logging output in any way? EDIT: for example I have this script: #!/usr/bin/env python3 # encoding: utf-8 import logHelper as lh import rest_trigger_configparser as c lh.init(c.get(c.LOG_PATH), 'CallExternalService_%Y_%m_%d_%H_%M.log',\ 'CallExternalService_%Y_%m_%d_', c.get(c.LOG_LEVEL_NAME)) def thing(): try: print("Nice") except Exception as exc: lh.logException(str(exc)) And now I want to catch that Logexception from another script that starts this one
answer count: 0
has comment: http://stackoverflow.com/comment/90964734
tagged with: python-3.x

http://stackoverflow.com/comment/91060771
has text: the same error: `django.db.utils.IntegrityError: datatype mismatch`
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/52041675
type: Comment

http://stackoverflow.com/a/51971005
has comment: http://stackoverflow.com/comment/90938102
has body: You may need to just do some manual cleaning-up before reading into a DataFrame: &gt;&gt;&gt; import json &gt;&gt;&gt; import pandas as pd &gt;&gt;&gt; def collapse_lists(data): ... return [{k: v[0] if (isinstance(v, list) and len(v) == 1) ... else v for k, v in d.items()} for d in data] &gt;&gt;&gt; with open('state.json') as f: ... data = pd.DataFrame(collapse_lists(json.load(f)['State'])) &gt;&gt;&gt; data sensor ts value 0 accBodyX_ftPerSec2 2018-04-11T21:37:05.401Z NaN 1 accBodyX_ftPerSec2 2018-04-11T21:37:05.901Z -3.389190 2 accBodyY_ftPerSec2 2018-04-11T21:37:05.901Z -2.004781 3 accBodyZ_ftPerSec2 2018-04-11T21:37:05.901Z -34.776940 This loads the JSON file into a Python list of dictionaries, converts any length-1 lists into scalar values, and then loads that result into a DataFrame. That is admittedly not the most efficient means, but your other option of parsing the JSON itself is probably overkill unless the file is massive. Finally, to convert to datetime: &gt;&gt;&gt; data['ts'] = pd.to_datetime(data['ts']) &gt;&gt;&gt; data.dtypes sensor object ts datetime64[ns] value float64 dtype: object You may also want to consider converting sensor to a categorical data type to save a possibly significant amount of memory: The memory usage of a Categorical is proportional to the number of categories plus the length of the data. In contrast, an object dtype is a constant times the length of the data. (source) In explicit-loop form, this would look like: def collapse_lists(data): result = [] for d in data: entry = {} for k, v in d.items(): if isinstance(k, list) and len(v) == 1: entry.update({k: v[0]}) else: entry.update({k: v}) result.append(entry) return result
answers question: http://stackoverflow.com/q/51970315
has comment: http://stackoverflow.com/comment/90894423
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51970315
has comment: http://stackoverflow.com/comment/90894405
type: Answer
has comment: http://stackoverflow.com/comment/90894165
has comment: http://stackoverflow.com/comment/90961122
score: 1
upvote count: 1

http://stackoverflow.com/q/51975951
downvote count: 0
tagged with: keras
has title: Keras Recurrent Neural Networks For Multivariate Time Series
favorite count: 0
type: Question
tagged with: python
score: 4
has body: I have been reading about Keras RNN models (LSTMs and GRUs), and authors seem to largely focus on language data or univariate time series that use training instances composed of previous time steps. The data I have is a bit different. I have 20 variables measured every year for 10 years for 100,000 persons as input data, and the 20 variables measured for year 11 as output data. What I would like to do is predict the value of one of the variables (not the other 19) for the 11th year. I have my data structured as X.shape = [persons, years, variables] = [100000, 10, 20] and Y.shape = [persons, variable] = [100000, 1]. Below is my Python code for a LSTM model. ## LSTM model. # Define model. network_lstm = models.Sequential() network_lstm.add(layers.LSTM(128, activation = 'tanh', input_shape = (X.shape[1], X.shape[2]))) network_lstm.add(layers.Dense(1, activation = None)) # Compile model. network_lstm.compile(optimizer = 'adam', loss = 'mean_squared_error') # Fit model. history_lstm = network_lstm.fit(X, Y, epochs = 25, batch_size = 128) I have four (related) questions, please: Have I coded the Keras model correctly for the data structure I have? The performance I get from a fully-connected network (using flattened data) and from LSTM, GRU, and 1D CNN models are nearly identical, and I don't know if I have made an error in Keras or if a recurrent model is simply not helpful in this case. Should I have Y as a series with shape Y.shape = [persons, years] = [100000, 11], rather than including the variable in X, which would then have shape X.shape = [persons, years, variables] = [100000, 10, 19]? If so, how can I get the RNN to output the predicted sequence? When I use return_sequences = True, Keras returns an error. Is this the best way to predict with the data I have? Are there better option choices available in the Keras RNN models, or even other models? How could I simulate data resembling the data structure I have so that a RNN model would outperform a fully-connected n…
has answer: http://stackoverflow.com/a/51976383
answer count: 1
tagged with: time-series
tagged with: recurrent-neural-network
upvote count: 4
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51976383

http://stackoverflow.com/a/52083754
upvote count: 1
score: 1
type: AcceptedAnswer
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/52063337
has body: I found the error and the solution is to be careful. One of my Django legacy-app suddenly has another Celery instance which was trying to start with another settings and broke everything.
answers question: http://stackoverflow.com/q/52063337

http://stackoverflow.com/q/52066617
has comment: http://stackoverflow.com/comment/91345855
score: 9
type: Question
has comment: http://stackoverflow.com/comment/91335495
tagged with: django-admin
answer count: 1
favorite count: 0
has title: ForeignKey fields in add/change forms - Django admin
has answer: http://stackoverflow.com/a/52068982
tagged with: python
has comment: http://stackoverflow.com/comment/91358332
has body: Say I have these models as a simple example: class Event(models.Model): name = models.CharField(max_length=50, default='') app = models.ForeignKey(App) class App(models.Model): name = models.CharField(max_length=50, default='') app_config = models.ForeignKey(AppConfig) class AppConfig(models.Model): type = models.CharField(max_length=50, default='') is_valid = models.BooleanField(default=True) I want to create an Admin page with add/change forms for Event that will allow me to select an App and create AppConfig with all its fields. Basically, to have a form with a dropdown to choose an App and below it a form to fill in the AppConfig fields. Or even just a "+" sign or a link that will popup a form to create an AppConfig. I saw many examples of how to add this to the list_display (such as this) but couldn't manage to do the same with fields or fieldsets in order to have it in the add/change form as well. Any suggestions will be appreciated. Thanks! Note: I know that this might be easily solved if I also had AppConfig as a foreign key in Event but this doesn't really make sense. Edit: My Django and Python versions: Python: 2.7.x Django: 1.7.4 Edit2: I have found this nice open-source code django_reverse_admin which might be helpful, but first, this specific package support only Django 2.0+. I tried to use the original code which does seem to support previous Django versions but didn't manage to apply it to my specific case. If anyone have an idea or can show me how to use this in my specific case it will be great. Thanks!
upvote count: 9
linked to: http://stackoverflow.com/q/9853595
has comment: http://stackoverflow.com/comment/91358400
downvote count: 0
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/7009010
tagged with: django
has comment: http://stackoverflow.com/comment/91358729
has comment: http://stackoverflow.com/comment/91354852
tagged with: django-forms

http://stackoverflow.com/comment/91146030
type: QuestionComment
has text: If anything you want then please let me know. Thanks
comment on: http://stackoverflow.com/q/52082123
score: 0
type: Comment

pytest
tags question: http://stackoverflow.com/q/52055788
tags question: http://stackoverflow.com/q/51969805
tags question: http://stackoverflow.com/q/52030518
tags question: http://stackoverflow.com/q/52038748
tags question: http://stackoverflow.com/q/52100035
tag name: pytest
tags question: http://stackoverflow.com/q/52078191
tags question: http://stackoverflow.com/q/52086974
tags question: http://stackoverflow.com/q/51990413
tags question: http://stackoverflow.com/q/51992496
tags question: http://stackoverflow.com/q/52078823
tags question: http://stackoverflow.com/q/51992562
tags question: http://stackoverflow.com/q/52042642
tags question: http://stackoverflow.com/q/51988331
tags question: http://stackoverflow.com/q/52032885
tags question: http://stackoverflow.com/q/52102065
tags question: http://stackoverflow.com/q/51976104
tags question: http://stackoverflow.com/q/52059605
tags question: http://stackoverflow.com/q/51988317
tags question: http://stackoverflow.com/q/52077389
tags question: http://stackoverflow.com/q/52030839
tags question: http://stackoverflow.com/q/52041802
tags question: http://stackoverflow.com/q/52002325
tags question: http://stackoverflow.com/q/51987078
tags question: http://stackoverflow.com/q/52072085
tags question: http://stackoverflow.com/q/51991220
tags question: http://stackoverflow.com/q/52081556
tags question: http://stackoverflow.com/q/52018430
tags question: http://stackoverflow.com/q/52049297
tags question: http://stackoverflow.com/q/51984719
tags question: http://stackoverflow.com/q/52044490
tags question: http://stackoverflow.com/q/52060950
tags question: http://stackoverflow.com/q/51965320
type: Tag

http://stackoverflow.com/a/51988289
type: Answer
has comment: http://stackoverflow.com/comment/90927428
answers question: http://stackoverflow.com/q/51987840
has comment: http://stackoverflow.com/comment/90929709
has body: There is the PYC-only distribution, that installed instead of your regular python package will accomplish the goal. However the attacker could just bring their own python if they are able to create files on your server. How about disallowing writing new files in the directory (assuming you're using linux it's # chmod ugo-w &lt;dirname&gt;) EDIT: Maybe a good solution would be to ditch python interpreter and VM completely on the production machine, compile scripts with Nuitka, and put execuables created by Nuitka in the write-forbidden directory.
score: 0
has comment: http://stackoverflow.com/comment/90929017
has comment: http://stackoverflow.com/comment/90926288

http://stackoverflow.com/q/51973153
tagged with: python
has title: Transposing in a specific order using Pandas
answer count: 0
score: 0
has comment: http://stackoverflow.com/comment/90896955
has comment: http://stackoverflow.com/comment/90897479
type: Question
has comment: http://stackoverflow.com/comment/90896763
has comment: http://stackoverflow.com/comment/90896721
tagged with: pandas
has body: I have a df that looks like this: EmpID Obs_ID Component Rating avg_2a avg_2d avg_3b avg_3c avg_3d 01301 13943 2a 3 3.0 3.0 1.0 1.33 1.0 01301 13944 2a 3 3.0 3.0 1.0 1.33 1.0 01301 13945 2a 3 3.0 3.0 1.0 1.33 1.0 01301 13945 2d 3 3.0 3.0 1.0 1.33 1.0 01301 13945 3b 3 3.0 3.0 1.0 1.33 1.0 And I need it to look like this: EmpID comp_2a_obs_1 comp_2a_obs_2 comp_2a_obs_3 comp_2d_obs_1 ... ... comp_2a_avg comp_2d_avg comp_3b_avg comp_3c_avg comp_3d_avg 01301 3 3 3 3 ... ... 3.0 3.0 1.0 1.33 1.0 Where the obs order (obs_1, obs_2, obs_3) is based on the Obs_ID (smallest to largest) and the value of the comp_2a_obs_1, etc columns are drawn from Rating Can I do this with pd.Transpose or would I need a for loop or something else?
tagged with: python-3.x
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90900489

http://stackoverflow.com/comment/91156430
has text: When you say lexicographical order, you mean character by character or element by element? By example, which of these is ordered: [[100, 0], [90, 0]] or [[90, 0], [100, 0]]
comment on: http://stackoverflow.com/q/52102724
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91034142
type: AnswerComment
score: 0
type: Comment
has text: I don't know the precise reason the question was downvoted, but likely because you hadn't attempted the problem which some people don't like... Anyway, since this answer does solve this problem, you should accept it. There is no way (as far as I know) of forcing the `open()` function to provide a warning.
comment on: http://stackoverflow.com/a/52040099

http://stackoverflow.com/comment/91055510
comment on: http://stackoverflow.com/q/52052566
type: Comment
score: 0
has text: Is there only one line per day or could there be days spread over several lines?
type: QuestionComment

http://stackoverflow.com/q/51957188
linked to: http://stackoverflow.com/q/35045924
score: 0
has comment: http://stackoverflow.com/comment/90865205
answer count: 3
has title: What is the malware associated with pywin32
has comment: http://stackoverflow.com/comment/90866417
tagged with: pywin32
has answer: http://stackoverflow.com/a/51957384
downvote count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/51957956
has answer: http://stackoverflow.com/a/51957492
tagged with: malware
tagged with: python
possible better answer: http://stackoverflow.com/a/51957956
has comment: http://stackoverflow.com/comment/90866349
type: AnsweredQuestion
has body: I tried to download the pywin32 package off github and am unable to as my antivirus software keeps deleting it (Message is- Security risk detected: Heur.AdvML.C). It is the same complaint that was outlined in this thread: pywin32-220 installer "high risk" file I have been using an the pywin32 package of python 2.7 for years but am switching to ArcPro and need to upgrade my scripts to the python 3.6 version. I need to have this to run my scripts and was hoping someone could tell me what the virus captures so we can weigh whether it is ok to download. With all the recommendations to download this, I would think someone out there would have knowledge of what the risk was. I tried to download it from the official website: https://github.com/mhammond/pywin32/releases Any ideas how I can get a clean version? Many thanks
type: Question
upvote count: 1
has comment: http://stackoverflow.com/comment/90865031
accepted answer: http://stackoverflow.com/a/51957384

http://stackoverflow.com/comment/90999629
comment on: http://stackoverflow.com/q/52014546
type: Comment
has text: What OS are you on? There are some significant differences in the out-of-the-box multiprocessing behaviour between Windows and non-Windows platforms.
score: 0
type: QuestionComment

http://stackoverflow.com/comment/91122716
comment on: http://stackoverflow.com/q/52086166
type: Comment
type: QuestionComment
has text: What is the point of that output dict?
score: 0

http://stackoverflow.com/comment/91131089
has text: Possible duplicate of [How to sort (list/tuple) of lists/tuples?](https://stackoverflow.com/questions/3121979/how-to-sort-list-tuple-of-lists-tuples)
comment on: http://stackoverflow.com/q/52090587
type: Comment
type: QuestionComment
score: 1

http://stackoverflow.com/comment/91053894
has text: then only can access it from odoo after that
type: Comment
comment on: http://stackoverflow.com/a/52051613
score: 0
type: AnswerComment

http://stackoverflow.com/comment/91767058
type: QuestionComment
score: 1
has text: Tnx , It's work very nice
comment on: http://stackoverflow.com/q/52026079
type: Comment

http://stackoverflow.com/comment/91018379
type: QuestionComment
score: 3
comment on: http://stackoverflow.com/q/52034239
has text: Why do you need to have all the combinations in memory at the same time?
type: Comment

http://stackoverflow.com/a/52073519
has body: I wouldn't create test_urls.py at all. Anyway, you will assert response status code while testing views. def test_get_users(self): for i in range(3): user = User(name='Test user {}'.format(i)) user.save() path = reverse('users') response = self.client.get(path) self.assertEqual(response.status_code, 200) self.assertEqual(len(response['users']), 3)
type: Answer
answers question: http://stackoverflow.com/q/52073187
score: 0

http://stackoverflow.com/q/51999725
possible better answer: http://stackoverflow.com/a/52000068
has answer: http://stackoverflow.com/a/52000068
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52000146
upvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/90966554
has body: I have the following data of job details, one of them is job_detail = { "company": "abc company recruit", "job_title": "python developer", "job_request": "20k-40k /Delhi / 3-5years / Bachelor / Full-time", "job_tags": "Big Data\nSoftware Development", "pub_date": "10:19 published from network", } I tried to extract and format it with the following code: job_detail["company"] = job_detail["company"].replace("recruit", "").strip() job_detail["job_title"] = job_detail["job_title"].strip() job_request = [jr.strip() for jr in job_detail["job_request"].split("/")] salary, location, experience, education, time = job_request job_detail['salary'] = salary job_detail['location'] = location job_detail['experience'] = experience job_detail["education"] = education job_detail['time'] = time job_detail["job_tags"] = job_detail["job_tags"].replace("\n", ",") job_detail['pub_date'] = re.search(r"\w+", job_detail["pub_date"]).group() Run it an come by In [81]: job_detail Out[81]: {'company': 'abc company', 'job_title': 'python developer', 'job_request': '20k-40k /Delhi / 3-5years / Bachelor / Full-time', 'job_tags': 'Big Data,Software Development', 'pub_date': '10', 'salary': '20k-40k', 'location': 'Delhi', 'experience': '3-5years', 'education': 'Bachelor', 'time': 'Full-time'} I get the desired data with too many typing of "job_details", and every item should be copied on every line. How could I solve the problem in an elegant way?
accepted answer: http://stackoverflow.com/a/52000146
has title: Update dict's value without too many copies of items
answer count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/90948506
score: 1
favorite count: 0

http://stackoverflow.com/q/52001137
has title: Create a list depending on variance of elements
answer count: 1
tagged with: variance
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/52001638
type: Question
has body: I want to get a list of consecutive segments which are parts of a linestring (QGIS, Shapefile) and build up a nearly straight section of the linestring. In the moment I can calculate the azimuth of the segments and put them to a list. az_list = [260,263,260,209,245,339,337,343] So at first I thought about to fill up a new list with the elements of the az_list until the variance is to high. Example: The first three values of az_list 260, 263, 260 built up a nearly straight section of a line. I check the variance of these three values with: import numpy as np np.var([260, 263, 260]) # result: 2.0 And for the last three one: np.var([339,337,343]) # result: 6.22... Knowing that, I could determine that for a variance var a section is straight when var &gt; 0 and var &lt; 10 and if the list is empty (which will be the start point) math.isnan(np.var(az_list)) returns False. I start to put the first three values from az_list to the new list straight_list. With this code I tried to make this running but it returns an empty list. straight_list = [] while not math.isnan(np.var(straight_list)) and np.var(straight_list) != 0 and np.var(straight_list) &lt; 10: for i in az_list: straight_list.append(i) Finally a want to achieve a list of list where the straight sections are stored, like: straight_list = [[260,263,260],[339,337,343]]
score: 0
tagged with: while-loop

http://stackoverflow.com/comment/91038572
type: QuestionComment
has text: If you are rewriting it in C for performance reasons, then why do you insist on writing it recursive? The primary reason for writing recursive functions is that it makes the code clean, short and easy to read.
score: 2
comment on: http://stackoverflow.com/q/52043718
type: Comment

http://stackoverflow.com/comment/90899639
score: 0
has text: Oops! I meant to delete that, I replaced it with "get_dollars" to pull the dollars from the json file, but I'm not sure if this will pull a leaderboard the way I want it.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51973615

http://stackoverflow.com/comment/91067400
type: AnswerComment
type: Comment
has text: so i've tried to change the value of b into the index of last data, so that problem should be solved but i still got the same error. It says got something to do with the centroid.append(x[new_cen_idx])
comment on: http://stackoverflow.com/a/52054771
score: 0

http://stackoverflow.com/comment/91054804
score: 3
has text: What if they aren't in series or continuous?
comment on: http://stackoverflow.com/q/52052295
type: Comment
type: QuestionComment

http://stackoverflow.com/a/51973780
type: Answer
answers question: http://stackoverflow.com/q/51973105
upvote count: 0
score: -1
has body: i am unable to understand your 1st part of the question. i found a simple implementation for the 2nd part to your question Bob={} Bob=dict.fromkeys(mydict) The above will copy the keys from one dictionary to Bob. for key,val in Bob.items(): Bob[key]=input() Above code inputs the values for the copied keys.
downvote count: 1

http://stackoverflow.com/comment/90923877
type: Comment
score: 0
type: AnswerComment
has text: Great idea! i did this and it seems like it cant locate bubble.png allthough you can see it in this picture: http://oi68.tinypic.com/fk5pfl.jpg
comment on: http://stackoverflow.com/a/51986582

http://stackoverflow.com/comment/91153810
type: QuestionComment
has text: I've added a console.log(file_type); and see Uncaught TypeError: Cannot read property '0' of undefined at HTMLInputElement.uploadField.onchange (one_button.js:5). Looking into it now
comment on: http://stackoverflow.com/q/52101331
score: 0
type: Comment

http://stackoverflow.com/comment/90944478
type: Comment
comment on: http://stackoverflow.com/q/51997610
has text: Hello, welcome to StackOverflow. It looks like you have identified your problem as being at the 'cleaning' stage. Show some of your data.
score: 0
type: QuestionComment

http://stackoverflow.com/comment/91001441
score: 5
has text: You never *called* `set_y`. *Calling* is done with parentheses().
comment on: http://stackoverflow.com/q/52025639
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91028417
type: Comment
comment on: http://stackoverflow.com/q/52038209
has text: I was able to edit it and recreate the problem too.
score: 0
type: QuestionComment

http://stackoverflow.com/comment/91052536
type: AnswerComment
has text: there is a logs file and i read from this logs file and display the output.
type: Comment
comment on: http://stackoverflow.com/a/52050797
score: 0

http://stackoverflow.com/a/52056168
has comment: http://stackoverflow.com/comment/91064046
downvote count: 0
type: AcceptedAnswer
has body: This should work here, you have to manually set up bin boundaries: bins = [1000000,2000000,3000000,4000000,12000000] print(bins) labels = pd.cut(data['PRICE'], bins, right= True) labels = labels.value_counts().sort_index() labels Also, have a look here for different answers on that topic: Binning column with python pandas
answers question: http://stackoverflow.com/q/52055852
accepted answer of: http://stackoverflow.com/q/52055852
type: Answer
has comment: http://stackoverflow.com/comment/91063802
score: 3
upvote count: 3

http://stackoverflow.com/q/52052397
has answer: http://stackoverflow.com/a/52052526
linked to: http://stackoverflow.com/q/3012488
answer count: 3
has comment: http://stackoverflow.com/comment/91055036
downvote count: 0
has comment: http://stackoverflow.com/comment/91055057
has answer: http://stackoverflow.com/a/52052550
favorite count: 0
has answer: http://stackoverflow.com/a/52052525
has comment: http://stackoverflow.com/comment/91055053
tagged with: python
accepted answer: http://stackoverflow.com/a/52052525
tagged with: dictionary
has comment: http://stackoverflow.com/comment/91055014
score: 2
has title: output and input dictionary
upvote count: 2
linked to: http://stackoverflow.com/q/3348460
type: Question
has body: Hi I want to save a dictionary to csv, then input it. However on both output and input, I met some issues. For output I tried: (D_FINAL is the dictionary) f = open("D_FINAL.csv", "w") writer = csv.writer(f) for k, v in D_FINAL.items(): writer.writerow([k, v]) f.close It works fine but when I want to open the csv, it says the file is locked from editting For input I tried import csv dict = {} r = open('D_FINAL3.csv', 'r') for k, v in csv.reader(r): dict[k] = v r.close() but I got error ValueError Traceback (most recent call last) &lt;ipython-input-92-d3e2b3081317&gt; in &lt;module&gt;() 3 dict = {} 4 r = open('D_FINAL2.csv', 'r') ----&gt; 5 for k, v in csv.reader(r): 6 dict[k] = v 7 ValueError: not enough values to unpack (expected 2, got 0) What's the correct way to do these ?
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/52052526

http://stackoverflow.com/comment/91160039
type: QuestionComment
type: Comment
score: 0
comment on: http://stackoverflow.com/q/52104337
has text: In that case you should be able to make this question vastly shorter. Narrow it down to your actual problem.

http://stackoverflow.com/comment/91213402
type: Comment
has text: Thank you so much for looking into this and in-depth explanation of each of the lines.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52120410

http://stackoverflow.com/a/69031027
has comment: http://stackoverflow.com/comment/135598506
type: Answer
has comment: http://stackoverflow.com/comment/138405590
answers question: http://stackoverflow.com/q/52027676
has body: Problem The problem is that Django adds GROUP BY as soon as it sees using an aggregate function. Solution So you can just create your own aggregate function but so that Django thinks it is not aggregate. Just like this: doctors = Doctor.objects.filter( specialization=OuterRef("id") ).order_by().annotate( count=Func(F('id'), function='Count') ).values('count') spec_qs_with_counts = Specialization.objects.annotate( num_applicable_doctors=Subquery(doctors) ) The more details on this method you can see in this answer: https://stackoverflow.com/a/69020732/10567223 Useful information can also be found in the docs about using aggregates within a subquery expression and func expressions.
upvote count: 39
has comment: http://stackoverflow.com/comment/136700179
downvote count: 0
has comment: http://stackoverflow.com/comment/140017957
score: 39

http://stackoverflow.com/comment/90932569
score: 0
has text: @mad_ @coldspeed Thanks! However, my json keys and the `a` column were changed. If you look at the 3rd entry in my json file, the key is `"2"` and the value associated with `"a"` is 2 but both get changed to 10...
comment on: http://stackoverflow.com/q/51991322
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/90991967
has text: `it1, it2 = itertools.tee(generator)` [BUT](https://docs.python.org/3/library/itertools.html#itertools.tee) "Once `tee()` has made a split, the original iterable should not be used anywhere else; otherwise, the iterable could get advanced without the tee objects being informed. This itertool may require significant auxiliary storage (depending on how much temporary data needs to be stored). In general, if one iterator uses most or all of the data before another iterator starts, it is faster to use `list()` instead of `tee()`."
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52020719
score: 0

http://stackoverflow.com/comment/91107300
comment on: http://stackoverflow.com/a/52049728
score: 0
type: AnswerComment
has text: I am really impressed... Never heard of this library. The calculation is approximate, but I believe I can calculate 6 neatest, recalculate the Haversine formula for them, sort and remain first 3 location. Thank you G. Grothendieck. I will update my post soon with your solution.
type: Comment

http://stackoverflow.com/comment/91033749
type: QuestionComment
has text: Tested in Windows 7. Works fine.
comment on: http://stackoverflow.com/q/52039621
score: 0
type: Comment

http://stackoverflow.com/q/52013628
score: 0
has answer: http://stackoverflow.com/a/52014218
has body: I am just being curious because I am trying to learn python. I am extracting data from a website. Anyway, what I did is scroll the page, then get the title that corresponds with the URL and inside a loop I am requesting this URL and extracting it with BS. Obviously, it doesn't work, the HTML that I am requesting prints like this: 403 Forbidden 403 Forbidden nginx Here is the python code import time import requests from selenium import webdriver from selenium.webdriver.common.keys import Keys from bs4 import BeautifulSoup as soup chromedriver = "/Users/eduardfossas/Downloads/chromedriver" driver = webdriver.Chrome(chromedriver) my_url = driver.get("https://wodwell.com/wods/?sort=newest&category=none&feeds=736") time.sleep(1) elem = driver.find_element_by_tag_name("body") no_of_pagedowns = 20 while no_of_pagedowns: elem.send_keys(Keys.PAGE_DOWN) time.sleep(0) no_of_pagedowns-=1 containers = driver.find_elements_by_class_name('wod-title') for container in containers: my_sub_url = "https://wodwell.com/wod/" my_sub_url = my_sub_url + container.text + '/' page_html = requests.get(my_sub_url).text page_soup = soup(page_html, "html.parser") main_text = page_soup.select('.workout-list') Is there any way to make this work with BeatifulSoup and requests? If not, I think I am going to try Scrapy. What do you recommend? Kind regards and many thanks.
answer count: 1
has title: Selenium, BeatifulSoup, Requests in a loop
has comment: http://stackoverflow.com/comment/90978543
has comment: http://stackoverflow.com/comment/90977987
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/90978739
tagged with: selenium
tagged with: python-requests
type: Question
has comment: http://stackoverflow.com/comment/90978844

http://stackoverflow.com/q/52086973
upvote count: 0
score: -2
has comment: http://stackoverflow.com/comment/91124947
tagged with: arrays
has body: I have this code: for a in data_X: for i in a: if not i.isdigit(): x=hash(i) data_X[column,row]=x row=row+1 row=0 column=column+1 desired_array = [int(numeric_string) for numeric_string in data_X] and I the Data_X are these (only a part of the Array): [['42' '-6725209669690155188' '159449' ... '40' '4017763880221344027' '-136014339944321305'] ... ['30' '-6725209669690155188' '154950' ... '60' '4017763880221344027' '-136014339944321305']] and I wanted to transform the numbers from char ( e.g '42') to int (42) and I thougt I could doing this: desired_array = [int(numeric_string) for numeric_string in data_X] but I received the error "Error only size-1 arrays can be converted to Python scalars" and I don't know what can I do.. these is what I want to have: from : [['42' '-6725209669690155188' '159449' ... '40' '4017763880221344027' '-136014339944321305'] ... ['30' '-6725209669690155188' '154950' ... '60' '4017763880221344027' '-136014339944321305']] to: [[42 -6725209669690155188 159449 ... 40 4017763880221344027 -136014339944321305] ... [30 -6725209669690155188 154950 ... 60 4017763880221344027 -136014339944321305]] Can somebody tell me where is the Problem? thanks!
has comment: http://stackoverflow.com/comment/91124268
has comment: http://stackoverflow.com/comment/91124238
has comment: http://stackoverflow.com/comment/91124457
has comment: http://stackoverflow.com/comment/91124510
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/91124646
has answer: http://stackoverflow.com/a/52087316
downvote count: 2
has title: Error only size-1 arrays can be converted to Python scalars
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/52087316
has comment: http://stackoverflow.com/comment/91124678
has comment: http://stackoverflow.com/comment/91124648
has comment: http://stackoverflow.com/comment/91124839
has comment: http://stackoverflow.com/comment/91124817
has comment: http://stackoverflow.com/comment/91124505
type: Question

http://stackoverflow.com/q/52003818
upvote count: 0
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/90957170
type: UnansweredQuestion
tagged with: python
downvote count: 1
has title: How to access an attribut of a class defined inside an other class?
type: Question
has answer: http://stackoverflow.com/a/52003938
score: -1
has comment: http://stackoverflow.com/comment/91070058
tagged with: class
has body: Is it possible in Python to access an attribute of class B defined in a class A from the class A ? For example, access 'a' from the method 'toto'. class A(object): def __init__(self, ...): ... def toto(self): ... class B(object): def __init__(self, a): self.a = a Thank you for yours answers.

http://stackoverflow.com/comment/91137974
type: QuestionComment
has text: thank you @chillie you helped me a lot
comment on: http://stackoverflow.com/q/52000418
score: 0
type: Comment

http://stackoverflow.com/comment/90876876
type: QuestionComment
has text: This is not a good idea. Either you should pass only acceptable combinations as tuples and configure the estimator to use them or You should just pass all the available possibilities to the search and then take care in your estimator about the relationship between the two. You should raise an error if the constraint is not satisfied. RandomizedSearchCV has a param `error_score` which you can use to handle the errors raised from estimator.
score: 0
comment on: http://stackoverflow.com/q/51963174
type: Comment

http://stackoverflow.com/comment/90880777
comment on: http://stackoverflow.com/q/51965436
has text: @DavidG won't that fail if the longest substring is at the start
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51994013
type: Question
tagged with: apache-kafka
tagged with: boto
tagged with: pagination
upvote count: 1
favorite count: 0
type: UnansweredQuestion
has title: Boto Pagination for Kafka Topic
tagged with: python
has body: I'm learning Kafka on python. The source system sends the clickstream data for minute into S3 bucket under prefixes created for every minute.I want to use boto Pagination on S3 to read the data continuously and send the data to Kafka Topic. This Kafka Topic will be read by another team to do some analytics.Ia my approach a good one.? Thanks Jerome
answer count: 0
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/90941467

http://stackoverflow.com/q/51996381
type: UnansweredQuestion
has body: When I tried to update my pytorch version to 0.4 using the following command line conda install pytorch=0.4.0 -c pytorch I got the following error: Solving environment: done ##Package Plan## environment location: /anaconda added / updated specs: - pytorch=0.4.0 The following NEW packages will be INSTALLED: blas: 1.0-mkl intel-openmp: 2018.0.3-0 libcxx: 4.0.1-h579ed51_0 libcxxabi: 4.0.1-hebd6815_0 libgfortran: 3.0.1-h93005f0_2 mkl_fft: 1.0.4-py27h5d10147_1 mkl_random: 1.0.1-py27h5d10147_1 ninja: 1.8.2-py27h04f5b5a_1 numpy-base: 1.15.0-py27h8a80b8c_0 pytorch: 0.4.0-py27_cuda0.0_cudnn0.0_1 pytorch The following packages will be UPDATED: mkl: 2017.0.3-0 --&gt; 2018.0.3-1 numpy: 1.13.1-py27_0 --&gt; 1.15.0-py27h648b28d_0 Proceed ([y]/n)? y Preparing transaction: done Verifying transaction: done Executing transaction: failed ERROR conda.core.link:_execute(502): An error occurred while uninstalling package 'defaults::numpy-1.13.1-py27_0'. OSError(13, 'Permission denied') Attempting to roll back. Rolling back transaction: done OSError(13, 'Permission denied') I saw online that I should use the chown functionality but I am not sure how to use it. What should I do?
tagged with: chown
tagged with: django
tagged with: python
has answer: http://stackoverflow.com/a/52021346
type: Question
tagged with: apache
has title: OSError while updating pytorch
score: 0
answer count: 1
tagged with: unix

http://stackoverflow.com/q/51977881
has comment: http://stackoverflow.com/comment/90905854
tagged with: datetime
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90906217
has body: import time import pandas as pd x=pd.to_datetime('2017/01/01',yearfirst=True) print('x:', x) y=pd.to_datetime(time.mktime(x.timetuple()),unit='s') print('y:', y) The result is: x: 2017-01-01 00:00:00 y: 2016-12-31 16:00:00 I'd expect them to be the same, since we usually transform TimpStamp to seconds and then transform them back. I understand that this has things to do with timezone, but how can I eliminate the timezone effect? Edit: Package information: Python 3.6, Pandas 0.23.1 and dateutil 2.7.3 Local timezone： UTC+8
type: Question
has comment: http://stackoverflow.com/comment/90908279
accepted answer: http://stackoverflow.com/a/51979386
has comment: http://stackoverflow.com/comment/90905889
score: 0
tagged with: pandas
has comment: http://stackoverflow.com/comment/90905810
answer count: 1
has answer: http://stackoverflow.com/a/51979386
has title: pd.to_datetime inconsistent with time.mktime
has comment: http://stackoverflow.com/comment/90905763
tagged with: time

function
tags question: http://stackoverflow.com/q/51974566
tags question: http://stackoverflow.com/q/52009986
tag name: function
tags question: http://stackoverflow.com/q/52013486
tags question: http://stackoverflow.com/q/52024916
tags question: http://stackoverflow.com/q/52083510
tags question: http://stackoverflow.com/q/52050346
tags question: http://stackoverflow.com/q/52081316
tags question: http://stackoverflow.com/q/52033620
tags question: http://stackoverflow.com/q/51991038
tags question: http://stackoverflow.com/q/52046148
tags question: http://stackoverflow.com/q/52067530
tags question: http://stackoverflow.com/q/52004398
tags question: http://stackoverflow.com/q/52053685
tags question: http://stackoverflow.com/q/52029320
tags question: http://stackoverflow.com/q/52011435
tags question: http://stackoverflow.com/q/52011401
tags question: http://stackoverflow.com/q/51979302
tags question: http://stackoverflow.com/q/51966456
tags question: http://stackoverflow.com/q/52045772
tags question: http://stackoverflow.com/q/52044222
tags question: http://stackoverflow.com/q/52036656
tags question: http://stackoverflow.com/q/52082414
type: Tag
tags question: http://stackoverflow.com/q/52045842
tags question: http://stackoverflow.com/q/51969361
tags question: http://stackoverflow.com/q/52023685
tags question: http://stackoverflow.com/q/51964872
tags question: http://stackoverflow.com/q/52018736
tags question: http://stackoverflow.com/q/52033260
tags question: http://stackoverflow.com/q/52102254
tags question: http://stackoverflow.com/q/52067524
tags question: http://stackoverflow.com/q/52066815
tags question: http://stackoverflow.com/q/52005295
tags question: http://stackoverflow.com/q/52077459
tags question: http://stackoverflow.com/q/51958381
tags question: http://stackoverflow.com/q/52032525
tags question: http://stackoverflow.com/q/52032139
tags question: http://stackoverflow.com/q/52056933
tags question: http://stackoverflow.com/q/52030377
tags question: http://stackoverflow.com/q/52067104
tags question: http://stackoverflow.com/q/52022632
tags question: http://stackoverflow.com/q/51998384

http://stackoverflow.com/comment/90892299
type: Comment
comment on: http://stackoverflow.com/a/51970704
score: 0
type: AnswerComment
has text: Thank you for the response. By better results I mean the overall cost was about 2 orders of magnitude better (ie 0.00002 vs 0.002). Also comparing the images shows the first method to replicate the labelled image much better. The learning rate for the first method is about 0.0005...so multiplying this by a very large number doesn't seem to be right...? I have tried adjusting the learning rate for the second method and found one that trains okay, but I can't get the cost down to 2e-5.

http://stackoverflow.com/q/51991378
tagged with: gtk
type: AnsweredQuestion
type: Question
has answer: http://stackoverflow.com/a/52010523
accepted answer: http://stackoverflow.com/a/52010523
score: 0
tagged with: pygtk
answer count: 1
has body: I'm new at phyton programming and developing gui interface has gtk framework and serial port. It has a treeview whose liststore model. I could the insert new rows easily. I'm using the serialport recive callback in different thread from main gui thread avoid to not miss any data. After the received a new data, it should update the treeview. However, since the serialport is in different thread, I don't know how to update the list. Please help me to do this. the gui class: class MainGUI(): def __init__(self): self.builder = Gtk.Builder() self.builder.add_from_file("main.glade") self.builder.connect_signals(MainGUI) self.window = self.builder.get_object("window1") self.mycombobox = self.builder.get_object('comboboxtext1') self.toggle = self.builder.get_object('togglebutton1') self.table = self.builder.get_object('treeview2') self.list = self.builder.get_object('liststore1') self.scroll_window = self.builder.get_object('scrolledwindow1') def show(self): print("App main thread number", format(threading.get_ident())) self.window.show() Gtk.main() @staticmethod def connect_toggled(_self): if main.toggle.get_active(): main.toggle.set_label("Disconnect") serial_port.connect(main.mycombobox.get_active_text()) t3 = threading.Thread(target=serial_port.read_from_port) t3.start() serial_port.disconnect() def row_inserted_event(self, path, iter): """The actual scrolling method""" adj = main.scroll_window.get_vadjustment() adj.set_value(adj.get_upper() - adj.get_page_size()) def update_table(self): # for i in range(256): # main.list.append(['aaa', 'ddds', i]) # if len(main.list) &gt; 50: # main.list.remove(main.list.get_iter(0)) main.list.append(['aaa', 'ddds', 0]) if len(main.list) &gt; 50: main.list.remove(main.list.get_iter(0)) print(len(main.list)) if __name__ == "__main__": serial_port = SerialPort() ports = SerialPort().list_ports() main = MainGUI() for port in ports: main.mycombobox.append_text(port) main.mycombobox.set_active(0) main.toggle.set_label("Connect") main.update_…
has comment: http://stackoverflow.com/comment/90951872
has title: updating the list store of gtk periodically in python
tagged with: python

http://stackoverflow.com/q/52002176
tagged with: aws-lambda
favorite count: 0
tagged with: python
has title: AWS Xray: Cannot create segments inside Lambda function and segment not found
type: AnsweredQuestion
upvote count: 3
has answer: http://stackoverflow.com/a/52002216
type: Question
score: 3
has body: A really strange behaviour I was experiencing, I am following online documentation and while creating a segment to work with my subsegment, the lambda executes in following order: xray_recorder.begin_segment('segment-name') xray_recorder.begin_subsegment('subsegment-name') # put annotations and meta data etc xray_recorder.end_segment('segment-name') xray_recorder.end_subsegment('subsegment-name') but I get following error on CloudWatch Manager: Cannot create segments inside Lambda function. Discarded. When I remove segment creation and try running things locally like this: xray_recorder.begin_subsegment('subsegment-name') # put annotations and meta data etc xray_recorder.end_segment('segment-name') I get the error: SegmentNotFoundException: cannot find the current segment/subsegment, please make sure you have a segment open Confusing.
tagged with: aws-xray
downvote count: 0
answer count: 1
accepted answer: http://stackoverflow.com/a/52002216

http://stackoverflow.com/a/51976887
has body: It looks like you have installed those modules in your default/system interpreter, not into the venv you just made. You need to switch into (activate) the venv first, before installing the modules. Activate with a command something like (depending on your project's venv location): source my_project/bin/activate See: https://docs.python.org/3/library/venv.html
score: 4
type: Answer
answers question: http://stackoverflow.com/q/51976832
upvote count: 4
downvote count: 0

http://stackoverflow.com/a/52029117
has comment: http://stackoverflow.com/comment/91008946
upvote count: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/52028954
has body: Is this what you mean to accomplish? for txt, cls in zip(textt, classs): if txt==cls: print('correct')
type: Answer
answers question: http://stackoverflow.com/q/52028954
has comment: http://stackoverflow.com/comment/91008747
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/91037903

http://stackoverflow.com/a/51988632
upvote count: 1
downvote count: 0
type: Answer
score: 1
answers question: http://stackoverflow.com/q/51988491
has body: Checking until half and summing up all passing numbers is very inefficient. Try to change for k in range(1, int(i / 2) + 1): if i % k == 0: s += k to for k in range(1, int(i**0.5)+1): if i % k == 0: s += k if k != i//k: s += i//k

http://stackoverflow.com/comment/91144256
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52096896
type: Comment
has text: Ah I see, I misunderstood then. Let me check. That should be possible similarly.

http://stackoverflow.com/comment/91039185
type: Comment
comment on: http://stackoverflow.com/a/52044165
type: AnswerComment
has text: @steveJ made modifications
score: 0

http://stackoverflow.com/a/52052526
has comment: http://stackoverflow.com/comment/91055276
type: Answer
has body: Looking at the code you have given, it seems like you are not actually closing the file by calling f.close(). Changing f.close to f.close() should help you get over this issue. But remember you can improve your code by implementing a with block. for example, with open("D_FINAL.csv", "w",newline="") as f: writer = csv.writer(f) for k, v in D_FINAL.items(): writer.writerow([k, v])
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/91055309
downvote count: 0
answers question: http://stackoverflow.com/q/52052397

http://stackoverflow.com/a/52017624
has comment: http://stackoverflow.com/comment/90988220
has comment: http://stackoverflow.com/comment/90985876
accepted answer of: http://stackoverflow.com/q/52017598
type: Answer
has comment: http://stackoverflow.com/comment/90985879
upvote count: 4
has comment: http://stackoverflow.com/comment/90985965
has body: For a .. , the POST data sends the value=".." of the selected , so in case you want MachineA, you should send it with 'machine': '1', as payload: import requests URL = 'http://127.0.0.1:8000/recoater/new/' payload = { 'data': '40', 'machine': '1', } r = requests.post(URL, data=payload) print (r) print(r.text) The Django forms (or other mechanisms that handle the request) have logic in place to map this value back to the machine that is associated with this value: after all, the text in the option is just a textual representation of the Machine object, it can contain a lot of (extra) data that is not displayed (or is displayed, but in a non-structured way). So a browser will for a webpage: --------- MachineA Send in the POST data an entry that associates the name of the (here 'machine') that is associated with the value of the option picked (here '' or '1'). Just like a has a value parameter as well that is set to the value you enter in the textfield.
score: 4
has comment: http://stackoverflow.com/comment/90985526
has comment: http://stackoverflow.com/comment/90985462
answers question: http://stackoverflow.com/q/52017598
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/90986003

http://stackoverflow.com/q/52078738
has title: How to import object from builtins affecting just one class?
type: Question
has comment: http://stackoverflow.com/comment/91107679
has comment: http://stackoverflow.com/comment/91107669
has comment: http://stackoverflow.com/comment/91110571
tagged with: python-2.7
answer count: 3
tagged with: new-style-class
linked to: http://stackoverflow.com/q/14222416
has comment: http://stackoverflow.com/comment/91108023
possible better answer: http://stackoverflow.com/a/52078862
downvote count: 0
has answer: http://stackoverflow.com/a/52079498
has comment: http://stackoverflow.com/comment/91107751
has answer: http://stackoverflow.com/a/52078862
favorite count: 0
has comment: http://stackoverflow.com/comment/91107585
tagged with: python-3.x
linked to: http://stackoverflow.com/q/13816849
accepted answer: http://stackoverflow.com/a/52079498
score: 6
tagged with: future
tagged with: python
has comment: http://stackoverflow.com/comment/91107939
has body: I am converting code from python2 to python3 for newstyle classes using future. My project is in Django 1.11 I have a class in forms.py as: class Address: ...rest of code... class AddressForm(Address, forms.ModelForm): ...rest of code... in Python 2 which is converted to : from buitlins import object class Address(object): ...rest of code... class AddressForm(Address, forms.ModelForm): ...rest of code... in Python 3 I have a selenium test that fails when this Form is invoked after it is converted to Python3 with the following error: File "&lt;path_to_venv&gt;/local/lib/python2.7/site-packages/django/utils/six.py", line 842, in &lt;lambda&gt; klass.__str__ = lambda self: self.__unicode__().encode('utf-8') File "&lt;path_to_venv&gt;/local/lib/python2.7/site-packages/future/types/newobject.py", line 78, in __unicode__ s = type(self).__str__(self) RuntimeError: maximum recursion depth exceeded However, when I remove the import from buitlins import object the test passes. But as I have added a future check, I get a future difference error &amp; thus every class has to be converted to newstyle. I want it to work in both Python2 and Python3. Is there a way this module builtins module import can affect just one class and not others in the forms.py file. Or is there some other method to handle this?
upvote count: 6
has comment: http://stackoverflow.com/comment/91108094
has comment: http://stackoverflow.com/comment/91108566
has comment: http://stackoverflow.com/comment/91107613
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/63421762

http://stackoverflow.com/q/52021100
has answer: http://stackoverflow.com/a/52022001
answer count: 2
tagged with: pydev
has comment: http://stackoverflow.com/comment/90994398
has title: Eclipse PyDev - Reading CSV from Forked Project
score: 0
has answer: http://stackoverflow.com/a/52022061
tagged with: http://stackoverflow.com/tag/csv
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90994431
tagged with: python
has body: I've cloned a copy of "machine_learning_examples" from GitHub (https://github.com/lazyprogrammer/machine_learning_examples). In it, it has a file "data_2d.csv" under the "linear_regression_class" folder. I've added reference in my project to the "machine_learning_examples" project, and have tried a "from" and "import" statement with different target text, but can't determine the syntax to reference the "data_2d.csv" file. I've been able to copy the csv file locally to a folder in my project and then just take the example code and modify the target: import numpy as np X = [] for line in open('data/data_2d.csv'): row = line.split(',') sample = list(map(float, row)) X.append(sample) X = np.array(X) print(X) This works ok, as expected. But, I would like to directly reference the csv as it exists in the cloned project.
linked to: http://stackoverflow.com/q/22340265
tagged with: eclipse
type: Question

http://stackoverflow.com/q/51967822
has title: How to make jupyter pythreejs plots larger?
tagged with: widget
type: UnansweredQuestion
score: 1
upvote count: 1
has answer: http://stackoverflow.com/a/51971724
has body: I've been playing around with pythreejs, and, while it seems to be a good solution to the problem of visualizing 3D graphics in a jupyter notebook, I haven't been able to find any documentation about what jupyter is actually doing under the hood or what API exists for managing the widget. Currently, when I make a pythreejs plot (e.g., by calling display() on a pythreejs.Renderer object), I get a tiny little output window. How can I edit the size (and other properties) of this window? How can I see what the properties are? Thanks!
type: Question
answer count: 1
downvote count: 0
favorite count: 0
tagged with: three.js
tagged with: python
tagged with: jupyter-notebook

http://stackoverflow.com/comment/91092238
comment on: http://stackoverflow.com/a/52071268
has text: thank you for the nice lines! hope you don't mind I chose the answer which is easier to understand, especially for beginners. :)
score: 0
type: AnswerComment
type: Comment

while-loop
tags question: http://stackoverflow.com/q/52096848
tags question: http://stackoverflow.com/q/52044423
tags question: http://stackoverflow.com/q/52069552
type: Tag
tags question: http://stackoverflow.com/q/51971035
tags question: http://stackoverflow.com/q/52089186
tags question: http://stackoverflow.com/q/51986928
tags question: http://stackoverflow.com/q/51980534
tags question: http://stackoverflow.com/q/52040264
tags question: http://stackoverflow.com/q/51965213
tags question: http://stackoverflow.com/q/52001137
tags question: http://stackoverflow.com/q/52090959
tags question: http://stackoverflow.com/q/52005192
tags question: http://stackoverflow.com/q/51966845
tags question: http://stackoverflow.com/q/52027932
tag name: while-loop
tags question: http://stackoverflow.com/q/52111254

http://stackoverflow.com/a/52008194
type: Answer
answers question: http://stackoverflow.com/q/51984042
accepted answer of: http://stackoverflow.com/q/51984042
has comment: http://stackoverflow.com/comment/90968687
has body: As the names of the variables exp1, exp2, ... expN imply, this works for expressions only. However, : by itself is not an expression, so (:,) is a syntax error because the colon symbol can only be used in indexing in this sense.
score: 0
has comment: http://stackoverflow.com/comment/90969109
has comment: http://stackoverflow.com/comment/90968484
type: AcceptedAnswer

http://stackoverflow.com/comment/91136240
has text: @TBurgis It should run all the time. The server is a Windows server.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52092806

http://stackoverflow.com/a/51982913
has body: I think this error occurred because you haven't set a default value to your foreign key. For your previous P_Images instances (before your current migration), they don't have a Projects id related to them. The error text shown also confirms it: return self._get_default() TypeError: id() takes exactly one argument (0 given) So try adding a default value : DEFAULT_PROJECT = 1 # or the id of any project that does exist fk_post = models.ForeignKey(Projects, on_delete=models.CASCADE, default = DEFAULT_PROJECT)
downvote count: 1
answers question: http://stackoverflow.com/q/51979312
score: -1
upvote count: 0
has comment: http://stackoverflow.com/comment/90944021
type: Answer

http://stackoverflow.com/comment/90975619
has text: I thought that if its false then it would just pass that line and jump to another elif I never thought this actually. It seems like problem is solved
comment on: http://stackoverflow.com/a/52012329
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/q/51973231
has body: I'm working on a project using Python to search the XML of a research paper, searching for a particular string. I've accomplished this, but I need to get the search result's most previous section heading, which is the TITLE and LABEL tag and their content. #&lt;..... some XML .....&gt; &lt;sec id="aj387295s3"&gt; &lt;label&gt;3.&lt;/label&gt; &lt;title&gt;&lt;italic&gt;CHANDRA&lt;/italic&gt; OBSERVATIONS&lt;/title&gt; &lt;p&gt;The 13 candidates were observed with the Advanced CCD Imaging Spectrometer (ACIS; Burke et&amp;nbsp;al. &lt;xref ref-type="bibr" rid="aj387295r8"&gt;1997&lt;/xref&gt;) on board &lt;italic&gt;Chandra&lt;/italic&gt; (Weisskopf et&amp;nbsp;al. &lt;xref ref-type="bibr" rid="aj387295r46"&gt;1996&lt;/xref&gt;). We chose the S3 chip to image the sources because of its better low-energy sensitivity. The standard TIMED readout with a frame time of 3.2 s was used, and the data were collected in VFAINT mode. In 12 cases, our &lt;italic&gt;Chandra&lt;/italic&gt; observations led us to conclude that the RASS detection was not of a candidate INS (see Table&amp;nbsp;&lt;xref ref-type="table" rid="aj387295t1"&gt;1&lt;/xref&gt;; the &lt;xref ref-type="sec" rid="aj387295app1"&gt;Appendix&lt;/xref&gt; includes a case-by-case discussion of these sources).&lt;/p&gt; #&lt;..... more XML ....&gt; I have a regular expression to obtain the line that contains "Chandra", but I keep banging my head trying to get "3.CHANDRA OBSERVATIONS". It's probably super obvious but I don't have much training in regular expressions. My regular expression for Chandra and the rest of the line is "(.*)(c|C)handra\b" Thank you! -Jenny
upvote count: 0
has comment: http://stackoverflow.com/comment/90898587
has comment: http://stackoverflow.com/comment/90897166
has comment: http://stackoverflow.com/comment/90898503
type: Question
duplicate of: http://stackoverflow.com/q/6751105
has comment: http://stackoverflow.com/comment/90896865
score: -1
has comment: http://stackoverflow.com/comment/90897268
has title: Python regex in xml text, find tags
linked to: http://stackoverflow.com/q/1732348
linked to: http://stackoverflow.com/q/6751105
has comment: http://stackoverflow.com/comment/90897323
answer count: 1
downvote count: 1
linked to: http://stackoverflow.com/q/13241615
favorite count: 0
tagged with: beautifulsoup
has answer: http://stackoverflow.com/a/51974173
type: UnansweredQuestion
tagged with: python
tagged with: regex
tagged with: http://stackoverflow.com/tag/xml

http://stackoverflow.com/q/52079801
has comment: http://stackoverflow.com/comment/91111723
has comment: http://stackoverflow.com/comment/91110406
linked to: http://stackoverflow.com/q/51413816
has answer: http://stackoverflow.com/a/52080180
answer count: 2
has answer: http://stackoverflow.com/a/52079901
favorite count: 0
tagged with: python
tagged with: module
tagged with: tweepy
has comment: http://stackoverflow.com/comment/91110210
has comment: http://stackoverflow.com/comment/91111759
has title: Python - Tweepy module has incorrect syntax
has comment: http://stackoverflow.com/comment/91110064
has body: I am new to Python and I'd like to import tweepy in an app of mine. I run this code (taken from Tweepy official documentation): import tweepy auth = tweepy.OAuthHandler(consumer_key, consumer_secret) auth.set_access_token(access_token, access_token_secret) api = tweepy.API(auth) public_tweets = api.home_timeline() for tweet in public_tweets: print tweet.text it returns this error: Traceback (most recent call last): File "C:/Users/user/PycharmProjects/TwitterPythonAnalytics/file3.py", line 1, in import tweepy File "C:\Users\user\PycharmProjects\TwitterPythonAnalytics\venv\lib\site-packages\tweepy__init__.py", line 17, in from tweepy.streaming import Stream, StreamListener File "C:\Users\user\PycharmProjects\TwitterPythonAnalytics\venv\lib\site-packages\tweepy\streaming.py", line 358 def _start(self, async): ^ SyntaxError: invalid syntax I tried everything to fix indentations and spaces in my .py file, but apparently the problem seems to be inside the Tweepy modules. Can anybody help me to solve this please?
score: 0
type: UnansweredQuestion
upvote count: 1
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/91111072

apache
tag name: apache
tags question: http://stackoverflow.com/q/52002793
tags question: http://stackoverflow.com/q/52096264
tags question: http://stackoverflow.com/q/51996381
tags question: http://stackoverflow.com/q/52020221
type: Tag
tags question: http://stackoverflow.com/q/52100377
tags question: http://stackoverflow.com/q/52105854
tags question: http://stackoverflow.com/q/51988001

http://stackoverflow.com/q/52042923
has title: Turn trained TensorFlow model into fixed operation
answer count: 1
tagged with: python
accepted answer: http://stackoverflow.com/a/52044305
has body: Is there a way to take a trained TensorFlow model and convert all the tf.Variables and their respective weights (either from within a running tf.Session or from a checkpoint) into tf.constants with that value, such that one can run the model on a new input tensor without initializing or restoring the weights in a session? So can I basically condense a trained model into a fixed and immutable TensorFlow operation?
has answer: http://stackoverflow.com/a/52044305
tagged with: tensorflow
type: AnsweredQuestion
type: Question
score: 0

http://stackoverflow.com/a/52067069
upvote count: 0
score: -1
has comment: http://stackoverflow.com/comment/91084476
has comment: http://stackoverflow.com/comment/91656949
has body: As mentioned in one of the comments (kudos @mydaemon), the venv you're working with is a python3 environment, which is not compatible with python2 libs/scripts. In addition, if you didn't activate your environment, then any python scripts/tools will continue to run on the system python (which looks like python2.7 in this case). To get this working as python3, simply: (edit: new info shows that this env is indeed an activated python3 env, so this won't work). . ${HOME}/envs/py3/bin/activate pip install panda To use python2: virtualenv --python=python2.7 ${HOME}/envs/py2 . ${HOME}/envs/py2/bin/activate pip install panda Edit: Pandas on PyPi is a python 2.x library and will not work with pip on python3. The Pandas website recommends installing via anaconda
type: Answer
answers question: http://stackoverflow.com/q/52066816
downvote count: 1
has comment: http://stackoverflow.com/comment/91084967

http://stackoverflow.com/q/52094979
downvote count: 1
type: Question
accepted answer: http://stackoverflow.com/a/52104565
score: -1
has title: Is there a place to run psychopy scripts online?
upvote count: 0
answer count: 1
tagged with: psychopy
favorite count: 0
has answer: http://stackoverflow.com/a/52104565
tagged with: python
has comment: http://stackoverflow.com/comment/91140117
type: AnsweredQuestion
has body: Is there any place where you can run an online experiment by uploading a psychopy script (Python 2.7)? Best, Simon

http://stackoverflow.com/q/52096669
score: 3
tagged with: windows
has answer: http://stackoverflow.com/a/52274189
has comment: http://stackoverflow.com/comment/91144908
tagged with: python
favorite count: 0
has body: I have a third party executable called by using subprocess.check_output unfortunately my argument list is too long and repeatedly calling it is much slower than calling it once with many arguments. Slow due to making the command call many times: def call_third_party_slow(third_party_path, files): for file in files: output = subprocess.check_output([third_party_path, "-z", file]) if "sought" in decode(output): return False return True Fast but fails when there are many files: def call_third_party_fast(third_party_path, files): command = [third_party_path, "-z"] command.extend(files) output = subprocess.check_output(command) if "sought" in decode(output): return False return True Is there any easy way I can work around the command length limit or easily group the files to avoid exceeding the os dependent length?
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/52274189
has answer: http://stackoverflow.com/a/52103555
has comment: http://stackoverflow.com/comment/91144003
type: AnsweredQuestion
upvote count: 3
has comment: http://stackoverflow.com/comment/91143855
has comment: http://stackoverflow.com/comment/91143663
type: Question
has answer: http://stackoverflow.com/a/52096896
downvote count: 0
possible better answer: http://stackoverflow.com/a/52096896
has title: Subprocess argument list to long
linked to: http://stackoverflow.com/q/29801975
tagged with: linux
answer count: 3

http://stackoverflow.com/comment/91043776
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51973347
has text: .eps output would work but result in a huge file(more than 50mb) and the quality is low.

http://stackoverflow.com/q/52030641
accepted answer: http://stackoverflow.com/a/52030731
answer count: 1
score: 0
has comment: http://stackoverflow.com/comment/91011857
has comment: http://stackoverflow.com/comment/91011844
has title: python thread pool copy parameters
tagged with: copy
has answer: http://stackoverflow.com/a/52030731
has comment: http://stackoverflow.com/comment/91011801
tagged with: pool
has comment: http://stackoverflow.com/comment/91011753
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91011789
has comment: http://stackoverflow.com/comment/91011813
has body: I'm learning about multithreading and I try to implement a few things to understand it. After reading several (and very technical topics) I cannot find a solution or way to understand my issue. Basically, I have the following structure: class MyObject(): def __init__(): self.lastupdate = datetime.datetime.now() def DoThings(): ... def MyThreadFunction(OneOfMyObject): OneOfMyObject.DoThings() OneOfMyObject.lastupdate = datetime.datetime.now() def main(): MyObject1 = MyObject() MyObject2 = MyObject() MyObjects = [MyObject1, MyObject2] pool = Pool(2) while True: pool.map(MyThreadFunction, MyObjects) if __name__ == '__main__': main() I think the function .map make a copy of my objects because it does not update the time. Is it right ? if yes, how could I input a Global version of my objects. If not, would you have any idea why the time is fixed in my objects ? When I check the new time with print(MyObject.lastupdate), the time is right, but not in the next loop Thank you very much for any of your ideas
type: Question
tagged with: multithreading
tagged with: python

http://stackoverflow.com/q/52067784
type: AnsweredQuestion
tagged with: mixture-model
has comment: http://stackoverflow.com/comment/91087882
tagged with: pytorch
has body: I am trying to implement a simple MDN that predicts the parameters of a distribution over a target variable instead of a point value, and then assigns probabilities to discrete bins of the point value. Narrowing down the issue, the code from which the 'None' springs is: import torch # params tte_bins = np.linspace( start=0, stop=399, num=400, dtype='float32' ).reshape(1, 1, -1) bins = torch.tensor(tte_bins, dtype=torch.float32) x_train = np.random.randn(1, 1024, 3) y_labels = np.random.randint(low=0, high=399, size=(1, 1024)) y_train = np.eye(400)[y_labels] # data in_train = torch.tensor(x_train[0:1, :, :], dtype=torch.float) in_train = (in_train - torch.mean(in_train)) / torch.std(in_train) out_train = torch.tensor(y_train[0:1, :, :], dtype=torch.float) # model linear = torch.nn.Linear(in_features=3, out_features=2) lin = linear(in_train) preds = torch.exp(lin) # intermediate values alpha = torch.clamp(preds[0:1, :, 0:1], 0, 500) beta = torch.clamp(preds[0:1, :, 1:2], 0, 100) # probs p1 = torch.exp(-torch.pow(bins / alpha, beta)) p2 = torch.exp(-torch.pow((bins + 1.0) / alpha, beta)) probs = p1 - p2 # loss loss = torch.mean(torch.pow(out_train - probs, 2)) # gradients loss.backward() for p in linear.parameters(): print(p.grad, 'gradient') in_train has shape: [1, 1024, 3], out_train has shape: [1, 1024, 400], bins has shape: [1, 1, 400]. All the broadcasting etc.. appears find, the resulting matrices (like alpha/beta/loss) are the right shape and have the right values - there's simply no gradients edit: added loss.backward() and x_train/y_train, now I have nans
has comment: http://stackoverflow.com/comment/91088187
type: Question
has comment: http://stackoverflow.com/comment/91087719
accepted answer: http://stackoverflow.com/a/52068590
has title: 'None' gradients in pytorch
score: 0
has comment: http://stackoverflow.com/comment/91087962
answer count: 1
has comment: http://stackoverflow.com/comment/91087907
has comment: http://stackoverflow.com/comment/91087961
has answer: http://stackoverflow.com/a/52068590
tagged with: machine-learning
tagged with: python
has comment: http://stackoverflow.com/comment/91088100

http://stackoverflow.com/a/51990505
score: 1
answers question: http://stackoverflow.com/q/51990413
upvote count: 1
has body: This error means what it says: assertTrue is not defined. Have you imported assertTrue? If you imported the testing module but not the framework, you'll have to do: testing_module.assertTrue() If you want to use 'assertTrue` directly, you should write at the top of the test file the following: from testing_module import assertTrue
downvote count: 0
type: Answer

http://stackoverflow.com/a/52068173
accepted answer of: http://stackoverflow.com/q/52067809
upvote count: 1
has comment: http://stackoverflow.com/comment/91086710
type: AcceptedAnswer
downvote count: 0
type: Answer
has body: First the function ode45 is different to the function odeint, in the question of the position of the arguments: scipy.integrate.odeint(func, y0, t, args=(), ...) As we see that the second argument is the initial value, not the time range. Another mistake is: xdot = [[],[]] That is a list list, what you should do is create a list of 4 elements with any value that will be overwritten (typically those values are 0s) import numpy as np from scipy.integrate import odeint import matplotlib.pyplot as plt def model(x, t): m, K, C, c, k = 1, 49, 2, 0.5, 1 xdot = [0, 0, 0, 0] xdot[0] = x[1] xdot[1] = (1/m)*(-c*x[1]-k*x[0]+C*(x[3]-x[1])+k*(x[2]-x[0])) xdot[2] = x[3] xdot[3] = (1/m)*(-c*x[3]-k*x[2]+C*(x[1]-x[3])+k*(x[0]-x[2])) return xdot q1, q1dot, q2, q2dot = 1, 0, 1, 0 t0, tf = 0, 25 t = np.linspace(t0, tf, 100) y0 = [q1, q1dot, q2, q2dot] y = odeint(model, y0, t) plt.plot(t, y) plt.show()
has comment: http://stackoverflow.com/comment/91096598
answers question: http://stackoverflow.com/q/52067809
score: 1

http://stackoverflow.com/comment/91101204
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52075715
score: 0
has text: How AB+1 gets 54.3 ? when 21.7+13.9+17.8 = 53.4?

http://stackoverflow.com/a/57387549
score: 3
answers question: http://stackoverflow.com/q/51961386
has body: When you read any python function docs as bytes([source[, encoding[, errors]]]) square brackets represent that those parameters are optional. multiple square brackets inside another mean they are next level of option params. For example bytes([source.... means we can call bytes as byes() itself as [source] is optional here bytes() -&gt; empty bytes object bytes(22) Here 22 is being passed as the source read this for more details about bytes and its params https://docs.python.org/3/library/stdtypes.html#bytes
upvote count: 3
downvote count: 0
type: Answer

http://stackoverflow.com/comment/91012180
comment on: http://stackoverflow.com/a/52030731
type: Comment
has text: "you aren't from a python background" no I'm not but I love it :)
score: 0
type: AnswerComment

http://stackoverflow.com/comment/91214508
comment on: http://stackoverflow.com/a/52066705
type: AnswerComment
type: Comment
has text: I have added details about the directory structure, what files are where and the command that executes the tests. Thanks for helping with this!!
score: 0

http://stackoverflow.com/q/52067255
downvote count: 0
favorite count: 0
has body: Is there a way to open multiple browsers in python with requests? I am getting data off a site that has 6,000,000 pages. If I had the ability to open 10 at a time it would no doubt run faster. Is there a way to do this?
tagged with: python
has comment: http://stackoverflow.com/comment/91084859
has title: Python Requests Open Multiple Instances
type: UnansweredQuestion
upvote count: 1
tagged with: python-requests
score: 1
has answer: http://stackoverflow.com/a/52067304
has answer: http://stackoverflow.com/a/52067313
type: Question
answer count: 2

http://stackoverflow.com/comment/91149956
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52099494
has text: Ok, thank you. That's one option, but if I want to change TF, is that possible, like I want to do that ?

http://stackoverflow.com/comment/90931705
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/51990165
has text: if there is a way to get it to also go to page 18 that would be great
score: 0

http://stackoverflow.com/comment/91034295
type: QuestionComment
comment on: http://stackoverflow.com/q/52041542
score: 0
has text: What is the function `grey_closing` and what shape has `test_result_aug_2`?
type: Comment

http://stackoverflow.com/comment/90970258
type: Comment
comment on: http://stackoverflow.com/a/52009625
score: 0
type: AnswerComment
has text: This is awesome! I am absolutely blown away by your explanation, I did not know that python had mechanisms to do this kind of thing.

http://stackoverflow.com/comment/90989390
type: QuestionComment
has text: @CrisLuengo Doesn't the line `ax = fig.add_axes([0, 0, 1, 1])` does exactly that? I also tried the other things suggested here, but I'm still getting same result. I'm pretty much stumped! :(
score: 0
comment on: http://stackoverflow.com/q/52017297
type: Comment

http://stackoverflow.com/q/52017849
has comment: http://stackoverflow.com/comment/91029423
has comment: http://stackoverflow.com/comment/90985839
has comment: http://stackoverflow.com/comment/91045914
type: Question
score: 0
has comment: http://stackoverflow.com/comment/90986161
tagged with: pandas
has comment: http://stackoverflow.com/comment/90986563
tagged with: rolling-average
has comment: http://stackoverflow.com/comment/90985896
has title: Pandas GroupBy Datetime and Mean using Rolling
has body: I want to calculate the mean of values rolling over Datetime index with a window of an P period of time centering on a Q period of time. I have a dataset that have records in second: Time Temperature 2017-11-28 22:00:03 58.34 2017-11-28 22:00:05 57.54 2017-11-28 22:00:07 58.18 2017-11-28 22:00:09 58.18 2017-11-28 22:00:12 58.18 I would like to group meaning the values 2.5 minutes before and after 5 minutes frecuency and get something like this: Time Temperature 2017-11-28 22:05:00 mean(5 minutes before and after) 2017-11-28 22:10:00 mean(5 minutes before and after) 2017-11-28 22:15:00 mean(5 minutes before and after) 2017-11-28 22:20:00 mean(5 minutes before and after) 2017-11-28 22:25:00 mean(5 minutes before and after) I'm trying with hum_sta.set_index('Time').groupby(pd.Grouper(freq='5Min')).rolling("5min").mean() But I'm not getting what I want, I just getting Multiindex Pandas Dataframe: Time Time Temperature 2017-11-28 22:00:00 2017-11-28 22:00:03 NaN 2017-11-28 22:00:05 57.94 2017-11-28 22:00:07 57.86 2017-11-28 22:00:09 58.18 2017-11-28 22:00:12 58.18
has comment: http://stackoverflow.com/comment/90985930
type: UnansweredQuestion
tagged with: datetime
tagged with: python
has comment: http://stackoverflow.com/comment/90986677
has comment: http://stackoverflow.com/comment/90985861
answer count: 0
has comment: http://stackoverflow.com/comment/90985877

http://stackoverflow.com/comment/90959798
comment on: http://stackoverflow.com/a/52004937
score: 0
has text: The solution implemented is stopping at error 429, I dont need that, I only need to batch 100 urls per second.
type: AnswerComment
type: Comment

http://stackoverflow.com/q/52012488
tagged with: python-asyncio
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/52016866
favorite count: 0
has answer: http://stackoverflow.com/a/52016866
type: Question
accepted answer: http://stackoverflow.com/a/52021212
answer count: 2
tagged with: python
has body: Trying to download and process jpegs from URLs. My issue isn't that certificate verification fails for some URLs, as these URLs are old and may no longer be trustworthy, but that when I try...except... the SSLCertVerificationError, I still get the traceback. System: Linux 4.17.14-arch1-1-ARCH, python 3.7.0-3, aiohttp 3.3.2 Minimal example: import asyncio import aiohttp from ssl import SSLCertVerificationError async def fetch_url(url, client): try: async with client.get(url) as resp: print(resp.status) print(await resp.read()) except SSLCertVerificationError as e: print('Error handled') async def main(urls): tasks = [] async with aiohttp.ClientSession(loop=loop) as client: for url in urls: task = asyncio.ensure_future(fetch_url(url, client)) tasks.append(task) return await asyncio.gather(*tasks) loop = asyncio.get_event_loop() loop.run_until_complete(main(['https://images.photos.com/'])) Output: SSL handshake failed on verifying the certificate protocol: &lt;asyncio.sslproto.SSLProtocol object at 0x7ffbecad8ac8&gt; transport: &lt;_SelectorSocketTransport fd=6 read=polling write=&lt;idle, bufsize=0&gt;&gt; Traceback (most recent call last): File "/usr/lib/python3.7/asyncio/sslproto.py", line 625, in _on_handshake_complete raise handshake_exc File "/usr/lib/python3.7/asyncio/sslproto.py", line 189, in feed_ssldata self._sslobj.do_handshake() File "/usr/lib/python3.7/ssl.py", line 763, in do_handshake self._sslobj.do_handshake() ssl.SSLCertVerificationError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: Hostname mismatch, certificate is not valid for 'images.photos.com'. (_ssl.c:1045) SSL error in data received protocol: &lt;asyncio.sslproto.SSLProtocol object at 0x7ffbecad8ac8&gt; transport: &lt;_SelectorSocketTransport closing fd=6 read=idle write=&lt;idle, bufsize=0&gt;&gt; Traceback (most recent call last): File "/usr/lib/python3.7/asyncio/sslproto.py", line 526, in data_received ssldata, appdata = self._sslpipe.feed_ssldata(data) File "/usr/lib/python…
upvote count: 13
tagged with: aiohttp
has title: ssl/asyncio: traceback even when error is handled
downvote count: 0
tagged with: ssl
has answer: http://stackoverflow.com/a/52021212
has comment: http://stackoverflow.com/comment/90983848
score: 13
tagged with: openssl

dlib
tags question: http://stackoverflow.com/q/52059560
tags question: http://stackoverflow.com/q/52052946
type: Tag
tag name: dlib
tags question: http://stackoverflow.com/q/52031502

http://stackoverflow.com/comment/91122897
has text: I have done the double `{{` and `}}` and it's not going thru :(
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52086096

http://stackoverflow.com/a/51958876
score: 0
type: Answer
has body: I think your data structure could be greatly improved by transforming your lists into a list of dicts instead of your suggested format because the id key is redundant as proposed. This is how it would present in a typical JSON array. results = [ { 'action': 'unlocked', 'availability': 'available', 'hostname': 'hostname_1', 'id': '1', 'operational': 'enabled', 'personality': 'master' },{ 'action': 'unlocked', 'availability': 'available', 'hostname': 'hostname_2', 'id': '2', 'operational': 'enabled', 'personality': 'slave' },{ 'action': 'unlocked', 'availability': 'available', 'hostname': 'hostname_3', 'id': '3', 'operational': 'enabled', 'personality': 'slave' } ] As for parsing the strings into lists you don't need regex or anything fancy, simple string methods will suffice. Here is a function that will convert your data into the aforementioned structure. def get_list_of_dicts(headers, rows): rows = [[i.strip() for i in row.split('|') if i] for row in rows] return [{k: v for k, v in zip(headers, row)} for row in rows]
answers question: http://stackoverflow.com/q/51958696

http://stackoverflow.com/comment/91058043
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52052589
has text: You specified Tensorflow in your title but your input data shape does not match. It should be (X, 28, 28, 1). Issues that I had when predicting with trained model were : number being too big so you can resize to (22, 22) and pad to get the 28x28 size, applying dilation (cv.dilate(data, (5,5))) can improve your accuracy, also make sure that your input data are made of a white number and black background.
score: 0

http://stackoverflow.com/comment/90922063
has text: you can check by printing your first and last name.
type: Comment
comment on: http://stackoverflow.com/q/51986258
score: 0
type: QuestionComment

http://stackoverflow.com/q/51988850
accepted answer: http://stackoverflow.com/a/51989061
has title: is there a way to put a blank entry in place of a node value for the particular classes that don't contain that node with Scrapy and Python
answer count: 1
favorite count: 0
tagged with: xpath
has comment: http://stackoverflow.com/comment/90927288
tagged with: python
score: -1
type: AnsweredQuestion
tagged with: scrapy
downvote count: 1
type: Question
has answer: http://stackoverflow.com/a/51989061
has body: I'm using python and scrapy to pull information from a database of companies online. Each company's information is completely contained in a parent node but not every company has a child node containing its website, some only have the company name. This means when i pull the data with xpath i'm getting 20 company names but only 18 web addresses (per page) which means when i zip up the lists and export i'm only getting the first 18 companies and the websites don't match. is there a way to insert a blank entry into the website list for the companies that don't have the website information node as one of the child nodes. Thank you www.company.co.uk ... ... from the above, when i run xpath('//div[@class="company"]/p/text()') ideally i'd get ['www.company.co.uk',''] with a blank entry for the second company node since they don't have a p node for the website. when i run xpath i'm getting a longer list of company names than websites so the lists don't match when i zip them together
upvote count: 0

http://stackoverflow.com/q/52089249
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91129543
tagged with: python
has title: I have a dataframe which consists certain dates and respective values
answer count: 0
score: 0
type: Question
has comment: http://stackoverflow.com/comment/91128789
has comment: http://stackoverflow.com/comment/91129279
has body: My challenge is that if any date is to be checked against a dates in the dataframe and it should be able to pull the respective value that which holds. I can show this to you Date Value 4/6/2006 1,500,000 4/6/2007 1,600,000 4/6/2008 1,650,000 4/6/2009 1,750,000 4/6/2010 1,800,000 4/6/2011 1,800,000 4/6/2012 1,500,000 4/6/2013 1,500,000 4/6/2014 1,250,000 4/6/2015 1,250,000 4/6/2016 1,000,000 4/6/2017 1,000,000 4/6/2018 1,030,000 the date sometimes isn't exact same as the one in the field, it may vary and the value nearest to that date should be pulled. It should be in a loop.
has comment: http://stackoverflow.com/comment/91128630
tagged with: python-3.x

http://stackoverflow.com/comment/95516768
has text: I guess you are simply trying to create a *new style* class, which became standard in Python 3. For that you may simply use `object` without need to import anything
comment on: http://stackoverflow.com/q/52111339
score: 3
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/90990302
type: AnswerComment
has text: Get the position by char or something instead of sel_first, for the “config” function
type: Comment
comment on: http://stackoverflow.com/a/52008540
score: 0

chunking
tags question: http://stackoverflow.com/q/52014482
tag name: chunking
tags question: http://stackoverflow.com/q/52107825
tags question: http://stackoverflow.com/q/52021855
type: Tag

http://stackoverflow.com/a/52119293
downvote count: 0
score: 1
has body: Here is the deal. PyQt5 was the issue. The latest versions seems to require os x 10.11.x. My solution was to uninstall PyQt5 and install the version, v=5.9.2, which is the version that works in a different virtual environment.
upvote count: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/52046048
type: Answer
answers question: http://stackoverflow.com/q/52046048

http://stackoverflow.com/q/52042199
accepted answer: http://stackoverflow.com/a/52042274
score: 0
has body: The get_weights() function in Keras returns the weight matrix along with the biases of a layer in a neural network. Let's say a variable x = layer.get_weights(). I'll transfer the value of x to a different network. In the new network, I'd like to add a layer to a trained network, but with the weights and biases of this newly added layer being equivalent to x. In other words, I'd like to use the same layer of the old network in the new one. How can I do this?
tagged with: neural-network
tagged with: keras
tagged with: keras-layer
type: AnsweredQuestion
has title: Opposite of get_weights() in Keras?
has answer: http://stackoverflow.com/a/52042274
type: Question
tagged with: python
answer count: 1

http://stackoverflow.com/a/51972129
type: Answer
answers question: http://stackoverflow.com/q/51971829
upvote count: 2
has body: You've misunderstood what a file-like object is. "File-like object" describes the interface an object presents - methods like read or write, and line-by-line iteration. It doesn't say anything about whether it stores data in memory. Regular file objects are file-like objects. File objects for OS-level pipes are file-like objects. io.StringIO and io.BytesIO objects are file-like objects, and those actually do work like you seem to have been thinking. Rather than thinking in terms of file-like objects, you should probably think about what OS-level mechanism you want to use to communicate between your processes. You've already got sockets; why not send data between your processes with a socket? A pipe would be another option. Shared memory is possible but platform-dependent and tricky; it's probably not the best option.
score: 2
downvote count: 0

http://stackoverflow.com/q/51957374
favorite count: 0
has comment: http://stackoverflow.com/comment/90865340
type: UnansweredQuestion
has title: Python got no result and KeyError:1
has answer: http://stackoverflow.com/a/51957560
tagged with: python
tagged with: dictionary
has comment: http://stackoverflow.com/comment/90865360
has body: def fre(dic, k): max_k = dic.keys()[0] max_v = dic.values()[0] while len(dic2) &lt; k: for key, value in dic.items(): if max_v &lt; value: max_k = key max_v = value dic2[max_k] = max_v del dic[max_k] return dic2 # dic is a dictionary, k is an int This question is to get the k biggest value in dic and get the matched key :value pairs. But I got running problem and got KeyError: 1.
downvote count: 0
score: 1
type: Question
upvote count: 1
answer count: 1
has comment: http://stackoverflow.com/comment/90865343

http://stackoverflow.com/q/51968603
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/90889013
accepted answer: http://stackoverflow.com/a/51969108
possible better answer: http://stackoverflow.com/a/51969249
has body: im using python 3.7 and i wanted to write a program that takes name of a city and returns the weather forcast . i started my code with : import re import urllib.request #https://www.weather-forecast.com/locations/Tel-Aviv-Yafo/forecasts/latest city=input("entercity:") url="https://www.weather-forecast.com/locations/" + city +"/forecasts/latest" data=urllib.request.urlopen(url).read data1=data.decode("uf-8") print(data1) but when I wanted to read my data i got this error : File "C:\Users\User\AppData\Local\Programs\Python\Python37-32\lib\urllib\request.py", line 503, in _call_chain result = func(*args) File "C:\Users\User\AppData\Local\Programs\Python\Python37-32\lib\urllib\request.py", line 649, in http_error_default raise HTTPError(req.full_url, code, msg, hdrs, fp) urllib.error.HTTPError: HTTP Error 404: Not Found Process finished with exit code 1 => can some one help me and tell what is the problem ? thanks:)
has comment: http://stackoverflow.com/comment/90888049
tagged with: python
tagged with: module
type: AnsweredQuestion
score: 3
upvote count: 3
tagged with: urllib
type: Question
has title: using the re and urllib.request module
has answer: http://stackoverflow.com/a/51969108
has comment: http://stackoverflow.com/comment/90887672
answer count: 2
has answer: http://stackoverflow.com/a/51969249

http://stackoverflow.com/a/52073266
has comment: http://stackoverflow.com/comment/91097152
upvote count: 0
type: Answer
score: -1
has body: To begin with, there are 2 problems in your code def chnum(xtrr): lis2 = [] for n in xtrr: if lis2[0][0] == n: # lis2 is empty. It does not have 0th element, much less another nested list. # this will only check if n is in the first element of lis2, what about all the other elements? continue lis1=[n] i = 0 for m in xtrr: if n== m: i+=1 lis1 += [i] lis2 += [lis1] return lis2 print(chnum('kkidduus')) But instead of fixing it I would advise to use the power of python. In particular its dictionaries like so: def chnum(xtrr): d = {n:0 for n in xtrr} # create a dict where keys are letters from input string for n in xtrr: d[n] += 1 # for each letter from input increment the dict's value for that letter return d print(chnum('kkidduus')) You will see how much more concise and readable this code is. if you are really adamant about getting results as nested lists then this dictionary is also a good starting point. Just dol = [list(t) for t in chnum('kkidduus').items()] afterwards EDIT: the OP wants to see counts at every repetition of the letter, so the code above can be modified to accomodate that def chnum(xtrr): d = {n:0 for n in xtrr} # create a dict where keys are letters from input string for n in xtrr: d[n] += 1 # for each letter from input increment the dict's value for that letter l = [[n, d[n]] for n in xtrr] return l print(chnum('kkidduus')) using a dictionary still has merit here as dict keys are hashed and thus will have speed advantages when counting letter occurence
answers question: http://stackoverflow.com/q/52072181
has comment: http://stackoverflow.com/comment/91101801
has comment: http://stackoverflow.com/comment/91096606
downvote count: 1

http://stackoverflow.com/a/52042515
has comment: http://stackoverflow.com/comment/91036107
has body: This is for comparing members nicely: a.keys() == b.keys() keys() returns a view over the members of a dictionary. To make this work with 2 lists of dicts, just wrap it in a comprehension: [a.keys() == b.keys() for a, b in zip(list1, list2)] It will return a list of True's and False's. If you want to know it they are all equal, then just wrap it with all(), so the final result is: all([a.keys() == b.keys() for a, b in zip(list1, list2)]) Benchmarks a = {} b = {} for i in range(100_0000): a[i] = i b[i] = i In [10]: %timeit a==b # wrong, but just for comparison 11.6 ms ± 265 µs per loop (mean ± std. dev. of 7 runs, 100 loops each) In [11]: %timeit a.keys()==b.keys() 16.9 ms ± 209 µs per loop (mean ± std. dev. of 7 runs, 100 loops each) In [17]: %timeit _compare(a, b) 30.6 ms ± 633 µs per loop (mean ± std. dev. of 7 runs, 10 loops each) In [18]: %timeit set(a.keys()) == set(b.keys()) 71 ms ± 1.04 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
has comment: http://stackoverflow.com/comment/91036136
has comment: http://stackoverflow.com/comment/91035963
has comment: http://stackoverflow.com/comment/91035960
has comment: http://stackoverflow.com/comment/91036232
upvote count: 2
type: Answer
has comment: http://stackoverflow.com/comment/91036789
has comment: http://stackoverflow.com/comment/91036988
has comment: http://stackoverflow.com/comment/91036489
has comment: http://stackoverflow.com/comment/91036389
has comment: http://stackoverflow.com/comment/91036041
has comment: http://stackoverflow.com/comment/91036888
score: 1
answers question: http://stackoverflow.com/q/52042430
downvote count: 1
has comment: http://stackoverflow.com/comment/91036112

http://stackoverflow.com/comment/90902845
has text: as @alok mentions it is essentially short circuited logic at work. since numpyArray0 is the first item in the mainList it is Ture because it is a single value. i.e. >>> numpyArray0 in [numpyArray0] True >>> numpyArray1 in [numpyArray1] True
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/51976229
type: Comment

http://stackoverflow.com/comment/91115440
type: Comment
comment on: http://stackoverflow.com/a/52082311
has text: Are you using an older version of pandas? It works fine when I try it with the DF you provided in the question
type: AnswerComment
score: 0

http://stackoverflow.com/q/52027981
has comment: http://stackoverflow.com/comment/91006329
has title: Identify project's version using setup.py
downvote count: 0
answer count: 1
favorite count: 0
has body: I'm trying to build wheels for multiple projects that support different python versions. I can't just use "python bdist_wheel" because it will build the wheels for python 2. So, is there an elegant way to identify project's supported python versions using setup.py? If something will be need to be added to setup.py, it's ok.
has answer: http://stackoverflow.com/a/52028056
tagged with: python
has comment: http://stackoverflow.com/comment/91007094
score: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91006344
upvote count: 2
tagged with: setuptools
tagged with: python-wheel
type: Question
accepted answer: http://stackoverflow.com/a/52028056

http://stackoverflow.com/q/52045064
tagged with: python
tagged with: regex
has answer: http://stackoverflow.com/a/56091087
has title: PyperclipException: only str, int, float, and bool values can be copied to the clipboard, not unicode
has answer: http://stackoverflow.com/a/52474844
has body: Currently I am going through the automate the boring stuff with python video course and am basically copying his shown code and trying to create the program that way, my code is currently the exact same as in the video. 1st I will state the function of the program intended than 2nd why I think it might be having the error stated above and would appreciate someone helping the noob out on solving this. The program is intended take a pdf document that we have copied to the clipboard, the document contains emails and phone numbers. We want it to extract the email and phone and than copy that info at the end to the clipboard. What is different between the instructor and I is I am using a different document to copy and extract phone numbers as the one he used no longer exists. The current output if I print the phone numbers copied is the letter u and than the intended phone number Current program output import re, pyperclip # Create a regex for phone numbers phoneRegex = re.compile(r''' (((\d\d\d)|(\(\d\d\d\)))? # area code &lt;optional&gt; (\s|-) # first seperator \d\d\d # first 3 digitis - # seperator \d\d\d\d # last 4 digits (((ext(\.)?\s)|x) # extension word-part&lt;optional&gt; (\d{2,5}))? # extension number-part&lt;optional&gt; 2,5 is to signify that it can be 2-5 digits ) ''', re.VERBOSE) # TODO:: Create a regex object for email addresses emailRegex = re.compile(r''' # we will make it search for emails that contain any numbers, letters plus or period symbols [a-zA-Z0-9_.+]+ # name part @ # @ symbol [a-zA-Z0-9_.+]+ # domain part ''', re.VERBOSE) # Get the text off the clipboard text = pyperclip.paste() # Extract the email/phone from this text extractedPhone = phoneRegex.findall(text) extractedEmail = emailRegex.findall(text) allPhoneNumbers = [] for phoneNumber in extractedPhone: allPhoneNumbers.append(phoneNumber[0]) print(allPhoneNumbers) # TODO: Copy the extracted email/phone to the cliboard results = '\n'.join(allPhoneNumbers) + '\n' + '\n'.join(extractedEmail) …
type: Question
has answer: http://stackoverflow.com/a/52050565
score: 0
tagged with: pyperclip
answer count: 3
tagged with: python-3.x
type: UnansweredQuestion

http://stackoverflow.com/comment/90896362
comment on: http://stackoverflow.com/q/51972853
has text: It works. Please put it on answer
type: Comment
type: QuestionComment
score: 1

http://stackoverflow.com/comment/90994456
comment on: http://stackoverflow.com/a/52014131
score: 0
type: AnswerComment
has text: @abarnert Thanks very much!!!, by the way should just directly install it will it interrupt my python 3.6
type: Comment

http://stackoverflow.com/comment/91177382
type: Comment
comment on: http://stackoverflow.com/a/52111585
score: 1
has text: But be aware that because of `set(l)` the new list has no more duplicates even if all of them were either positive or negative!
type: AnswerComment

http://stackoverflow.com/q/52086486
score: 1
favorite count: 0
has body: I have three 2-dim tensor in the training. I made like this below, but I get an error Cannot convert an unknown Dimension to a Tensor: ? mu = params[:, :self.num_mixture] sigma = params[:, self.num_mixture:self.num_mixture * 2] alpha = params[:, self.num_mixture * 2:self.num_mixture * 3] max_alpha = tf.cast(tf.argmax(alpha, axis=1 ), 'int32') mu = tf.gather_nd(mu,tf.stack([tf.range(max_alpha.shape[0])[...,tf.newaxis], mu[...,tf.newaxis]], axis=2)) sigma = tf.gather_nd(sigma,tf.stack([tf.range(max_alpha.shape[0])[...,tf.newaxis], sigma[...,tf.newaxis]], axis=2)) How can I fix it?
tagged with: python
tagged with: argmax
has title: How can use index in tensorflow?
answer count: 0
type: UnansweredQuestion
upvote count: 1
type: Question
tagged with: indexing
downvote count: 0

http://stackoverflow.com/comment/90969131
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/52009234
has text: Packages are not loaded into the script/folder. They need to be installed into the Python library that the program is using. A good practice is to use [virtual enviornments](https://packaging.python.org/guides/installing-using-pip-and-virtualenv/) and [pip requirements files](https://pip.pypa.io/en/stable/user_guide/#id1).
score: 0

http://stackoverflow.com/comment/90876815
type: QuestionComment
has text: also you're using `np.sum`, which is a sum of the row/column ... and that will only work when background is 0. Because sum of all 1's is not 1
score: 2
comment on: http://stackoverflow.com/q/51962649
type: Comment

http://stackoverflow.com/q/52019945
has title: Python: Getting class instance from stack / trace?
has comment: http://stackoverflow.com/comment/91222394
tagged with: accessor
tagged with: dynamic
has body: I'm working on an implementation of single-line AccessorFunc additions for classes and the new system works fine, but if I want to access internal functions, I have to pass self through to it and I'd rather not have to do that... In Short: The main questions are: 1) How do I get the class instance reference from within a method being called inside of a different class which was called by the class I am trying to reference, without passing it in as an argument... HIGH PRIORITY! 2) Why does property( ) seem to ask for more arguments than necessary if I use self.Get / self.Set / self.Del instead of lambda definitions? Get should have at most 2 - self and _default, Set should have 2 - self and _value, Del should have 1 - self, and doc is a string... -- It could also be something related to memory or some things staying in memory between builds ( I'm using Sublime Text ctrl + b )... LOW PRIORITY... I can just use lambda... 3) If anyone has time to look at my AccessorFunc calls in AcecoolCodeMappingSystem in Sublime Text - why do I need to define some of the functions in the object such as def GetLanguage( self, _default = 'x' ): return None -- when I create the Accessor Functions in init and I never call the class by itself, I always use the instance reference.... Some functions which are used early, if not pre-defined to be overwritten, I get a Key not found or some similar error.... LOW PRIORITY ( New version doesn't have this issue ) Once it is ready, I'll post the solution in the forum in response to someone asking about dynamic accessorfuncs / properties... For instance, I do: class MyClassBase: pass class MyClass( MyClassBase ): # Note: Arg 4 is optional to set Allowed Data-Types and can be None, a type( x ) or a Dict, List or Tuple of type( x )'s which is converted to an O( 1 ) Dict of allowed data-types used to restrict the setter.. # Note: Arg 5 is optional to set Allowed Stored Values and can be None, a single value or a Dict, List or Tuple of values which is c…
has comment: http://stackoverflow.com/comment/91102193
type: Question
score: 0
answer count: 1
has answer: http://stackoverflow.com/a/52136347
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/a/52101853
answers question: http://stackoverflow.com/q/52095254
type: AcceptedAnswer
has body: I finally got it!! If anyone has any interest, here is the code: import xlsxwriter import pandas as pd def outputdata(Filename,Sheetname,df): try: xlsx_file = pd.ExcelFile(Filename) except: xlsxwriter.Workbook(Filename) xlsx_file = pd.ExcelFile(Filename) writer = pd.ExcelWriter(Filename, engine='openpyxl') IsSheetThereAlready = False for sheet in xlsx_file.sheet_names: if sheet == Sheetname: df2 = xlsx_file.parse(sheet) df2.to_excel(writer,sheet_name= sheet, index=False) df.to_excel(writer,sheet_name= sheet, startrow=len(df2)+1, index=False, header=None) IsSheetThereAlready = True else: df2 = xlsx_file.parse(sheet) df2.to_excel(writer,sheet_name= sheet, index=False) if IsSheetThereAlready is False: df.to_excel(writer,sheet_name = Sheetname, index=False) writer.save() return
type: Answer
score: 2
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52095254
upvote count: 2

http://stackoverflow.com/a/52085264
answers question: http://stackoverflow.com/q/52084871
has comment: http://stackoverflow.com/comment/91120898
has comment: http://stackoverflow.com/comment/91121227
has body: Here we search for some identifier (like cycles and apply a different regex) import re with open('test.txt','r') as f: for line in f: if re.search(r'Cycles',line): m=re.findall(r'\d+$',line) else: m=re.findall(r'Current&gt; (\d+)',line) print(m)
score: 0
type: Answer
has comment: http://stackoverflow.com/comment/91121346

http://stackoverflow.com/comment/99562106
comment on: http://stackoverflow.com/q/52087571
type: Comment
type: QuestionComment
score: 6
has text: The question is not complete. Can you please provide a link to the data file? And, there are a lot of variables used inside of plot_results(), where are they set? Can you provide a minimum complete code example that demonstrates the problem?

http://stackoverflow.com/comment/90922272
comment on: http://stackoverflow.com/q/51986378
score: 0
type: Comment
type: QuestionComment
has text: There is very little explanation of the problem here and it is at all not clear what the OP is trying to do with the wrapping function

http://stackoverflow.com/a/52011591
upvote count: 2
type: Answer
has body: You are trying to get the href prematurely. You are trying to extract the attribute directly from a span tag that has nested a tags, rather than a list of a tags. for each_rating in ratings: page = requests.get(each_rating) soup = BeautifulSoup(page.text, 'html.parser') span = soup.find('span', class_='letter-pages') for a in span.find_all('a'): href = a.get('href') pages_scrape.append(href) I didn't test this on all pages, but it worked for the first one. You pointed out that on some of the pages the content wasn't getting scraped, which is due to the span search returning None. To get around this you can do something like: for each_rating in ratings: page = requests.get(each_rating) soup = BeautifulSoup(page.text, 'html.parser') span = soup.find('span', class_='letter-pages') if span: for a in span.find_all('a'): href = a.get('href') pages_scrape.append(href) print(href) else: print('span.letter-pages not found on ' + page) Depending on your use case you might want to do something different, but this will indicate to you which pages don't match your scraping model and need to be manually investigated.
score: 2
answers question: http://stackoverflow.com/q/52011353
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/52011353
downvote count: 0
has comment: http://stackoverflow.com/comment/91002633
has comment: http://stackoverflow.com/comment/90977759

selenium-webdriver
tags question: http://stackoverflow.com/q/52040630
tags question: http://stackoverflow.com/q/51972597
tags question: http://stackoverflow.com/q/52099417
tags question: http://stackoverflow.com/q/52060834
tags question: http://stackoverflow.com/q/52013284
tags question: http://stackoverflow.com/q/52084458
tags question: http://stackoverflow.com/q/51987761
tags question: http://stackoverflow.com/q/52087021
tags question: http://stackoverflow.com/q/51986258
tags question: http://stackoverflow.com/q/52035719
tags question: http://stackoverflow.com/q/51965561
tags question: http://stackoverflow.com/q/51994766
tags question: http://stackoverflow.com/q/51977550
tags question: http://stackoverflow.com/q/52009771
tags question: http://stackoverflow.com/q/51958273
tags question: http://stackoverflow.com/q/51994821
tags question: http://stackoverflow.com/q/52067414
tags question: http://stackoverflow.com/q/52022841
tags question: http://stackoverflow.com/q/51976238
tags question: http://stackoverflow.com/q/52109777
tags question: http://stackoverflow.com/q/52009351
tag name: selenium-webdriver
tags question: http://stackoverflow.com/q/52013679
tags question: http://stackoverflow.com/q/51958574
tags question: http://stackoverflow.com/q/52010624
tags question: http://stackoverflow.com/q/52020105
tags question: http://stackoverflow.com/q/52101431
tags question: http://stackoverflow.com/q/52074660
tags question: http://stackoverflow.com/q/52023371
tags question: http://stackoverflow.com/q/52066226
tags question: http://stackoverflow.com/q/52111479
tags question: http://stackoverflow.com/q/52006499
tags question: http://stackoverflow.com/q/51988165
tags question: http://stackoverflow.com/q/52010458
type: Tag
tags question: http://stackoverflow.com/q/51973253
tags question: http://stackoverflow.com/q/52069778
tags question: http://stackoverflow.com/q/51975996
tags question: http://stackoverflow.com/q/51984774
tags question: http://stackoverflow.com/q/52048943
tags question: http://stackoverflow.com/q/52096755
tags question: http://stackoverflow.com/q/52011775
tags question: http://stackoverflow.com/q/52080597
tags question: http://stackoverflow.com/q/51978555
tags question: http://stackoverflow.com/q/52002958
tags question: http://stackoverflow.com/q/52073181
tags question: http://stackoverflow.com/q/52002135

http://stackoverflow.com/comment/91020069
type: Comment
type: QuestionComment
has text: @BurhanKhalid how?
comment on: http://stackoverflow.com/q/52034485
score: 0

http://stackoverflow.com/q/52040923
type: Question
has comment: http://stackoverflow.com/comment/91057026
has body: we started implementing a mongoDB IO Connector for first Apache Beam test, and the Source part seems to work properly. Concerning the Sink part, the execution leads to an error... We used this guidelines for the implementation: https://beam.apache.org/documentation/sdks/python-custom-io/ Our implementation can be found here: https://github.com/PEAT-AI/beam-extended The example I try to run is the following: """ A simple example of how to use the MongoDB reader and writer. If you like, you can test it out with these commands (requires Docker and virtualenv for python2): $ virtualenv venv $ source venv/bin/activate $ pip install google-cloud-dataflow pymongo $ # The following line is optional if mongod is running already $ sudo service mongod stop $ docker run -p 27017:27017 --name dataflowtest --rm mongo:3.2 $ docker exec -it dataflowtest mongo &gt; use mydb &gt; db.mycollection.insert({ _id: ObjectId() }) &gt; exit $ python -m simple $ # The following line is optional if mongod was shut down previously $ sudo service mongod start """ from __future__ import absolute_import import logging import apache_beam as beam from apache_beam.options.pipeline_options import PipelineOptions from beam_extended.io.mongodbio import ReadFromMongo, WriteToMongo def transform_doc(document): print(document) return {'_id': str(document['_id'])} def run(argv=None): """Main entry point; defines and runs the aggregation pipeline.""" connection_string = 'mongodb://localhost:27017' # Can also fetch a connection string from a Google Cloud Storage file. # This might be preferable to avoid pickling the mongodb connection string. # E.g. # connection_string = 'gs://my-bucket/mongo_connection_string.txt' # where "mongo_connection_string.txt" contains a single line with the connection string. # with beam.Pipeline(runner='DirectRunner', options=PipelineOptions()) as pipeline: options = PipelineOptions() with beam.Pipeline(options=options) as pipeline: (pipeline | 'read' &gt;&gt; ReadFromMongo(connect…
score: 0
has comment: http://stackoverflow.com/comment/91123066
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91800320
tagged with: apache-beam
tagged with: python
tagged with: apache-beam-io
has comment: http://stackoverflow.com/comment/91943769
has title: Error trying to implement a mongoDB IO connector Sink

http://stackoverflow.com/comment/91149715
comment on: http://stackoverflow.com/q/52099464
score: 0
has text: It returns None
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52068447
tagged with: python
has body: import os path = 'c:\users\name\desktop\project\input_samples' for xyz_file in os.listdir(path): if xyz_file.endswith('xyz'): (operations of function here) In the folder 'input samples' I have multiple .xyz files (coordinate files). I'm trying to create a function that accepts a path to one input xyz file and not the directory. I don't want it to loop over the files, just process a single file. I want to do it without having to remove all the files except 1 in the directory path, but i'm not sure how to redefine the function. Any help would be much appreciated :)
accepted answer: http://stackoverflow.com/a/52068512
type: AnsweredQuestion
score: 0
upvote count: 1
downvote count: 1
type: Question
has title: Changing a path from a directory to a single input file
has answer: http://stackoverflow.com/a/52068512
answer count: 1
favorite count: 0

http://stackoverflow.com/a/52014572
type: Answer
has comment: http://stackoverflow.com/comment/90979825
has comment: http://stackoverflow.com/comment/90979779
upvote count: 1
has body: By specifying the separator as sep=",|;|\|", you make that whole string a separator. Instead, you want to use the Sniffer from the csv module to detect the CSV dialect used in each file, in particular the delimiter. For example, for a single file example.csv: import csv with open('example.csv', newline='') as csvfile: dialect = csv.Sniffer().sniff(csvfile.read(1024)) sep = dialect.delimiter df = pd.read_csv('example.csv', sep=sep) Don't enable the Python engine by default, as it is much slower.
score: 1
answers question: http://stackoverflow.com/q/52014473
has comment: http://stackoverflow.com/comment/90979727
downvote count: 0
has comment: http://stackoverflow.com/comment/90979657
has comment: http://stackoverflow.com/comment/90979614

http://stackoverflow.com/comment/90964570
type: QuestionComment
has text: @Nu2prog are you sure you have jacobian function right? Please check my solution, optimisation achieved though :p
score: 0
comment on: http://stackoverflow.com/q/52004412
type: Comment

http://stackoverflow.com/q/52029148
answer count: 4
has answer: http://stackoverflow.com/a/52032494
type: AnsweredQuestion
score: 2
accepted answer: http://stackoverflow.com/a/52029252
tagged with: list
upvote count: 2
has title: Convert list of dictionaries to csv file
type: Question
has body: I have a list of dictionaries of this kind : [ {'site1':'data1'}, {'site2':'data2'} ] What would be the proper way to generate a csv file with the data in this order ? : row 1 row2 site1 data1 site2 data2
has answer: http://stackoverflow.com/a/52029581
possible better answer: http://stackoverflow.com/a/52029171
has answer: http://stackoverflow.com/a/52029252
has answer: http://stackoverflow.com/a/52029171
downvote count: 0
favorite count: 0
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
tagged with: dictionary

http://stackoverflow.com/q/51993428
tagged with: python
has comment: http://stackoverflow.com/comment/90936623
type: AnsweredQuestion
downvote count: 0
has comment: http://stackoverflow.com/comment/90936423
has comment: http://stackoverflow.com/comment/90936717
has title: Function to create a non equally spaced array in numpy
type: Question
has comment: http://stackoverflow.com/comment/90936530
score: 1
accepted answer: http://stackoverflow.com/a/51993668
has comment: http://stackoverflow.com/comment/90936492
tagged with: numpy
upvote count: 1
answer count: 1
has answer: http://stackoverflow.com/a/51993668
has comment: http://stackoverflow.com/comment/90936661
favorite count: 0
has body: I would like to create an array with the form [1, 2, 4, 8, 16, 32, ...]. Not always with that spacing between numbers. Is there a linspace/arange type function which allows me to create vector of non equally spaced numbers? Thanks

http://stackoverflow.com/a/51967084
has body: What you receive from requests.post is not JSON, it's a dictionary. One that can be encoded in JSON, via json.dumps(result). JSON is a text format to represent objects (the "ON" means "object notation"). You can convert a dictionary (or list or scalar) into a JSON-encoded string, or the other way around. What requests.post does is taking the JSON response and already parsing it (with json.loads), so you don't have to think about JSON at all.
type: AcceptedAnswer
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/90884125
upvote count: 7
answers question: http://stackoverflow.com/q/51967052
score: 7
accepted answer of: http://stackoverflow.com/q/51967052

http://stackoverflow.com/a/52011144
answers question: http://stackoverflow.com/q/52010677
score: 0
has body: try this by declaring the list before. characters = ['a','b','c','d'] a = [] if True in a = [c in 'hello' for c in characters]: print('true') else: print('false')
type: Answer

http://stackoverflow.com/comment/118618292
score: 0
type: Comment
has text: That is very unfortunate as I have an actual map below so transparency is required :-/ But thanks for the explanation!
comment on: http://stackoverflow.com/a/52101597
type: AnswerComment

http://stackoverflow.com/comment/92384420
score: 0
has text: @user4815162342: I stated several times that the win32 support for streams with stdio is severely lacking, and linked to the relevant Python bug tracker issue for this. We then discussed some of the limitations of the shim, and some possible extensions. That could have been it, but I have the feeling that you are more about making demands here than having a discussion about the possibilities or options. As such, I'm just going to leave this conversation.
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52702646

http://stackoverflow.com/q/52094206
tagged with: sqlalchemy
has comment: http://stackoverflow.com/comment/91218180
answer count: 0
tagged with: database
has body: I have a table consisting of consisting of three fields, here is the pseudocode class Table(Base): a = Column() b = Column() c = Column() When I do commit, I want to restrict any change to field "b" irrespective that it is changed in code. t = getObj(c=3) # Gets object of Table with a=1, b=2, c=3 t.a = 5 t.b = 10 session.merge(t) session.commit() After I commit to database, I make a query: new_t = getObj(c=3) new_t.a ==&gt; should be 5 new_t.b ==&gt; should be 2 new_t.c ==&gt; should be 3 I do not want the new value of t.b to persist in DB, irrespective it is changed above or not. Please let me know in comments, if anything doesn't make sense in question.
type: UnansweredQuestion
tagged with: sql
downvote count: 0
has comment: http://stackoverflow.com/comment/91145095
score: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/91139968
tagged with: python
has title: Update specific fields of object in SQLAlchemy
has comment: http://stackoverflow.com/comment/91138779
tagged with: mysql
upvote count: 1

http://stackoverflow.com/q/51982898
type: UnansweredQuestion
tagged with: python
tagged with: openpyxl
has comment: http://stackoverflow.com/comment/91089425
has comment: http://stackoverflow.com/comment/90915376
type: Question
has body: Am trying to convert csv to xlsx using python 2.7 version but it gives me error like Traceback (most recent call last): File "C:/Users/XYZ/Desktop/converter.py", line 13, in &lt;module&gt; ws.cell(row=r, column=c).value = val File "C:\Python27\lib\openpyxl\cell\cell.py", line 291, in value self._bind_value(value) File "C:\Python27\lib\openpyxl\cell\cell.py", line 190, in _bind_value value = self.check_string(value) File "C:\Python27\lib\openpyxl\cell\cell.py", line 149, in check_string value = unicode(value, self.encoding) UnicodeDecodeError: 'utf8' codec can't decode byte 0x93 in position 1037: invalid start byte And My code is import os import glob import csv import openpyxl for csvfile in glob.glob(os.path.join('.', 'i.csv')): wb = openpyxl.Workbook() ws = wb.active with open(csvfile, 'rb') as f: reader = csv.reader(f) for r, row in enumerate(reader, start=1): for c, val in enumerate(row, start=1): ws.cell(row=r, column=c).value = val wb.save(csvfile + '.xlsx') Below is the CSV File name i.csv AFFECTED PLATFORM Column Name and 1 row Cell data. "• Adobe Photoshop CC 2018 version 19.1.3 and earlier. &lt;br /&gt; • Adobe Photoshop CC 2017 version 18.1.3 and earlier for mac OS.&lt;br /&gt; • Adobe Photoshop CC 2017 version 18.1.2 and earlier for Windows.&lt;br /&gt; • Adobe Acrobat DC Consumer version 2018.011.20038 and earlier.&lt;br /&gt; • Adobe Acrobat Reader DC Consumer version 2018.011.20038 and earlier. &lt;br /&gt; • Adobe Acrobat 2017 Classic 2017 version 2017.011.30079 and earlier. &lt;br /&gt; • Adobe Acrobat Reader 2017 Classic 2017 version 2017.011.30079 and earlier. &lt;br /&gt; • Adobe Acrobat DC Classic 2015 version 2015.006.30417 and earlier. &lt;br /&gt; • Adobe Acrobat Reader DC Classic 2015 version 2015.006.30417 and earlier.&lt;br /&gt; "
has comment: http://stackoverflow.com/comment/91066978
has title: CSV to XLSX in Python
has comment: http://stackoverflow.com/comment/90954314
has comment: http://stackoverflow.com/comment/90943992
tagged with: python-2.7
score: 0
has comment: http://stackoverflow.com/comment/91051039
tagged with: http://stackoverflow.com/tag/xlsx
tagged with: http://stackoverflow.com/tag/csv
has answer: http://stackoverflow.com/a/52075173
upvote count: 1
answer count: 1
downvote count: 1
favorite count: 0
linked to: http://stackoverflow.com/q/17684610
has comment: http://stackoverflow.com/comment/90927624

http://stackoverflow.com/q/51999891
has body: I am trying to extract 150 lines in random from a dataset of 500 lines. So I would do it at random. My data object,color,label puppy,white,animal mango,orange,fruit pants,black,clothing My script import pandas import pandas as pd df = pd.read_csv ('data.csv', sep = ',') data_random = df.sample (150) print (data_random) But the result is very strange, I do not have the complete line... object ... label 277 grape ... fruit 116 bear ... animal 495 ... ... ... Is it possible to have the full line?
type: Question
tagged with: pandas
possible better answer: http://stackoverflow.com/a/52000089
has comment: http://stackoverflow.com/comment/90948866
has answer: http://stackoverflow.com/a/52000089
upvote count: 2
has answer: http://stackoverflow.com/a/51999945
answer count: 2
tagged with: python
accepted answer: http://stackoverflow.com/a/51999945
has comment: http://stackoverflow.com/comment/90948970
score: 2
type: AnsweredQuestion
has title: Make a random of a dataset with pandas
downvote count: 0
favorite count: 0

http://stackoverflow.com/a/52067799
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/91088917
score: 1
upvote count: 1
accepted answer of: http://stackoverflow.com/q/52047625
answers question: http://stackoverflow.com/q/52047625
has body: Usually it doesn't matter that much either way. Even when libraries/APIs talk about "sentences" they really mean "texts" which might be multiple sentences. The worst case, if you wind up with some contexts spanning texts that have no essential relation, is that it adds a little noise to training... which might require a little more training to reach optimality on the other non-noise contexts. But often run-together texts are actually related, from the same original source, so such contexts might still capture real useful patterns, and thus be a net positive compared to smaller text fragments. You could try it both ways and score the results against each other to see if one or the other is better with your corpus and end task.
type: AcceptedAnswer

http://stackoverflow.com/comment/108522622
type: AnswerComment
has text: As a note, at least in Django 3.0 (I haven't tested on other versions), you should not initialize an instance of the filter in `list_filter`, instead passing the class as `MyDateTimeFilter`.
comment on: http://stackoverflow.com/a/51975962
type: Comment
score: 2

http://stackoverflow.com/q/52032525
tagged with: iterator
has body: In the code given below, I wrote two functions. The second one applies the first function. I am trying to see if it's possible to have an iteration over the elements of the first function. This is the code: def numbers(n): for m in range(n): print(m) def sets(n): r=[] for e in numbers(n): r.append([e]) return r sets(6) The result I would like is [[0], [1], [2], [3], [4], [5]]. I know there are other ways (not defining a function) in order to obtain all numbers from 0 to m-1, but for what the actual code I have developed, this relates to the issue I am trying to fix. The error message I get is: 'NoneType' object is not iterable
tagged with: function
has title: listing the elements given by a function's output
score: 0
answer count: 3
accepted answer: http://stackoverflow.com/a/52032938
has comment: http://stackoverflow.com/comment/91015280
possible better answer: http://stackoverflow.com/a/52032578
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/91016247
has answer: http://stackoverflow.com/a/52032578
has answer: http://stackoverflow.com/a/52032637
tagged with: python
type: AnsweredQuestion
tagged with: list
has answer: http://stackoverflow.com/a/52032938
type: Question

http://stackoverflow.com/comment/91039927
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52044423
has text: Its simple: `raw_input()` returns string values, while `input()` return integer values. You have to use `raw_input()`.

http://stackoverflow.com/comment/91129555
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52089571
has text: read and understand this: https://nedbatchelder.com/text/names.html
score: 0

http://stackoverflow.com/a/52098394
has comment: http://stackoverflow.com/comment/91148838
answers question: http://stackoverflow.com/q/52098107
downvote count: 0
type: Answer
score: 3
has comment: http://stackoverflow.com/comment/91148594
has comment: http://stackoverflow.com/comment/91148721
has comment: http://stackoverflow.com/comment/91148802
type: AcceptedAnswer
upvote count: 3
has comment: http://stackoverflow.com/comment/91148532
has body: GridSearchCV extends BaseSearchCV class. This means that it will be using the fit() function defined in BaseSearchCV. So now as you can see in source code here: ... ... scorers, self.multimetric_ = _check_multimetric_scoring( self.estimator, scoring=self.scoring) ... ... It checks all the parameters supplied during the construction of GridSearchCV here. For 'scoring' param, its calling a method _check_multimetric_scoring(). Now on top of this file, you will see many imports. The method _check_multimetric_scoring points to scorer.py file: Similarly tracing the method calls, we will reach here: SCORERS = dict(explained_variance=explained_variance_scorer, r2=r2_scorer, neg_median_absolute_error=neg_median_absolute_error_scorer, neg_mean_absolute_error=neg_mean_absolute_error_scorer, neg_mean_squared_error=neg_mean_squared_error_scorer, neg_mean_squared_log_error=neg_mean_squared_log_error_scorer, accuracy=accuracy_scorer, roc_auc=roc_auc_scorer, ... ... ... ... Looking at roc_auc, we will reach here: roc_auc_scorer = make_scorer(roc_auc_score, greater_is_better=True, needs_threshold=True) Now look at the parameters here, roc_auc_score is sent to make_scorer. So from where it is imported? Look at the top of this file and you will see this: from . import (r2_score, median_absolute_error, mean_absolute_error, mean_squared_error, mean_squared_log_error, accuracy_score, f1_score, roc_auc_score, average_precision_score, precision_score, recall_score, log_loss, balanced_accuracy_score, explained_variance_score, brier_score_loss) So from here, the actual scoring object is returned to the GridSearchCV. Now, the library is using relative and absolute imports, and as @Denziloe correctly said, those imports are local for that module, not the global imports. See these answers for more information on import scope and namespaces: Python "import" scope Python: Namespaces with Module Imports And this python documentation page
accepted answer of: http://stackoverflow.com/q/52098107

http://stackoverflow.com/comment/91097426
comment on: http://stackoverflow.com/a/52073775
score: 0
type: Comment
has text: you have to read your xlsx file as a df using read_excel and then write out using the code above or you can directly write the df which you have instead of saving it to file5
type: AnswerComment

http://stackoverflow.com/q/52081408
tagged with: buffer
has body: I have a homemade tool that runs a lot of steps and then I'm caching all is going on with the package import logging and then writing it into a file for logging purposes. I would like to make my process smarter and I was wondering how to keep all the data collected for the log steps in a buffer and then send it to cloud or a database table or any other destination. thanks so much for your advice and approaches.
type: UnansweredQuestion
tagged with: python
answer count: 0
has comment: http://stackoverflow.com/comment/91113161
tagged with: amazon-kinesis
type: Question
score: 0
has title: Python 3.6 keep log info in buffer and then send it
has comment: http://stackoverflow.com/comment/91117641
tagged with: amazon-web-services
tagged with: python-3.x

http://stackoverflow.com/a/51977180
downvote count: 0
score: 1
type: Answer
upvote count: 1
answers question: http://stackoverflow.com/q/51976517
has body: I solved this myself: os.rename(os.path.join(root, filename), os.path.join(newfolder, "ref" + re.sub(r'\d{2}', '', name) + ext)) Adding the {2} made it look for 2 consecutive numbers, and left the 1 alone. Thanks!

http://stackoverflow.com/q/52011435
tagged with: python
has answer: http://stackoverflow.com/a/52011835
has answer: http://stackoverflow.com/a/52011533
has answer: http://stackoverflow.com/a/52011473
type: Question
answer count: 6
score: 4
has answer: http://stackoverflow.com/a/52011635
has answer: http://stackoverflow.com/a/52011883
has body: I'll illustrate my question with a couple of overly simple functions that just square numbers. But it is the general best practice for writing functions that I want to know about. Suppose I have a number that I want to square, I could write the following function. def square (x): y = x**2 return y If I had a list of numbers and wanted to get the list in which each element is squared, I could use def square (x_list): y_list = [] for x in x_list: y_list.append( x**2 ) return y_list But I want to write just one function that will handle both of these cases. It will see whether the input is a number or a list, and act accordingly. I could do this using type to detect type, but I'd like to know what the most pythonic way to do it is.
upvote count: 4
tagged with: function
has answer: http://stackoverflow.com/a/52011576
downvote count: 0
favorite count: 0
type: UnansweredQuestion
has title: How to make a function that can handle single inputs or lists of inputs

http://stackoverflow.com/comment/91308817
type: Comment
score: 0
has text: I reinstall python,and this problem is fixed,thanks a lot. even though the PYTHONPATH is still replaced by 'lib',anyway,my C++ program can work properly.
type: QuestionComment
comment on: http://stackoverflow.com/q/52057307

http://stackoverflow.com/q/52040297
has answer: http://stackoverflow.com/a/52043704
tagged with: printing
has title: How to print() output to previous line after input
score: 2
linked to: http://stackoverflow.com/q/7173850
has answer: http://stackoverflow.com/a/52040358
downvote count: 0
linked to: http://stackoverflow.com/q/12032214
type: UnansweredQuestion
favorite count: 0
type: Question
tagged with: input
tagged with: python
has answer: http://stackoverflow.com/a/52040483
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/91032811
upvote count: 2
has comment: http://stackoverflow.com/comment/91033313
answer count: 3
has body: for i in range(1, 10): print('temp {}: '.format(i), end = '') temp = float(input('')) print(' Celsius = {} Fahrenheit'.format(9 / 5 * temp + 32)) output is: temp 1: 0 Celsius = 32 Fahrenheit temp 2: 5 Celsius = 41 Fahrenheit I want print ' Celsius =...' in previous line. I want to output be: temp 1: 0 Celsius = 32 Fahrenheit temp 2: 5 Celsius = 41 Fahrenheit
has comment: http://stackoverflow.com/comment/91031016

azure-iot-hub
type: Tag
tags question: http://stackoverflow.com/q/51956929
tag name: azure-iot-hub

http://stackoverflow.com/a/52012810
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/91011035
has comment: http://stackoverflow.com/comment/91008921
has comment: http://stackoverflow.com/comment/91006533
upvote count: 2
has body: Try in Dockerfile RUN apt-get update &amp;&amp; sudo apt-get upgrade and check dependecies apt-get install -f python2.7-dev
answers question: http://stackoverflow.com/q/52012559
score: 2

timestamp
tags question: http://stackoverflow.com/q/52101757
tags question: http://stackoverflow.com/q/52007139
tag name: timestamp
type: Tag
tags question: http://stackoverflow.com/q/52089857

http://stackoverflow.com/a/51977890
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/51977766
has body: Try with this df=pd.read_csv("text.csv", sep=', ',header =None,names=['colA','colB','colC','colD','colE','colF']) df.head() it outputs: Out[25]: colA colB colC colD colE colF 0 1977 PA 2017-08-07 55 New Firms 327.0 1 1978 NY 2017-08-07 45 New Firms $30,127 2 1978 NY 2017-08-07 $10,000 New Firms 1,000
score: 4
upvote count: 4

http://stackoverflow.com/a/52090314
upvote count: 1
score: 1
accepted answer of: http://stackoverflow.com/q/52089522
answers question: http://stackoverflow.com/q/52089522
type: AcceptedAnswer
downvote count: 0
type: Answer
has body: When you call the hashlib.md5 command it does expect a string like object instead of a file handle. But guess what you already have that. So there is no need to read it back from the file. import tempfile import hashlib with tempfile.NamedTemporaryFile() as temp: data = payload.get_payload(decode=True) temp.write(data) print(hashlib.md5(data).hexdigest())

http://stackoverflow.com/comment/101159113
score: 0
has text: You certainly can use multiple files. The “spawn” start method puts (the same) restrictions on how to write the main script file however many you use.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52107471

http://stackoverflow.com/comment/91157894
score: 0
comment on: http://stackoverflow.com/a/52048228
type: Comment
has text: Hi, this example did not address only filtering purchase order numbers that are late, so I thought the other answer someone gave more accurately depicted that. I would appreciate if you would be able to help me with this issue, as the other answer does not fully work as well. Thank you!
type: AnswerComment

http://stackoverflow.com/q/52102252
upvote count: 2
has answer: http://stackoverflow.com/a/52809794
type: Question
tagged with: self-organizing-maps
tagged with: feature-selection
has title: How to get the important features in SOM(Self Organizing Maps)?
has body: I am looking at the popular python implementation of SOM : MiniSom. A lot of blogs cite various examples like fraud detection using MiniSom. While I do get how we can get the items associated with the outlier nodes(BMUs), I am not able to understand how to get the important features that distinguish the outlier. What is a function or package that may help me do that?
score: 2
answer count: 1
downvote count: 0
favorite count: 0
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/comment/91056883
comment on: http://stackoverflow.com/q/52050623
has text: You can change `for val in df['col1']:` to `for val in df['col1'].astype(str) + ' - ' df['col2'].astype(str):`
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/51986530
upvote count: 3
has body: You may use contextmanager. from contextlib import contextmanager @contextmanager def csn_context(csn_obj): try: csn_obj.csn(0) yield finally: csn_obj.csn(1) with csn_context(self): self.spidev.xfer2(txbuffer)
downvote count: 0
answers question: http://stackoverflow.com/q/51986378
type: Answer
score: 3

http://stackoverflow.com/comment/91142226
comment on: http://stackoverflow.com/q/52096033
score: 0
type: QuestionComment
has text: Are you saying that `sched.shutdown()` didn't work, or was never called, or something else?
type: Comment

http://stackoverflow.com/comment/90928410
comment on: http://stackoverflow.com/q/51989196
type: Comment
type: QuestionComment
score: 1
has text: If it uses user input, I guess you need to check their field names against a list of the database schema before executing the query

http://stackoverflow.com/q/52065886
tagged with: php
has title: "there is no package called 'rmarkdown" when calling R script from PHP
tagged with: r-markdown
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52083794
linked to: http://stackoverflow.com/q/9546324
type: Question
has comment: http://stackoverflow.com/comment/91112096
answer count: 2
tagged with: http://stackoverflow.com/tag/r
score: 0
possible better answer: http://stackoverflow.com/a/52081853
accepted answer: http://stackoverflow.com/a/52083794
has answer: http://stackoverflow.com/a/52081853
tagged with: python
has comment: http://stackoverflow.com/comment/91082671
has body: I have a WAMP server 3.1.3 running a HTML main page that takes a 'start' date, 'end' date and 'organization' text inputs. The submit button than passes the info to a following php script: &lt;?php $from = strtotime($_POST["fromdate"]); $to = strtotime($_POST["todate"]); $org = $_POST["org"]; $python = "C:\Python27\python.exe "; $pyscript = "C:\wamp64\www\DMARC\Sample_Reports\GetOutlookAttachments.py $from $to $org"; echo $python, $pyscript; chdir("C:\wamp64\www\DMARC\Sample_Reports"); exec("$python $pyscript"); ?&gt; The script takes the data, converts it to the proper format and passes it to a python 2.7 script. The data the python script receives is used to filter some logs. Once the logs are filtered the python script calls an R-markdown script to produce an HTML report. The Python code that calls the rmarkdown script: cmd = '"C:/PROGRA~1/R/R-3.5.1/bin/x64/Rscript.exe -e \"Sys.setenv(RSTUDIO_PANDOC=\'C:/Program Files (x86)/Pandoc\'); rmarkdown::render(\'../Filter\ Tool/report.Rmd\')\""' os.system(cmd) Before, I used to run the python script from cmd, giving it the arguments it needs and everything worked fine. The filtering done by python was correct, rmarkdown analyzed the logs and produced HTML reports. Now that I try running it from a PHP call I constantly get the following in apache_error.log: Error in loadNamespace(name): there is no package called 'rmarkdown' I have made sure that R uses the proper paths for libraries, stated the path in the top of the rmarkdown script. I made sure that what goes into exec() works by pasting it's value into cmd and it runs. Anything else I can try? EDIT: As requested here is the top of the markdown script: ```{r setup, include=FALSE} knitr::opts_chunk$set(echo = TRUE) ``` ```{r include=FALSE} library(XML) library(methods) library(readbulk) library(zoo) library(tidyr) library(stringr) library(data.table) library(ggplot2) library(plyr) library(plotly) library(IPtoCountry) library(rworldmap) library(knitr) library(rmarkdown) .…

http://stackoverflow.com/a/59140282
score: 0
answers question: http://stackoverflow.com/q/52107405
has body: Here is the easiest way I can share with you: # read the sheet file import pandas as pd sheets = pd.ExcelFile('sheet_filename.xlsx') # save each sheet to a dataframe df1 = pd.read_excel(sheets, 'Sheet1') df2 = pd.read_excel(sheets, 'Sheet2') Hope this helped you!
type: Answer

dialogflow-es
tag name: dialogflow-es
tags question: http://stackoverflow.com/q/52111792
tags question: http://stackoverflow.com/q/52060662
type: Tag

http://stackoverflow.com/comment/91094884
score: 3
comment on: http://stackoverflow.com/q/52065654
type: QuestionComment
type: Comment
has text: I wonder if the sign is being drawn, but outside of the extent of the map you're producing? This would make it appear that it wasn't being drawn. To quickly check this, you could replace the line `cartmap.set_extent([...])` with `cartmap.set_global()`. If the sign appears, but elsewhere on the map, then you'll need to transform the sign's `(x, y)` point value into your map's projection (a good place to do this would be in the method `add_point_icon`).

http://stackoverflow.com/comment/91043667
comment on: http://stackoverflow.com/a/52022974
type: Comment
has text: I have shown another example at the first paragraph as well. Using docker compose, right now I am serving one Django server via Nginx, but I can use the same instance to serve multiple servers(Multiple Django/Flask etc) as well. Personally I prefer that setup.
score: 0
type: AnswerComment

http://stackoverflow.com/comment/91190744
type: QuestionComment
comment on: http://stackoverflow.com/q/52109370
has text: (*Spyder maintainer here*) The pictures the OP was referring to were posted in our issues tracker, specifically [here](https://github.com/spyder-ide/spyder/issues/7778). We're trying to help him there.
score: 0
type: Comment

cassandra
tags question: http://stackoverflow.com/q/51996954
type: Tag
tag name: cassandra

http://stackoverflow.com/comment/91043025
has text: What do you mean by “use the import function” and “use the def function”? Neither of those are functions, they’re statements. And they do very different things: one makes a module and all of its globals available to your code; the other creates a new function.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52046016
score: 0

http://stackoverflow.com/q/52064512
tagged with: django
accepted answer: http://stackoverflow.com/a/52065671
tagged with: python
has answer: http://stackoverflow.com/a/52064687
has body: I am attempting to write a Field Serializer for my django API that passes null to a custom .to_internal_value method. My use case is for two datetime fields that make up a time range. I want a user of my API to be able to give me something along the lines of "start_dt": null in a PUT/POST/PATCH request and have my serializer translate that into datetime.datetime.min (or, in the case of end_dt, datetime.datetime.max). Here is what I have so far. I am able to get Object-&gt;JSON serialization to work well (translates datetime.min and datetime.max values to None) using the .to_representation(self, value) method - however it does not seem to call .to_internal_value(self, value) when converting from null-&gt;None - and instead passes None through to the rest of my logic whenever one of the two fields is given as null. import pytz from datetime import datetime UTC = pytz.timezone("UTC") max_dt = UTC.localize(datetime.max) min_dt = UTC.localize(datetime.min) class CustomDateTimeField(serializers.Field): def __init__(self, *args, **kwargs): self.datetime_field = fields.DateTimeField() self.infinity_direction = kwargs.pop('infinity_direction', None) if not (self.infinity_direction == '+' or self.infinity_direction == '-'): raise AssertionError("Expected CustomDateTimeField to be created with `infinity_direction` equal to either '+' or '-'") super().__init__(*args, **kwargs) def to_representation(self, value): """ Represent both MAX and MIN times as None/'null' Else return a normal datetime string """ if value == min_dt or value == max_dt: return None return self.datetime_field.to_representation(value) def to_internal_value(self, value): """ Translate None/'null' values to either MAX or MIN - depending on self.infinity_direction Else return a normal datetime object """ if value == None: return max_dt if self.infinity_direction == '+' else min_dt return self.datetime_field.to_internal_value(value) In my Model's serializer I have these fields in use like... class TimeRangeSeria…
has comment: http://stackoverflow.com/comment/91079601
has title: Django Rest Framework - call serializer.to_internal_value on a null value
score: 2
downvote count: 0
tagged with: django-rest-framework
has answer: http://stackoverflow.com/a/52065671
type: Question
type: AnsweredQuestion
tagged with: deserialization
favorite count: 0
has comment: http://stackoverflow.com/comment/91079742
tagged with: serialization
upvote count: 2
answer count: 2
possible better answer: http://stackoverflow.com/a/52064687

http://stackoverflow.com/comment/91150611
has text: Suggesting iteration is rarely a good approach when using `pandas`
type: AnswerComment
comment on: http://stackoverflow.com/a/52099622
score: 0
type: Comment

http://stackoverflow.com/comment/90865360
has text: You should *always* post the entire traceback and error message when asking questions about exceptions.
type: QuestionComment
type: Comment
score: 1
comment on: http://stackoverflow.com/q/51957374

http://stackoverflow.com/a/52050137
has body: You're dumping the JSON twice, which causes quotes to be escaped on the second dump. (After the first json.dumps the result is only a string, so you're just dumping a string instead of a dict again) import json # result = json.dumps(result) with open('result.json', 'w') as fp: json.dump(result, fp, indent=4) Or remove the second dump: import json result = json.dumps(result) with open('result.json', 'w') as fp: # json.dump(result, fp, indent=4) print(result, file=fp)
answers question: http://stackoverflow.com/q/52050108
has comment: http://stackoverflow.com/comment/98529375
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52050108
has comment: http://stackoverflow.com/comment/98528761
type: Answer
score: 19
upvote count: 19

http://stackoverflow.com/comment/91137028
comment on: http://stackoverflow.com/a/52093384
score: 0
type: AnswerComment
type: Comment
has text: Yes I'm sure, I tested it :)

http://stackoverflow.com/a/52068490
has comment: http://stackoverflow.com/comment/91087311
downvote count: 0
upvote count: 2
has comment: http://stackoverflow.com/comment/91087075
has comment: http://stackoverflow.com/comment/91088219
answers question: http://stackoverflow.com/q/52068482
has body: That means your //DestPath doesn't exist in first place, so file.zip can't be created there. Are those double slashes intentional?
type: Answer
has comment: http://stackoverflow.com/comment/91087036
score: 2

http://stackoverflow.com/a/53271054
upvote count: 1
has comment: http://stackoverflow.com/comment/93680594
score: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/93719400
type: Answer
has body: I send messages to Google Chat based on this gist. Since upgrading to Django 2.1, this stopped working even though the config stayed the same (much like your situation). While I'm not entirely sure what is happening, I found that if I changed my server's DEBUG to True and changed the filter on my 'chat_admins' logging handler to 'require_debug_true' it would work again. Of course this is not ideal as it's in Production, where DEBUG is 'False', that I need this to work. I ended up rewriting my LOGGING variable in settings.py, trying to get a minimal configuration and following the documenation for Django Logging. and it is now working in Production with DEBUG to 'True'. LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'django.server': { '()': 'django.utils.log.ServerFormatter', 'format': '[{server_time}] {message}', 'style': '{', }, }, 'filters': { 'require_debug_true': { '()': 'django.utils.log.RequireDebugTrue', }, 'require_debug_false': { '()': 'django.utils.log.RequireDebugFalse', }, }, 'handlers': { 'console': { 'level': 'INFO', 'filters': ['require_debug_true'], 'class': 'logging.StreamHandler', }, 'django.server': { 'level': 'INFO', 'class': 'logging.StreamHandler', 'formatter': 'django.server', }, 'chat_admins': { 'level': 'DEBUG', 'filters': ['require_debug_false'], 'class': 'myapp.chat_logger.ChatExceptionHandler', }, }, 'loggers': { 'django': { 'handlers': ['console', 'chat_admins'], 'level': 'INFO', 'propagate': True, }, 'django.server': { 'handlers': ['django.server'], 'level': 'INFO', 'propagate': False, }, }, } There are only two main differences between the original settings and my re-write: 1) the 'mail_admins' handler is gone and 2) 'propagate' in the django logger is now set to 'True'. I tried manually applying those settings to the prior config as well but it still doesn't work.
answers question: http://stackoverflow.com/q/51984404

http://stackoverflow.com/a/52031939
has comment: http://stackoverflow.com/comment/91014349
type: Answer
downvote count: 0
score: 1
accepted answer of: http://stackoverflow.com/q/52031829
answers question: http://stackoverflow.com/q/52031829
has body: You can use df.columns to get all column names and then create sub-dataframes: outdflist =[] # for each column beyond first: for col in oridf.columns[1:]: # create a subdf with desired columns: subdf = oridf'GeneID',col # append subdf to list of df: outdflist.append(subdf) # to view all dataframes created: for df in outdflist: print(df) Output: GeneID A 0 1 0.3 1 2 0.5 2 3 0.4 3 4 0.9 4 5 0.1 GeneID B 0 1 0.2 1 2 0.3 2 3 0.1 3 4 0.7 4 5 0.4 GeneID C 0 1 0.6 1 2 0.1 2 3 0.5 3 4 0.1 4 5 0.7 GeneID D 0 1 0.4 1 2 0.2 2 3 0.1 3 4 0.6 4 5 0.2 GeneID E 0 1 0.8 1 2 0.6 2 3 0.3 3 4 0.7 4 5 0.5 Above for loop can also be written more simply as list comprehension: outdflist = [ oridf'GeneID', col for col in oridf.columns[1:] ]
upvote count: 1
type: AcceptedAnswer

http://stackoverflow.com/comment/91018523
type: Comment
has text: How So? OP says he wants to convert my date into >>DateTime object .
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52034198

http://stackoverflow.com/q/52017976
has comment: http://stackoverflow.com/comment/90986176
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90986558
has title: How to - Write a program to check if a number has at least one equal adjacent number
type: Question
accepted answer: http://stackoverflow.com/a/52018180
has answer: http://stackoverflow.com/a/52018057
has body: I already did some research but i cant find the solution or help for my doubt. Im doing coursera python course, and i have an optional exercise that i not figuring out the solution. So the exercise is a kinda simple, "Write a program that receave a number and check if the receave number has, at least, one equal adjacent number." EX: 12256 (adjacent number), 123456 (doesnt have adjacent number) Only using while loop and/or if statment. So list and lens aren't allowed to use. I did like this: x = int(input("Number: ")) while (x != 0): resto = x % 10 x = (x - resto) //10 if resto == resto: print("yes") else: print("no") The question, here, is that i not figuring out how to evaluate my if statement to false. Thanks in advance for any help =)
score: 0
answer count: 3
has comment: http://stackoverflow.com/comment/90986206
tagged with: python-3.x
has answer: http://stackoverflow.com/a/52018055
tagged with: python
has answer: http://stackoverflow.com/a/52018180
has comment: http://stackoverflow.com/comment/90986450
possible better answer: http://stackoverflow.com/a/52018055

http://stackoverflow.com/q/52029805
has comment: http://stackoverflow.com/comment/91010143
tagged with: django
has comment: http://stackoverflow.com/comment/91010724
type: Question
score: 0
has title: Django Admin app's contents are not being displayed
has body: For some reason, The contents of the database containing the list of all the Projects is not being displayed on my Projects/Issues page for some reason. I recently added a feature to my software making it such a way that everytime I click on save in the Issues page, an email is sent to the Admin and the Person who is concerned. Ever since I added that feature, my Website stopped displaying the contents but it displays the Number of contents in my List. UPDATE the 1st entry on the Project page doesn't show up. the title of the table doesn't show up either. But when I add the 2nd entry, the 2nd entry shows up, but the 1st doesn't. Im using SQLite. Ill be using MySQL for production. In my Issues/Bugs table None of my entries show up, neither does the title of the table show up. Which means, I cant delete the entries or make any changes to the entires I have made so far. Could someone help me out? Here's my Models.py from django.db import models # Create your models here. from django.contrib.auth.models import User from django.db import models from django.core.mail import EmailMessage # Create your models here. class Project(models.Model): STATUS_CHOICE = ( ('Project Manager', 'Project Manager'), ('Technician', 'Technician'), ('Tester', 'Tester') ) STATUS_CHOICE_1 = ( ('Work Assigned', 'Work Assigned'), ('Work in Progress', 'Work in Progress'), ('Testing', 'Testing'), ('Completed', 'Completed') ) Project_Name = models.CharField(max_length=100) Project_Description = models.CharField(max_length=100) Admin_Name = models.ForeignKey(User, on_delete=models.CASCADE, related_name='User.Admin_Name_users+') Admin_Mail_ID = models.EmailField(max_length=50) Project_Manager_1 = models.ForeignKey(User, on_delete=models.CASCADE, related_name='User.Project_Manager_1_users+') Project_Manager_1_Mail_ID = models.EmailField(max_length=50) Project_Manager_2 = models.ForeignKey(User, on_delete=models.CASCADE, related_name='User.Project_Manager_2_users+', blank=True, null=True) Project_Manage…
tagged with: python
answer count: 0
type: UnansweredQuestion

http://stackoverflow.com/a/52059880
has body: You could make list and favsub sets instead, and the take the length of the intersection. NOTE: This will only work if all the phrases in list and favsub are single words, without a space.
downvote count: 0
type: Answer
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/91070037
answers question: http://stackoverflow.com/q/52059772

http://stackoverflow.com/comment/90933005
has text: Yes some of those 'text x' entries are blanks now that you mention it. It may give a pivot a hard time. Never seen the columns=[f"Col {i}... construction before, thank you it works!
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51991531
type: Comment

size
type: Tag
tag name: size
tags question: http://stackoverflow.com/q/52058971

http://stackoverflow.com/comment/90910918
type: QuestionComment
has text: First you need to learn some basic programming in python. There are plenty of tutorials online - I can recommend codeacademy for example. After you learn the basics, have a look at the 'pandas' package for python - it is designed to do what you want and it is very simple to use. There are plenty of tutorials for pandas as well.
type: Comment
score: 3
comment on: http://stackoverflow.com/q/51980540

http://stackoverflow.com/comment/91031190
comment on: http://stackoverflow.com/q/52040389
has text: there is no logical or used in your c++ code, there is only bitwise or. So to do the same in python, you should use bitwise or there as well (which is `|`, just like in C++), not logical.
type: Comment
type: QuestionComment
score: 2

http://stackoverflow.com/comment/90995617
type: Comment
comment on: http://stackoverflow.com/a/51973738
has text: The result of FileSystems.match(patter) contains a metadata_list (List of FileMetadata). You can iterate over the list and extract the path as string. And output the Tuple of (string path, True) to a groupBy. In the MapTask after GroupBy, you can get the tuple and extract the file path. You can then read the path using FileSystem.read. Another recommendation is that instead of using GcsFileSystem directly use FileSystems ( https://github.com/apache/beam/blob/master/sdks/python/apache_beam/io/filesystems.py ).
type: AnswerComment
score: 0

http://stackoverflow.com/a/51991091
answers question: http://stackoverflow.com/q/51982806
upvote count: 21
has comment: http://stackoverflow.com/comment/118189020
score: 21
has body: From https://github.com/Rapptz/discord.py/issues/390: It's &lt;:emoji_name:emoji_id&gt; for custom emojis. You can also find the discord.Emoji instance through Server.emojis and then cast it to str.
downvote count: 0
type: Answer

http://stackoverflow.com/comment/91154434
score: 0
has text: Do the code and the question title have any relation?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52101782

http://stackoverflow.com/q/51990726
has comment: http://stackoverflow.com/comment/90931802
has body: I am having a lot of problems to understand how to create a tkinter-gui for an sqlite query. Idea: I have one table with 1.7m+ rows. My queries are divided in three areas: I. queries with 5 variables - II. query with one variable - III. same as II. (After the output in pandas, I can create and open an xlsx-File, there is no problem.) import tkinter as tk import numpy as np import pandas as pd import sqlite3 class MyApp: def __init__(self): root = Tk() root.title('7s_final_004') frame = Frame(root) frame.pack() self.fields = {} l = Label(frame, text="Description:") l.grid(row=1, column=0) self.fields['description'] = Entry(frame) self.fields['description'].grid(row=1, column=1)` ### self.fields go on for all 5 categories(description2, client, etc...) `l = Label(frame, text="Num:") l.grid(pady=10, row=19, column=0) #self.fields['num'] = Entry(frame) #self.fields['num'].grid(row=19, column=1) self.numentry = Entry(frame) self.numentry.grid(pady=10, row=19, column=1) ## 2/3 buttons plus one exemplary def: btn_generalsearch = Button(frame, text="Search above", command=self.do_generalsearch) btn_generalsearch.grid(row=10, column=0) btn_numsearch = Button(frame, text="Search Num", command=self.do_numsearch) btn_numsearch.grid(row=20, column=0) def do_numsearch(self): conn = sqlite3.connect("data.db") #with conn: cursor = conn.cursor() num = """SELECT Client, Ship, Num, Product, Description, Units, Price, Supplier, Cost, 'Date', Margin, DN FROM table2 WHERE Num = ? ORDER BY Date DESC;""" #print(num) #numargs = self.fields['num'].get() numargs = numentry() df = pd.read_sql_query(num, conn, param=(numentry)) print(df.head(5)) if __name__=="__main__": MyApp() Note: I left my messed up do_numsearch as it is, so you might see what I tried already. I am stuck with this since two weeks. I would like to add a radiobutton-widget and checkboxes too, I would be very glad if someone could point me in a direction how I can make this piece work.
score: 0
upvote count: 1
tagged with: sqlite
downvote count: 1
favorite count: 0
tagged with: tkinter
answer count: 0
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/90931263
has title: Tkinter Entry + Python + Sqlite with params
type: Question

http://stackoverflow.com/comment/91082907
type: QuestionComment
has text: What exactly does "I not working" mean? Incorrect output? Exception thrown?
comment on: http://stackoverflow.com/q/52062156
score: 0
type: Comment

single-sign-on
tags question: http://stackoverflow.com/q/52034273
type: Tag
tag name: single-sign-on

http://stackoverflow.com/q/52031875
has comment: http://stackoverflow.com/comment/91054405
upvote count: 1
has comment: http://stackoverflow.com/comment/91052606
duplicate of: http://stackoverflow.com/q/45131528
score: 1
linked to: http://stackoverflow.com/q/45131528
tagged with: sqlalchemy
type: Question
has body: Python 3.6 and sqlalchemy 1.2.10 result=db_query(db_session.query(orm_model).filter(orm_model.id==1,orm_model.time.between(1,2)).all()) if I return this result directly in a restful api: return [x.to_json() for x in result] Front end got empty content, and I found x.__dict__ has only one key "_sa_instance_state". The "to_json()" is orm_model's function: def to_json(self): jsonobj = {} for x in self.__dict__: jsonobj[x] = self.__dict__[x] if "_sa_instance_state" in jsonobj.keys(): del jsonobj['_sa_instance_state'] return jsonobj If I print it before return, every thing is ok, front end got the right content. print(result) return [x.to_json() for x in result] And if I remove the "all()": result=db_query(db_session.query(orm_model).filter(orm_model.id==1,orm_model.time.between(1,2))) every thing is ok, without print before return, front end got the right content. The Model is: Base = declarative_base() class orm_model(Base): __tablename__ = 'orm_model' id = Column(INTEGER(11), primary_key=True) user = Column(INTEGER(11)) ... def to_json(self): ... def __repr__(self): return '&lt;orm_model %s&gt;' % self.id and I define the db_query is always with commit and rollback： def db_query(sql=None): try: db_session.commit() except: db_session.rollback() return False else: return sql My English is poor, sorry.
has title: python sqlalchemy query all() result.__dict__ empty without print
linked to: http://stackoverflow.com/q/1078383
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/91046155
tagged with: python
answer count: 0
has comment: http://stackoverflow.com/comment/91051610
type: UnansweredQuestion

http://stackoverflow.com/q/51962038
answer count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/90874266
tagged with: continue
has body: I've one inner loop and one outer (records in database). The outer loop (json) make a filter based of a couple of fields (eg : begin/end => 0 : 0.5 >>> IDs 114 to 159). The Table : ID begin end status FK1_field FK2_field FK3_field FK4_field FK5_field report_id 114 0 0.5 1 NULL 13 8 142 44 1 115 0 0.5 1 NULL 13 8 61 45 1 158 0 0.5 1 NULL 13 8 142 45 1 159 0 0.5 1 NULL 13 8 61 44 1 116 0.5 1.5 1 NULL 13 8 142 45 1 117 0.5 1.5 1 NULL 13 8 131 45 1 118 1.5 2.5 1 NULL 13 8 142 45 1 The result is looping over the inner loop (eg : 4 records/lines (*) ). But, when I exit the inner loop, I must loop over the outer loop 4 times (*) to get the ID 116 (and filter begin/end) => 0.5 : 1.5. Indeed, I can loop over only the inner loop and test with an 'if' the same couple times. But I think the filtering is more elegant. For now, I think looping when exit the inner loop is stupid. The code : highways = tools_cronjob.getAPI(API_URL + action, headers) for highway in highways: print('&gt;&gt;&gt;&gt;&gt; Highway : %s ' % highway['name']) # all the prpk, same values like the table prpk_by_highway = tools_cronjob.getAPI(API_URL + actions_api['prpk_by_highway'] + "%s" % (highway['id']), headers) # get all prpk by highway for prpk in prpk_by_highway: filtered_by_begin_end = [pr_pk for pr_pk in prpk_by_highway if pr_pk['begin'] == prpk['begin']] # each couple of prpk 'begin' and 'end' for filter_prpk in filtered_prpk_by_begin_end: # some stuff print (filter_prpk) # when I exit, for eg, I must continue looping (prpk in prpk_by_highway) starting the couple begin/end : 0.5 : 1.5 So the first loop is 4 records, the second is 2 and the third just 1. The Json : [ { 'end':0.5, 'begin':0.0, 'status':'1', 'department':{ 'number':'13', 'id':13, 'name':'Bouches-du-Rhône' }, 'meteozone':{ 'id':44, 'name':'137' }, 'commune':None, 'massif':{ 'meteozones':[ { 'id':44, 'name':'137' }, { 'id':45, 'name':'138' }, { 'id':104, 'name':'831' }, { 'id':105, 'name':'832' } ], 'id':142, 'name':'Sainte-baume' } }, …
favorite count: 0
has comment: http://stackoverflow.com/comment/90876005
has comment: http://stackoverflow.com/comment/90874903
has title: Continue outer-loop several times, when exit inner-loop (Python)
tagged with: break
tagged with: python
has comment: http://stackoverflow.com/comment/90875478
has comment: http://stackoverflow.com/comment/90876455
type: AnsweredQuestion
upvote count: 0
has answer: http://stackoverflow.com/a/51962891
accepted answer: http://stackoverflow.com/a/51962891
type: Question
score: -1
tagged with: for-loop
has comment: http://stackoverflow.com/comment/90875790
has comment: http://stackoverflow.com/comment/90876111

http://stackoverflow.com/comment/91114799
comment on: http://stackoverflow.com/a/52081838
has text: @jwodder Interesting! I had no idea `\8` and `\9` weren't escape sequences.
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/q/52064097
tagged with: python-3.x
type: UnansweredQuestion
tagged with: irc
tagged with: python
has title: Troubles Sending Message in IRC using python
answer count: 0
linked to: http://stackoverflow.com/q/51484971
has body: I am trying to create an irc bot using python, but I'm getting an error. When I try to check for a message sent, the PRIVMSG doesn't send a message to the chat, but the test print statement outputs. If I just try to send a message when anything is received it sends the message. I commented in the code where this happens. This is my first time trying to do this, so sorry if I'm a bit inexperienced using python sockets. #connect.py #connects to twitch irc and presents a class to b import cfg import socket import time def ban(sock, user): chat(sock, ".ban {}".format(user)) def timeout(sock, user, secs=600): chat(sock, ".timeout {}".format(user, secs)) # network functions go here s = socket.socket() s.connect((cfg.HOST, cfg.PORT)) s.send("PASS {}\r\n".format(cfg.PASS).encode("utf-8")) s.send("NICK {}\r\n".format(cfg.NICK).encode("utf-8")) s.send("JOIN {}\r\n".format(cfg.CHAN).encode("utf-8")) while True: time.sleep(0.1) response = s.recv(1024).decode("utf-8") print(response) if response == "PING :tmi.twitch.tv\r\n": s.send("PONG :tmi.twitch.tv\r\n".encode("utf-8")) elif "hi" in response: #prints Condition Worked but doesn't send message print("Condition Worked") s.send(("PRIVMSG #garrett_the_savage :hello"+"\r\n").encode('utf-8')) else #sends a message when anything is received from the socket s.send(("PRIVMSG #garrett_the_savage :hello"+"\r\n").encode('utf-8')) EDIT: I have a separate file called cfg.py that houses some variables for connecting.
has comment: http://stackoverflow.com/comment/91100501
type: Question
score: 0
has comment: http://stackoverflow.com/comment/92953171
tagged with: twitch
tagged with: twitch-api

http://stackoverflow.com/comment/91113206
comment on: http://stackoverflow.com/q/52043671
score: 1
type: Comment
type: QuestionComment
has text: I tried to change order, but didn't work

http://stackoverflow.com/a/52010961
has comment: http://stackoverflow.com/comment/90975035
accepted answer of: http://stackoverflow.com/q/52009769
answers question: http://stackoverflow.com/q/52009769
score: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/90994544
has body: I can't comment, as I don't have enough reputation, but do you have any error messages from the other computer you're trying to run this batch file on? According to this section of the pyinstaller documentation, you will need to send the recipient of your executable the "build" directory. This is because build contains all of the dependencies in your script. To quote the section about importing in one folder (NOTE: don't worry, I see the onefile option you set. This is just the section where the docs allude to the build directory you're inquiring about): Another advantage of a one-folder bundle is that when you change your code, as long as it imports exactly the same set of dependencies, you could send out only the updated myscript executable. That is typically much smaller than the entire folder. (If you change the script so that it imports more or different dependencies, or if the dependencies are upgraded, you must redistribute the whole bundle.) I think -F still creates a /build directory (so you can still track dependencies). Iwould share that out, as it would be shared with the one folder option as well. Pyinstaller knows to look for Tkinter (also in doc linked above), so at least you don't have to worry about that part. When you use onefile, the /dist directory should be empty, or at least it is when I create executables. Try out the one folder method and send that folder out to whatever computers you need to. Let me know if this helps. TLDR; Yes, share out the build file. It contains all of your dependencies. The dist file shouldn't contain anything for the "-F" option.
has comment: http://stackoverflow.com/comment/90982733
type: Answer
has comment: http://stackoverflow.com/comment/90982774

http://stackoverflow.com/comment/90871905
has text: I honestly don't even know if I need a whole library or there are existing things I can use. The answer in the post I referenced in my question was only 3 lines of code, but that doesn't seem valid anymore. So I was hoping someone could give me a valid alternative
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51960766

http://stackoverflow.com/q/52034043
tagged with: python
has comment: http://stackoverflow.com/comment/91026551
has comment: http://stackoverflow.com/comment/91019069
tagged with: linear-regression
type: Question
has answer: http://stackoverflow.com/a/52034450
has comment: http://stackoverflow.com/comment/91019356
score: 0
tagged with: pandas
answer count: 1
has title: python - using linear regression to predict missing values
has body: I have data from 2012-2014 with some missing months in 2014. I would like to predict those months using a linear regression model trained on the 2012/2013 data. 2014 is missing June-August and has '' as its value so i clean it up using the following code, I also change 2012,2013 to have the same shape by cutting 20 data: data2014NaN=data2014['mob'].replace(' ', np.nan) data2014CleanNaN = data2014NaN[data2014NaN.notnull()] data2012[0:300] data2013[0:300] Then I train a linear regression model using both years as a training set. X = pd.concat([data2012[0:300], data2013[0:300]], axis=1, join='inner') y = data2014CleanNaN .values y = y.reshape(-1,1) from sklearn.model_selection import train_test_split # Split into 75% train and 25% test X_train, X_test, y_train, y_test = train_test_split(X, y, train_size=0.75, random_state=4) lm = LinearRegression() lm.fit(X_train,y_train) score = lm.score(X_test,y_test) print("The prediction score on the test data is {:.2f}%".format(score*100)) However the result I got is an abysmal 4.65% and I'm not too sure on how to approach this problem, I assume I did something wrong when I cut down the data for 2012 and 2013 Here I attached the data (this is just dummy data): 2014: date value 29/01/2014 10 30/01/2014 20 31/01/2014 15 1/02/2014 ' ' 2012: date value 29/01/2014 15 30/01/2014 18 31/01/2014 19 1/02/2014 50 I'm only using the value data, not sure if I'm in the right direction Best Regards
has comment: http://stackoverflow.com/comment/91019058
tagged with: scikit-learn
has comment: http://stackoverflow.com/comment/91019207
favorite count: 0
upvote count: 2
type: UnansweredQuestion
tagged with: predict
downvote count: 2

http://stackoverflow.com/q/52014550
answer count: 3
downvote count: 0
linked to: http://stackoverflow.com/q/41177803
favorite count: 0
accepted answer: http://stackoverflow.com/a/52016247
tagged with: python
has title: Solve a nonlinear ODE system for the Frenet frame
has body: I have checked python non linear ODE with 2 variables , which is not my case. Maybe my case is not called as nonlinear ODE, correct me please. The question isFrenet Frame actually, in which there are 3 vectors T(s), N(s) and B(s); the parameter s>=0. And there are 2 scalar with known math formula expression t(s) and k(s). I have the initial value T(0), N(0) and B(0). diff(T(s), s) = k(s)*N(s) diff(N(s), s) = -k(s)*T(s) + t(s)*B(s) diff(B(s), s) = -t(s)*N(s) Then how can I get T(s), N(s) and B(s) numerically or symbolically? I have checked scipy.integrate.ode but I don't know how to pass k(s)*N(s) into its first parameter at all def model (z, tspan): T = z[0] N = z[1] B = z[2] dTds = k(s) * N # how to express function k(s)? dNds = -k(s) * T + t(s) * B dBds = -t(s)* N return [dTds, dNds, dBds] z = scipy.integrate.ode(model, [T0, N0, B0]
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52033713
tagged with: differential-equations
score: 1
upvote count: 1
tagged with: scipy
has answer: http://stackoverflow.com/a/52022694
type: Question
has answer: http://stackoverflow.com/a/52016247
possible better answer: http://stackoverflow.com/a/52022694

http://stackoverflow.com/q/52056032
favorite count: 0
has comment: http://stackoverflow.com/comment/91064356
has body: I am trying to get the soap response and read few tags and then put the key and values inside a dictionary. Better would be if I could use the response generated directly and preform regd operations to it. But since I was not able to do that, I tried storing the response in an xml file and then using that for operations. My problem is that the response generated is in a raw form. How to resolve this. Example: &amp;lt;medical:totEeCnt val=&amp;quot;2&amp;quot; /&amp;gt;&amp;#xd; &amp;lt;medical:totMbrCnt val=&amp;quot;2&amp;quot; /&amp;gt;&amp;#xd; &amp;lt;medical:totDepCnt val=&amp;quot;0&amp;quot; /&amp;gt;&amp;#xd; def soapTest(): request = """&lt;soapenv:Envelope....... auth = HTTPBasicAuth('', '') headers = {'content-type': 'application/soap+xml', 'SOAPAction': "", 'Host': 'bfx-b2b....com'} url = "https://bfx-b2b....com/B2BWEB/services/IProductPort" response = requests.post(url, data=request, headers=headers, auth=auth, verify=True) # Open local file fd = os.open('planRates.xml', os.O_RDWR|os.O_CREAT) # Convert response object into string response_str = str(response.content) # Write response to the file os.write(fd, response_str) # Close the file os.close(fd) tree = ET.parse('planRates.xml') root = tree.getroot() dict = {} print root for plan in root.findall('.//{http://services.b2b.../types/rates/dental}dentPln'): # type: object plan_id = plan.get('cd') print plan print plan_id for rtGroup in plan.findall('.//{http://services.b2b....com/types/rates/dental}censRtGrp'): #print rtGroup for amt in rtGroup.findall('.//{http://services.b2b....com/types/rates/dental}totAnnPrem'): # print amt print amt.get('val') amount = amt.get('val') dict[plan_id] = amount print dict Update-: I did few things, what I am not able to understand is that , using this, the operations further are working, tree = ET.parse('data/planRates.xml') root = tree.getroot() dict = {} print tree print root for plan in root.findall(.. output - &lt;xml.etree.ElementTree.ElementTree object at 0x100d7b9…
tagged with: python
tagged with: request
has comment: http://stackoverflow.com/comment/91064082
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91062927
has title: Getting the xml soap response instead of raw data
accepted answer: http://stackoverflow.com/a/52057276
upvote count: 1
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/91062465
has comment: http://stackoverflow.com/comment/91063783
score: 0
answer count: 1
tagged with: elementtree
has answer: http://stackoverflow.com/a/52057276

http://stackoverflow.com/q/51971647
favorite count: 0
tagged with: argparse
tagged with: python
has comment: http://stackoverflow.com/comment/90893935
has comment: http://stackoverflow.com/comment/90896586
has answer: http://stackoverflow.com/a/51975689
downvote count: 2
upvote count: 1
has comment: http://stackoverflow.com/comment/90894004
has comment: http://stackoverflow.com/comment/90895298
type: Question
has comment: http://stackoverflow.com/comment/90898407
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90895535
has comment: http://stackoverflow.com/comment/90894815
score: -1
accepted answer: http://stackoverflow.com/a/51975689
has comment: http://stackoverflow.com/comment/90894765
has comment: http://stackoverflow.com/comment/90894897
has body: main(): parser = argparse.ArgumentParser(description="IVS code") parser.add_argument("--prod", help="Product to import config for") parser.add_argument("--wf", help="File to write results to") parser.add_argument("--ipf", help="IVS product family file") #not in use yet, might keep all ivs product family in same file args=parser.parse_args() print (args) dataDF,keepDF,rulesDF,family_list,level_list,price_override_dict = getInputDataStructures(args) ============================================================================= function def getInputDataStructures(args): #Create the price override dictionary reader = csv.reader(open(cfg[args.prod]["po"], 'r'), skipinitialspace=True) #reader = csv.reader(open(cfg[args.prod]["po"], 'r'), skipinitialspace=True) next(reader, None) # skip the headers price_override_dict = {} for row in reader: cd,cntry,price = row price_override_dict[cd+'|'+cntry] = price ======================================================================= YAML file -> Sets and Miscelineous: lvl: "ITEM_CODE,REGIONS,CLUSTERS,SUBCLUSTER,COUNTRY" kl: Keep.csv rs: rules.csv pf: "Sets and Misc" ps: "-" pg: Product_Family.csv dt: "Sets_Misc.rpt" po: "priceOverride.csv" ============================================================================= ERROR OUTPUT: 24]: runfile('.../Workspace/CodeFiles/volume_substitution_v3.py', wdir='.../Workspace/CodeFiles') Reloaded modules: config Namespace(ipf=None, prod=None, wf=None) Traceback (most recent call last): File "&lt;ipython-input-24-6b4c2ae644d5&gt;", line 1, in &lt;module&gt; runfile('.../Workspace/CodeFiles/volume_substitution_v3.py', wdir=.../CodeFiles') File ".../Workspace/CodeFiles/volume_substitution_v3.py", line 447, in &lt;module&gt; main() File ".../Workspace/CodeFiles/volume_substitution_v3.py", line 130, in main dataDF,keepDF,rulesDF,family_list,level_list,price_override_dict = getInputDataStructures(args) File ".../CodeFiles/volume_substitution_v3.py", line 21, in getInputDataStructures reader = csv.rea…
has title: KeyError: None + argparse python 3.xx
has comment: http://stackoverflow.com/comment/90894232
tagged with: yaml
has comment: http://stackoverflow.com/comment/90895112
answer count: 1

http://stackoverflow.com/q/51991406
score: 2
type: AnsweredQuestion
downvote count: 0
has body: I get a weird line through my optionmenu and I have no idea why. Any tips? Just test code, but I have no idea where that line comes from. I've tried changing the size of the menu to fix it and tried to find the error but I just can't find it. It's not "game-breaking" but it's still kinda annoying that I can't get rid of it. from tkinter import * root = Tk() root.state("zoomed") root.title("XP-dot GUI") root.configure(background='black') mainframe = Frame(root, width=50) mainframe.grid(row=0, column=0, sticky=(N,W,E,S)) mainframe.columnconfigure(0, weight = 1) mainframe.rowconfigure(0, weight = 1) buttonframe = Frame(root) buttonframe.grid(row=3, column=0, sticky=(N,W)) buttonframe.configure(background='blue') tkvar = StringVar(root) tkvar.set('1 row') choices = ['1 row','2 rows','Still frame','Animation', 'diy'] r=0 c=0 theLabel = Label(root, text="") theLabel.grid(row=r,column=c) dropDown = OptionMenu(mainframe, tkvar, *choices) Label(mainframe, text="Options").grid(row=r, column=c) dropDown.grid(row=r, column=c+1, sticky=(W,E)) dropDown.config(width=14) def preview(): print ("value is", tkvar.get()) button = Button(buttonframe, text="Preview", command=preview) button.grid(row=5,column=0) def random(): print ("value is", tkvar.get()) button = Button(buttonframe, text="Randomize", command=random) button.grid(row=5,column=1) def update(): print ("value is", tkvar.get()) button = Button(buttonframe, text="Update", command=update) button.grid(row=5,column=2) root.mainloop()
type: Question
upvote count: 2
tagged with: drop-down-menu
has answer: http://stackoverflow.com/a/51993257
accepted answer: http://stackoverflow.com/a/51993257
answer count: 1
has title: White line through optionmenu
favorite count: 0
tagged with: tkinter
tagged with: python

http://stackoverflow.com/q/52047340
tagged with: python-multiprocessing
has title: Python: How to parallelize functions used in nested for loops with many function inputs?
score: 0
has comment: http://stackoverflow.com/comment/91337323
answer count: 1
tagged with: python-multithreading
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91045678
has body: I am looking to speed up a slow running loop, but do not think I am going at this with the best approach. I would like to parallelize some code which runs a function which I have written and am having some trouble trying to figure out exactly how to formulate the input parameters when using python's multiprocessing module. The code I have is essentially of the following form: a = some_value b = some_value c = some_value for i in range(1,101): for j in range(1,101): b = np.array([i*0.001,j*0.001]).reshape((2,1)) (A,B,C,D) = function(a,b,c,d) So my function itself takes on a variety of parameters but for this particular use I need to vary only one variable (which is an array of two values) and create a grid of values. Also, all other inputs are integers. I am familiar with very simple examples of parallelizing such loops by using a pool of workers through the following example code: pool = mp.Pool(processes=4) input_parameters = *list of iterables for multiprocessing* result = pool.map(paramest.parameter_estimate_ND, input_parameters) where the list of iterables is created using the itertools module. Since I am changing only one input variable of the function and all others are declared before I am having troubles structuring such input parameters. So what I would really like is to use multiprocessing to run different inputs at the same time to speed up the execution of the for loops. My question then being, how would one structure the use of multiprocessing to parallelize code that runs on a function while only changing inputs of specific variables? Am I approaching this in the best manner? Is there a better way to do such a thing? Thank you!
tagged with: multiprocessing
type: Question
has answer: http://stackoverflow.com/a/52047550
accepted answer: http://stackoverflow.com/a/52047550
has comment: http://stackoverflow.com/comment/91302513
tagged with: nested-loops

http://stackoverflow.com/comment/90958889
comment on: http://stackoverflow.com/q/52004719
has text: what is that ??
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/q/52013260
has body: I have more of a background with data science libraries or calling methods and attributes from classes. I am experimenting with manipulating magic methods. I am having a difficult time getting bool types and returning their opposites. I did something with str and datetime objects that worked but can't seem to to the same with __cmp__, __lt__, __eq__ or `gt'. Here is my code: class Opposite: def __cmp__(self, other): if other.__class__.__name__ == 'bool': return other def __lt__(self, other): if other.__class__.__name__ == 'bool': return other def __eq__(self, other): if other.__class__.__name__ == 'bool': return other def __gt__(self, other): if other.__class__.__name__ == 'bool': return other if __name__=="__main__": """ test class Compare """ a = 1 b = 1 c = a &lt; b d = a &gt; b e = a == b print("Results:\na\t{}\nb\t{}\nc\t{}\nd\t{}\ne\t{}\n".format(a,b,c,d,e)) print("\nType:\na-type\t{}\nb-type\t{}\nc-type\t{}\nd-type\t{}\ne-type\t{}\n" .format(type(a),type(b),type(c),type(d),type(e))) This prints the following: Results: a 1 b 1 c False d False e True Type: a-type &lt;class 'int'&gt; b-type &lt;class 'int'&gt; c-type &lt;class 'bool'&gt; d-type &lt;class 'bool'&gt; e-type &lt;class 'bool'&gt; As you can see, the results are the same as not using the class at all. I added an __init__ method to print using Opposite and it only prints that if I instantiate the object with something like a = Opposite(). I would like to enter something like a &gt; b, a &lt; b, or a == b, and return the opposite boolean value, True, or False, as an exercise. I tried several things such as placing the methods under the __init__ method I created, which didn't work either. I read on this and still don't quite understand how to do this with booleans, integers and floats for that matter. The way the methods are above is how I was able to turn datetime objects into strings with __add__, __radd__ and __rsub__ methods. Thank you for your help. EDIT Thanks to your help, I have a better underst…
has comment: http://stackoverflow.com/comment/90977458
has answer: http://stackoverflow.com/a/52013281
tagged with: class
type: AnsweredQuestion
upvote count: 0
has comment: http://stackoverflow.com/comment/90977315
favorite count: 0
accepted answer: http://stackoverflow.com/a/52013281
has title: Manipulating Python Magic Methods
type: Question
has comment: http://stackoverflow.com/comment/90977576
has comment: http://stackoverflow.com/comment/91159839
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/90977312
tagged with: methods
answer count: 1
downvote count: 1

http://stackoverflow.com/a/52031095
has body: You have to convert the graph to an undirected graph the calculate the size. NetworkX does not have a function that does this in one shot like snap does. networkx_Graph.to_undirected().size()
answers question: http://stackoverflow.com/q/52030344
type: Answer
has comment: http://stackoverflow.com/comment/91014720
score: 0

http://stackoverflow.com/comment/91055010
has text: He wants the inverse problem of `as_strided`
comment on: http://stackoverflow.com/q/52044113
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/52012793
downvote count: 0
has title: Variable when called outside of an on_message function is not able to be referenced inside the function
type: Question
upvote count: 2
tagged with: discord.py
has answer: http://stackoverflow.com/a/52013117
accepted answer: http://stackoverflow.com/a/52013117
answer count: 1
has body: I am trying to create a code called "saynum" with a parameter of amount(which is a natural number.) The way the command is supposed to work is it counts the number of messages since you ran the command, and sends the number onto discord. I have a block though. When trying to run an async def on_message(message) (with @bot.event of course) and calling a variable outside of that, I am not able to reference the variable from outside the on_message function. Is there a workaround to this? This question will probably get downvoted. If there is not a workaround to this, then is it possible for that command to work? I have no idea how to approach it in another way. Here is the code I am using: import discord from discord.ext import commands import random import sys import traceback Client = discord.Client() client = commands.Bot(command_prefix='~', case_insensitive=True) client.remove_command("help") @client.command() async def saynum(ctx, amount): num = 0 if amount.isdigit(): if int(amount) &lt; 1: await ctx.send("Please put an integer greater than 1.") else: @client.event async def on_message(message): num += 1 await ctx.send(num) Oh, one last thing. My python version is 3.6.6 and I am using discord.py rewrite if you couldn't tell.
favorite count: 0
tagged with: discord
tagged with: python
score: 2
type: AnsweredQuestion

http://stackoverflow.com/comment/90935271
has text: Hey Thanks! But this code has removed the digits present in myDict.
type: Comment
comment on: http://stackoverflow.com/a/51992338
type: AnswerComment
score: 0

http://stackoverflow.com/comment/91057122
type: Comment
has text: It hasnt given me option to lets continue this discussion to chat. Is it okay, if i create another public room and invite you there ?
comment on: http://stackoverflow.com/a/52051933
type: AnswerComment
score: 0

http://stackoverflow.com/q/51963054
tagged with: admin
tagged with: model
has body: #models.py from django.db import models from django.contrib.auth.models import User CHOICES = (('1','Earned Leave'),('2','Casual Leave'),('3','Sick Leave'),('4','Paid Leave')) class Leave(models.Model): employee_ID = models.CharField(max_length = 20) name = models.CharField(max_length = 50) user = models.ForeignKey(User, on_delete = models.CASCADE, null =True) department = models.CharField(max_length = 50) designation = models.CharField(max_length = 50) type_of_leave = models.CharField(max_length = 15, choices = CHOICES) from_date = models.DateField(help_text = 'mm/dd/yy') to_date = models.DateField(help_text = 'mm/dd/yy') reporting_manager = models.CharField(max_length = 50, default = None, help_text = '0001_manager, 0002_manager') reason = models.CharField(max_length= 180) accepted = models.BooleanField(('accept'), default= False) rejected = models.BooleanField(('reject'), default = False) reason_reject = models.CharField(('reason for rejection'),max_length=50) // this didn't help me. def __str__(self): return self.name This is a leave request form, where only of the two fields (accepted, rejected) should be selected and if the field rejected field is not selected then the reason_reject should not be shown in the /admin panel. #forms.py from django import forms from lrequests import models class LeaveRequestForm(forms.ModelForm): class Meta: fields = ("name", "employee_ID", "department", "designation", "type_of_leave", "from_date", "to_date", "reporting_manager", "reason") model = models.Leave The user fills the form and submits it. So, now the admin has to either accept it or reject it. The reason_reject field should appear to the admin only after once he selects rejected field. This all should happen only at the admin side. #admin.py from django.contrib import admin from . import models @admin.register(models.Leave) class LeaveAdmin(admin.ModelAdmin): list_display = ["name"] #"employee_ID", "department", "designation", "type_of_leave", "from_date", "to_date", "r…
has comment: http://stackoverflow.com/comment/90876524
linked to: http://stackoverflow.com/q/51997403
tagged with: django
tagged with: python
has title: How to write code such that only one of the radio button should be selected in models with django.?
has answer: http://stackoverflow.com/a/52162739
accepted answer: http://stackoverflow.com/a/52162739
has answer: http://stackoverflow.com/a/51963384
type: AnsweredQuestion
tagged with: view
has comment: http://stackoverflow.com/comment/90876933
has comment: http://stackoverflow.com/comment/90877049
has comment: http://stackoverflow.com/comment/90876896
possible better answer: http://stackoverflow.com/a/51963384
type: Question
has comment: http://stackoverflow.com/comment/90876334
has comment: http://stackoverflow.com/comment/90876825
has comment: http://stackoverflow.com/comment/90877274
has comment: http://stackoverflow.com/comment/90876288
score: 0
answer count: 2

http://stackoverflow.com/q/52101829
tagged with: python
type: AnsweredQuestion
type: Question
has body: I have the DataFrame: df = np.DataFrame = {'Year' : [2010, 2011, 2012, 2013, 1922, 1923, 1924, 1925], 'ID' : ['A', 'A', 'A', 'A', 'B', 'B', 'B'], 'Data1' : [1, 2, 3, 4, 2, 3, 4], 'Data2' : [2, 2, 2, 2, 3, 3, 3]} df Year ID Data1 Data2 2010 A 1 2 2011 A 2 2 2012 A 3 2 2013 A 4 2 1922 B 2 3 1923 B 3 3 1924 B 4 3 I would like to sum up total Data1 and Data2 up for each ID so that each year gives the sum of all Data1 or Data2 up to that year. Ultimately, I would like my DataFrame to look like this: df Year ID Data1 Data2 2010 A 1 2 2011 A 3 4 2012 A 6 6 2013 A 10 8 1922 B 2 3 1923 B 5 6 1924 B 9 9 I have over 100k rows, so this needs to be done without iteration if possible.
answer count: 1
has comment: http://stackoverflow.com/comment/91154437
score: 0
tagged with: pandas
has answer: http://stackoverflow.com/a/52101934
accepted answer: http://stackoverflow.com/a/52101934
has title: Trying to sum up rows with Pandas in a somewhat complicated manner
linked to: http://stackoverflow.com/q/36901

http://stackoverflow.com/comment/91089444
comment on: http://stackoverflow.com/a/52068579
has text: Thanks @DYZ for your help. It was extremely useful. It now runs under a second.
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/90908569
score: 5
has text: Have you reassigned the `filter` keyword?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51979432

http://stackoverflow.com/a/52077700
score: 1
accepted answer of: http://stackoverflow.com/q/52077632
answers question: http://stackoverflow.com/q/52077632
has body: If by 'selected' you mean that the first one has the selected class, you can simply test for that: nosto_sku_tags = bs4.select('select[name="id"] option') for nosto_sku_tag in nosto_sku_tags: if 'selected' in nosto_sku_tag.get('class', ()): continue sku_size = nosto_sku_tag.get_text(strip=True) (There is really no need to use exception handling in this case, all tags have a get_text() method). Because the class attribute could be missing, you need to use .get('class', ()) to get an empty tuple instead in that case. Note that I used a different query to find the &lt;option&gt; elements you posted in the HTML. Your code prints the &lt;select&gt; element, as one big object, not the individual &lt;option&gt; elements under it. Rather than use a separate search for the &lt;select&gt; element and then the &lt;option&gt; elements contained, I used a CSS selector to directly go to the options. The BeautifulSoup CSS selector code isn't all that sophisticated, so we can't use the :not(.selected) psuedo selector to filter out that one option. Demo: &gt;&gt;&gt; nosto_sku_tags = soup.select('select[name="id"] option') &gt;&gt;&gt; for nosto_sku_tag in nosto_sku_tags: ... if 'selected' in nosto_sku_tag.get('class', ()): ... continue ... sku_size = nosto_sku_tag.get_text(strip=True) ... print(sku_size) ... 4,5 5,5 6 7 8,5 9 10 If there is no class on the &lt;option&gt; elements, and there is no selected attribute either, then you'll have to come up with your own heuristics. By default the first element is the one that is visible in the browser, so we can just skip that one: for nosto_sku_tag in nosto_sku_tags[1:]: sku_size = nosto_sku_tag.get_text(strip=True) Note the [1:] slice.
upvote count: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/91107051
type: Answer
has comment: http://stackoverflow.com/comment/91106872
has comment: http://stackoverflow.com/comment/91105319
has comment: http://stackoverflow.com/comment/91106921
downvote count: 0
has comment: http://stackoverflow.com/comment/91105515
has comment: http://stackoverflow.com/comment/91106847
has comment: http://stackoverflow.com/comment/91107152

http://stackoverflow.com/comment/91171556
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52101226
has text: Much better solution! I was not aware of the `.between` function.

http://stackoverflow.com/comment/91098628
type: AnswerComment
comment on: http://stackoverflow.com/a/52074395
type: Comment
has text: @Chaban33 My bad, needed to strip the leading spaces... Now it works :)
score: 0

http://stackoverflow.com/comment/91101372
has text: I'll add a comment. We don't have enough data to make a judgement one way or the other. Best to show all solutions :)
type: Comment
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/52075834

http://stackoverflow.com/comment/91518763
type: Comment
score: 1
comment on: http://stackoverflow.com/a/52135770
type: AnswerComment
has text: Never mind, my `PATH_TO_TRAIN_DIR` folder still had checkpoints in it from my last failed training attempt. TF was trying to restart training from those checkpoints, and realising that they didn't match the initial checkpoint... Training is running now. I'll just have to wait and see if it converges to a useful result!

http://stackoverflow.com/comment/90917507
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/51984042
has text: Welcome to SO :) Please provide some code samples, so it will be more straightforward to answer, I guess there may be some mess with the usage of `:` and `,`
type: Comment

http://stackoverflow.com/q/52092097
has comment: http://stackoverflow.com/comment/91136051
has title: GoogleCloudStorageToBigQueryOperator source_objects to receive list via XCom
has answer: http://stackoverflow.com/a/52093800
accepted answer: http://stackoverflow.com/a/52093800
possible better answer: http://stackoverflow.com/a/71961091
favorite count: 0
has comment: http://stackoverflow.com/comment/91136134
has comment: http://stackoverflow.com/comment/91136694
tagged with: python
has comment: http://stackoverflow.com/comment/91136833
has answer: http://stackoverflow.com/a/71961091
type: AnsweredQuestion
downvote count: 0
score: 1
type: Question
linked to: http://stackoverflow.com/q/47052582
has body: I would like to pass a list of strings, containing the name of files in google storage to XCom. Later to be picked up by a GoogleCloudStorageToBigQueryOperator task. The source_objects field is templated, so that Jinja templating can be used. Unfortunately, Jinja can only return a string, and thus I cannot pass the list in XCom. How can I use a XCom list in GoogleCloudStorageToBigQueryOperator? Reference to a similar question, solved by using provide_context: Pass a list of strings as parameter of a dependant task in Airflow The closest solution I've found, which works, is to create a wrapper class and sending the id of the task who posted the xcom like so: @apply_defaults def __init__(self, source_objects_task_id, .... def execute(self, context): source_objects = context['ti'] .xcom_pull(task_ids=self.source_objects_task_id) operator = GoogleCloudStorageToBigQueryOperator( source_objects=source_objects, dag=self.dag, .... ) operator.execute(context)
tagged with: airflow
answer count: 2
upvote count: 1

http://stackoverflow.com/comment/90867505
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51958480
has text: I did a test where a=pd.DataFrame({'test':[]}),a=a.append({'test':x},ignore_index=True) which seemed to work fine for my purposes however after running my whole script something obviously broke. Just trying to keep it all organised in one file.
score: 0

http://stackoverflow.com/q/52057583
score: 16
accepted answer: http://stackoverflow.com/a/52057975
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91065971
favorite count: 0
type: Question
tagged with: django
tagged with: python
answer count: 1
upvote count: 16
has comment: http://stackoverflow.com/comment/91065830
has title: Python 2 -> 3 Django migration causes field parameter type change
has answer: http://stackoverflow.com/a/52057975
has body: We are transitioning a Django project from Django 1.8 -> 2.1 and Python 2.7 -> 3.6. In the old project version, there are Django models that looked like this, for example: # models.py from django.db import models class RowStatusModel(models.Model): active = models.BooleanField(default=True, db_column='is_active') # ... class Meta: abstract = True Notice that from __future__ import unicode_literals is not used in this module. That means that db_column is a Python 2 str, corresponding to bytes in Python 3. The initial migration, 0001_initial.py, looks like this: # 0001_initial.py operations = [ # ... ('row_ef', models.BooleanField(default=True, db_column=b'is_active') # ... ] Notice the byte-literal b'is_active, which I suppose was done by Django in the interest of being more explicit, but am not sure. Now after transitioning most of the codebase with 2to3 and running makemigrations, Python 3 treats a string literal as what would be the unicode type in Python 2, and consequently generates a migration where the db_column is a string literal, for every single model that inherits from RowStatusModel: # migrations/0023_auto_20180827_1955.py migrations.AlterField( # ... field=models.BooleanField(default=True, db_column='is_active') ), # ... What effect, if any, will this have on the database side when ./manage.py migrate is ran? Is the "change" purely on the Python side, or what side effects may be created? Database engine is django.db.backends.postgresql. I'm aware that we can just clone the RDS instance and revert back to that if migrate causes immediate problems, but I am more concerned about more subtle issues being introduced that would not be caught until much later on.
tagged with: django-migrations
downvote count: 0

http://stackoverflow.com/q/52080846
type: UnansweredQuestion
has body: So I want to extract the number 45.5 from here: https://www.myscore.com.ua/match/I9pSZU2I/#odds-comparison;over-under;1st-qrt But when I try to find the table I get nothing. Here's my code: import requests from bs4 import BeautifulSoup url = 'https://www.myscore.com.ua/match/I9pSZU2I/#odds-comparison;over-under;1st-qrt' headers = {'User-Agent': 'Mozilla/5.0 (X11; Linux armv7l) AppleWebKit/537.36 (KHTML, like Gecko) Raspbian Chromium/65.0.3325.181 Chrome/65.0.3325.181 Safari/537.36'} response = requests.get(url, headers=headers) soup = BeautifulSoup(response.content, 'html.parser') text = soup.find_all('table', class_ = 'odds sortable') print(text) Can anybody help me to extract the number and store it's value into a variable?
tagged with: python
has comment: http://stackoverflow.com/comment/91112006
has title: I get nothing when trying to scrape a table
score: 1
has answer: http://stackoverflow.com/a/52081156
tagged with: web-scraping
upvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/91111889
answer count: 1
downvote count: 0
favorite count: 0

http://stackoverflow.com/comment/91003355
comment on: http://stackoverflow.com/q/52016793
score: 0
has text: Thanks for your advice.It's helpful.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/90996522
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52023108
score: 0
has text: Possible duplicate of [django MultiValueDictKeyError error, how do I deal with it](https://stackoverflow.com/questions/5895588/django-multivaluedictkeyerror-error-how-do-i-deal-with-it)

http://stackoverflow.com/q/52019733
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/52020159
tagged with: url
has comment: http://stackoverflow.com/comment/90990328
has answer: http://stackoverflow.com/a/52020184
tagged with: python
type: UnansweredQuestion
tagged with: django
has comment: http://stackoverflow.com/comment/90990870
has title: NoReverseMatch "Not valid new function or pattern name"
has body: It's been a few hours and I can't seem to find where my error is. my thoughts were its in my category.html file or new_topic.html file. I am trying to add a new topic to a category. There are multiple categories and the topic that is entered will go to a specific category based on what the user chooses. Every time I click on the link to add a new topic to a certain category I receive the error shown above. Everything else works just fine. urls.py. File : app_name = 'blogging_logs' urlpatterns = [ # Home page path('', views.index, name='index'), # Show all Categories path('categories/', views.categories, name='categories'), # Show all topics associated with category re_path(r'^topics/(?P<category_id>\d+)/$', views.topics, name='topics'), # Show single topics re_path(r'^topic/(?P<entry_id>\d+)/$', views.topic, name='topic'), # Page for adding a new category path('new_category/', views.new_category, name='new_category'), # Page for adding new topics re_path(r'^new_topic/(?P<category_id>\d+)/$', views.new_topic, name='new_topic'), ] view.py file: def new_category(request): """Add a new category""" if request.method != 'POST': # No data submitted; create a blank formself. form = CategoryForm() else: # POST data submitted; process data form = CategoryForm(data=request.POST) if form.is_valid(): form.save() return HttpResponseRedirect(reverse('blogging_logs:categories')) context = {'form': form} return render(request, 'blogging_logs/new_category.html', context) def new_topic(request, category_id): """ Add new topic to category """ category = Category.objects.get(id=category_id) if request.method != 'POST': # No data submitted; create a blank formself. form = TopicForm() else: form = TopicForm(data=request.POST) if form.is_valid(): new_topic = form.save(commit=False) new_topic.Category = category new_topic.save() return HttpResponseRedirect(reverse('blogging_logs:category', args=[category_id])) context = {'category': category, 'form': form} return render(request, 'blogging_l…
type: Question

http://stackoverflow.com/a/51994172
has body: Take advantage of the string.format method: file.write('{0}:{1}\n'.format(name, dat))
has comment: http://stackoverflow.com/comment/90938375
upvote count: 1
has comment: http://stackoverflow.com/comment/90938200
has comment: http://stackoverflow.com/comment/90938120
score: 1
answers question: http://stackoverflow.com/q/51994134
has comment: http://stackoverflow.com/comment/90938143
downvote count: 0
has comment: http://stackoverflow.com/comment/90938164
type: Answer
has comment: http://stackoverflow.com/comment/90938412

http://stackoverflow.com/q/52014327
has body: I am trying to scrape tweets from one webpage within a certain timeframe. To do so I am using this link which only searches within the timeframe I have specified: https://twitter.com/search?f=tweets&amp;q=subwaydstats%20since%3A2016-08-22%20until%3A2018-08-22 This is my code: import pandas as pd import datetime as dt import urllib.request from bs4 import BeautifulSoup url = 'https://twitter.com/search?f=tweets&amp;q=subwaydstats%20since%3A2016-08-22%20until%3A2018-08-22' thepage = urllib.request.urlopen(url) soup = BeautifulSoup(driver.page_source,"html.parser") i = 1 for tweet in soup.find_all('div', {'class': 'js-tweet-text-container'}): print(tweet.find('p', {'class': 'TweetTextSize'}).text.encode('UTF-8')) print(i) i += 1 The above code works when I am scraping from within the actual twitter page for the subwaystat user. For this reason I don't understand why it doesn't work for the search page even though the html appears to be the same to me. I am a total beginner so I'm sorry if this is a dumb question. Thank you!
has answer: http://stackoverflow.com/a/52014972
tagged with: twitter
score: 0
has comment: http://stackoverflow.com/comment/90998251
has comment: http://stackoverflow.com/comment/90980037
answer count: 1
tagged with: beautifulsoup
accepted answer: http://stackoverflow.com/a/52014972
tagged with: http://stackoverflow.com/tag/html
tagged with: python
has comment: http://stackoverflow.com/comment/90987988
has title: Issue with scraping tweets using python
type: Question
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90980054

http://stackoverflow.com/a/51997129
score: 2
has body: This should be a lil bit faster ... ;) import numpy as np blue = np.full_like(image, [76,150,250]) mask = np.sum((image-blue)**2,axis=-1) &lt; 12000 image[mask] = [255,0,255] Here you're generating the ideal blue image, squaring the difference of the images pixel by pixel, then summing over the last axis (the rgb vectors) before generating a mask and using it to modify values in the original image.
has comment: http://stackoverflow.com/comment/90944727
has comment: http://stackoverflow.com/comment/90953409
upvote count: 2
answers question: http://stackoverflow.com/q/51997022
downvote count: 0
type: Answer

http://stackoverflow.com/q/52080292
answer count: 0
has comment: http://stackoverflow.com/comment/91123386
tagged with: html-parsing
has body: I'm trying to retrieve the content of: https://www.towncity.com/property/whole-hotel-for-sale-in-riverside-area/ like this: class LinkParser(HTMLParser): def handle_starttag(self, tag, attrs): if tag == 'a': for (key, value) in attrs: if key == 'href': newUrl = parse.urljoin(self.baseUrl, value) self.links = self.links + [newUrl] def getLinks(self, url): self.links = [] self.baseUrl = url timeOut = False try: req = Request(url, headers={'User-Agent': 'Mozilla/5.0'}) response = urlopen(req,timeout=20) except: timeOut = True print(url,'timed out') if timeOut: return "timeOut",[] if 'text/html' in response.getheader('Content-Type') and not timeOut: htmlBytes = response.read() try: htmlString = htmlBytes.decode("utf-8") except: htmlString = htmlBytes.decode("ISO-8859-1") self.feed(htmlString) return htmlString, self.links else: return "",[] parser = LinkParser() data, links = parser.getLinks("https://www.towncity.com/property/whole-hotel-for-sale-in-riverside-area/") What I get differs from the actual content of the page (as seen with Chrome's view-source). I notice that what's missing comes from tabbed windows within the pages, could it be it? If so, how do I actually get all the content from the pages?
type: Question
score: 0
has comment: http://stackoverflow.com/comment/91110584
has comment: http://stackoverflow.com/comment/91112803
has comment: http://stackoverflow.com/comment/91110956
linked to: http://stackoverflow.com/q/51586527
has comment: http://stackoverflow.com/comment/91111004
type: UnansweredQuestion
tagged with: python
has title: Python's html.parser fails to retrieve parts of a web page (content of tabbed panels)
has comment: http://stackoverflow.com/comment/91113369
has comment: http://stackoverflow.com/comment/91110668

http://stackoverflow.com/q/51971141
tagged with: python
favorite count: 0
type: UnansweredQuestion
tagged with: timezone
has body: I am playing with some data. Out of all, two columns make me curious, Datetime and Timezone. Sample data looks like: |-----------------|------------| | Datetime | Timezone | |-----------------|------------| | 2446159.1805556 | -5.5000000 | | 2434633.2902778 | -5.5000000 | | 2444298.3437500 | -5.5000000 | | 2442694.3125000 | -5.5000000 | | 2444622.0604167 | -5.5000000 | | 2435409.3854167 | 8.0000000 | |-----------------|------------| While trying to convert these to timestamp format (YYYY-MM-DD hh:mm:ss), using the code below, I am getting all dates as 1970-01-29: pd.to_datetime(df['Datetime'], unit='s') How can I convert to the right date in the right timezone? I don't know the actual output, but I am certain that all dates are not going to be the same.
downvote count: 1
has title: Pandas date time with timezone to timestamp
score: -1
type: Question
upvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/90893383
tagged with: data-analysis
has answer: http://stackoverflow.com/a/51971576
tagged with: pandas
tagged with: datetime

http://stackoverflow.com/comment/91034955
has text: @GarvitaTiwari is there any way I could give access to my webcam?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52041888

http://stackoverflow.com/q/51964443
favorite count: 0
has comment: http://stackoverflow.com/comment/90907351
tagged with: python
has answer: http://stackoverflow.com/a/51965149
accepted answer: http://stackoverflow.com/a/51965149
type: AnsweredQuestion
tagged with: list
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/90940927
type: Question
has title: Check index for 2D list and print out the index based on 2D list
has comment: http://stackoverflow.com/comment/90917341
has body: I wanted to try another example such to print the index for 2D list. Example: a = [["text", "man","chest","funny"],["cruel", "just","for","testing"],["I", "take","this","for"],["learning", "purpose","only","please"] ] b = [["text", "funny"], ["cruel"],["I", "take"], ["for","learning", "purpose"]] ba = ["text", "funny", "purpose"] My code is something like this: store_x = [] for x in b: for i,xx in enumerate(x): if xx in ba: store_x.append(i) print(store_x) dic2 = [] for x,y in zip(store_x,a): result = [] for u in str(x): dic2.append(y[int(u)]) print(dic2) Current output: [0, 1, 2] ['text', 'just', 'this'] Expected output: [0][0,1],[3][2] # {b} based on {ba} Not sure whether this is how the index #should be look like for 2D [["text","man"],["only"]] # store_x based on {a} I wanted to first find the index value of {b} based on {ba} and then from the index value, I will use it to print the value from {a} by using the index stored in {store_x} New: Here is another questions when we play around with the {ba} elements. Example, a = [["text", "funny"], ["cruel"],["I", "take"], ["for","learning", "purpose"]] b = [["text", "funny"], ["cruel"],["I", "take"], ["for","learning", "purpose"]] ba = ["funny","text", "take","new","I", "purpose", "learning", "cruel"] Then the code I am currently using is: store_x = {} for ex, x in enumerate(b): row = [] for i, xx in enumerate(x): if xx in ba: row.append(i) if row: store_x[ex] = row print(store_x) order = {e: ii for ii, e in enumerate(ba)} dic2 = [] for i, x in store_x.items(): row = [] if x: for ex in x: dic2.append(a[i][ex]) if dic2: dic2.sort(key=lambda e: order.get(e, len(ba))) print(dic2) The store_x values appeared to be: {0: [0, 1], 1: [0], 2: [0, 1], 3: [1, 2]} and not what I expected it to be: {0: [1, 0], 2: [1,0], 3: [2, 1], 1: [0]} The current dic2: (which is correct but the store_x value is not what I expected it to be) ['funny', 'text', 'take', 'I', 'purpose', 'learning', 'cruel'] Updates! I try to use my new code: s = []…
has comment: http://stackoverflow.com/comment/90911096
upvote count: 1
answer count: 1
has comment: http://stackoverflow.com/comment/90879906

http://stackoverflow.com/comment/91251354
type: Comment
type: QuestionComment
has text: Done. Can you check it now? @asynts
comment on: http://stackoverflow.com/q/52064036
score: 0

http://stackoverflow.com/a/52081650
answers question: http://stackoverflow.com/q/52081556
has comment: http://stackoverflow.com/comment/91114147
has body: "PASSED" means the listed test passed. [ 50%] is how many of the tests have been run so far.
type: AcceptedAnswer
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/91114123
score: 3
upvote count: 3
accepted answer of: http://stackoverflow.com/q/52081556

http://stackoverflow.com/comment/90888355
comment on: http://stackoverflow.com/a/51968256
score: 0
type: AnswerComment
type: Comment
has text: Shall I refer to the class named "notranslate"? Hotel Name

http://stackoverflow.com/comment/91070418
comment on: http://stackoverflow.com/q/52059849
score: 0
has text: @appleapple Thinking about what if we had 100 coefficients. This is thinking ahead when we don't need to. We only have 3 coefficients right now, and this code is more than suitable at handling that.
type: Comment
type: QuestionComment

http://stackoverflow.com/a/52021031
downvote count: 0
answers question: http://stackoverflow.com/q/52020944
has body: Yes, the gen() function is not working correctly as your slicing is off, also, you count 2, 3, 5 and 7 as truncatable primes which the question denies. The second slice should be the other way around: &gt;&gt;&gt; s = 'abcd' &gt;&gt;&gt; for i in range(1,len(s)-1): ... print(s[i:]) ... print(s[:-i]) ... bcd abc cd ab which we can see produces the right strings. Altogether then, the function should be: def gen(nb): results = [nb] nb_str = str(nb) for k in range(1, len(nb_str)): results.append(int(nb_str[k:])) results.append(int(nb_str[:-k])) return results note I also added a string to int conversion - not sure how Python didn't make that obvious for you :/ And before get the full solution, Project Euler nearly always gives you an example which you can use to check your code: &gt;&gt;&gt; check(3797) True You must also add a condition in the check function to return False if the number is 2, 3, 5 or 7 as this is stated clearly in the question. And the result is the expected: 748317.
type: Answer
score: 2
upvote count: 2

http://stackoverflow.com/a/52016917
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/90984466
accepted answer of: http://stackoverflow.com/q/52016728
type: Answer
has comment: http://stackoverflow.com/comment/90983902
answers question: http://stackoverflow.com/q/52016728
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/90985282
has body: I suggest you use a GET request instead to display your table. The delete should happen through a POST and use redirect (instead of render) to go to the GET request again. If you want to store filter parameters between requests, I suggest you use Django Session to store that info. Maybe like this: urls.py url(r'^characters$', views.show_characters, name='show-characters'), url(r'^characters/(?P&lt;char_pk&gt;[0-9]+)/delete/$', views.delete_character, name='delete-character'), views.py def show_characters(request): # this will be a standard GET request to display the table filter_param_1 = request.GET.get('filter_param_1', None) if filter_param_1 is None: # if there is no GET param, look in the session filter_param_1 = request.session.get('filter_param_1', None) else: # if there is a GET param, store it in the session for the next time request.session['filter_param_1'] = filter_param_1 ctx = { 'data': Characters.objects.filter(some_field=filter_param_1), } return render(request, 'users/characters_found_table.html', ctx) def delete_character(request, char_pk): if request.method == "POST": character = get_obect_or_404(Characters, pk=char_pk) # here you can delete other related objects, if they're not set up for delete CASCADE character.delete() messages.success(request, 'delete was successful') return redirect('show-characters') Does that work for you?
has comment: http://stackoverflow.com/comment/90984232

http://stackoverflow.com/comment/90981641
comment on: http://stackoverflow.com/q/52015673
score: 0
has text: You should check `search_result.is_valid()`, and then you can access the value with `search_result.cleaned_data['student_select']`.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/90999162
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52015772
type: Comment
has text: @7kemZmani Thanks for your help, I appreciate your initiative, I'll make sure to add efficient details for further questions, However I already have accepted the first answer that solves my problem regardless to the persons points... Thanks all, Good luck!

http://stackoverflow.com/q/52110485
type: Question
has comment: http://stackoverflow.com/comment/91173066
has comment: http://stackoverflow.com/comment/91171628
has answer: http://stackoverflow.com/a/56892514
has comment: http://stackoverflow.com/comment/91176928
tagged with: visual-c++
score: 0
answer count: 2
has comment: http://stackoverflow.com/comment/91172720
has comment: http://stackoverflow.com/comment/91172028
has title: PIP INSTALL CROSSBAR gives error: Microsoft Visual C++ 14.0 is required. Get it with "Microsoft Visual C++ Build Tools":
linked to: http://stackoverflow.com/q/29846087
has answer: http://stackoverflow.com/a/52112873
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91175493
tagged with: python
has body: I have been trying to pip install crossbar on my virtual environment in Windows 10 but I keep getting: error: Microsoft Visual C++ 14.0 is required. Get it with "Microsoft Visual C++ Build Tools": http://landinghub.visualstudio.com/visual-cpp-build-tools I am using Python3.7 and Django2.1 I have installed the requirement and have restarted my system severally but still getting the same error. Pip has been upgraded too. Here is the list of programs install from my Control Panel: And here is the Command Prompt error (again) I have equally installed Microsoft Visual C++ 2017 Redistributable, both (x86) and (x64) but still did not work.
tagged with: visual-studio
has comment: http://stackoverflow.com/comment/91171961
tagged with: c++
has comment: http://stackoverflow.com/comment/91172207
has comment: http://stackoverflow.com/comment/91171655
has comment: http://stackoverflow.com/comment/91192892
tagged with: django

http://stackoverflow.com/q/51974513
has title: getting error of import in airflow DAG in google cloud composer
has comment: http://stackoverflow.com/comment/93117289
type: Question
tagged with: airflow
tagged with: google-cloud-composer
answer count: 2
has comment: http://stackoverflow.com/comment/92606066
tagged with: google-cloud-platform
upvote count: 1
has answer: http://stackoverflow.com/a/52020140
favorite count: 0
has body: I have a DAG in google composer (airflow) that imports: from airflow.contrib.sensors.gcs_sensor import GoogleCloudStorageObjectSensor when I run the DAG I got this error: "ImportError: No module named sensors.base_sensor_operator" Basically I want to check if a file exists in a bucket before doing something else. Here is the complete python code: from datetime import datetime,timedelta from airflow import DAG from airflow.operators.dummy_operator import DummyOperator from airflow.operators.subdag_operator import SubDagOperator from airflow.operators.python_operator import PythonOperator from airflow.contrib.operators.gcs_to_bq import GoogleCloudStorageToBigQueryOperator from airflow.contrib.sensors.gcs_sensor import GoogleCloudStorageObjectSensor CONNECTION_ID = 'something' default_args = { 'owner': 'airflow', 'depends_on_past': False, 'start_date': datetime(2018, 8, 21, 0, 0), } def print_hello(): return 'youtube folder exists!!' with DAG('DATA_TRANSFER_GCP_BUCKET_TO_BQ2', schedule_interval=timedelta(days=1), default_args=default_args ) as dag: gcp_sensorBucket=GoogleCloudStorageObjectSensor( task_id='gcp_sensorbucket', bucket='/aa_youtube_new/2018/06/04/', #bucket='{{var.value.gcp_youtube_video_bucket}}/2018/06/04/', object='*.csv', google_cloud_conn_id=CONNECTION_ID ) hello_operator = PythonOperator(task_id='hello_task', python_callable=print_hello) hello_operator.set_upstream(gcp_sensorBucket)
tagged with: python
has answer: http://stackoverflow.com/a/53111069
downvote count: 0
type: UnansweredQuestion
score: 1

seaborn
tags question: http://stackoverflow.com/q/52043402
tags question: http://stackoverflow.com/q/52107106
tags question: http://stackoverflow.com/q/52013973
tags question: http://stackoverflow.com/q/52064837
tags question: http://stackoverflow.com/q/52103408
tag name: seaborn
tags question: http://stackoverflow.com/q/52096050
tags question: http://stackoverflow.com/q/52004050
tags question: http://stackoverflow.com/q/51987134
tags question: http://stackoverflow.com/q/52101245
tags question: http://stackoverflow.com/q/52058695
tags question: http://stackoverflow.com/q/52098537
tags question: http://stackoverflow.com/q/52028043
tags question: http://stackoverflow.com/q/51974604
tags question: http://stackoverflow.com/q/52088018
tags question: http://stackoverflow.com/q/51988139
tags question: http://stackoverflow.com/q/52005576
tags question: http://stackoverflow.com/q/52007577
tags question: http://stackoverflow.com/q/51986724
tags question: http://stackoverflow.com/q/52024367
tags question: http://stackoverflow.com/q/52054168
tags question: http://stackoverflow.com/q/51963725
tags question: http://stackoverflow.com/q/51965611
tags question: http://stackoverflow.com/q/52105356
tags question: http://stackoverflow.com/q/52097045
tags question: http://stackoverflow.com/q/52002905
tags question: http://stackoverflow.com/q/52048631
tags question: http://stackoverflow.com/q/52020347
tags question: http://stackoverflow.com/q/52105048
tags question: http://stackoverflow.com/q/52084421
type: Tag
tags question: http://stackoverflow.com/q/52067785
tags question: http://stackoverflow.com/q/52097967

http://stackoverflow.com/comment/90889303
type: AnswerComment
comment on: http://stackoverflow.com/a/51969324
type: Comment
has text: Perfect! This works and very quickly. I just thought to use for loop to solve this, but that causes too much costs I think. Thanks a lot.
score: 0

http://stackoverflow.com/a/52015032
has comment: http://stackoverflow.com/comment/90982021
upvote count: 2
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/90981904
has comment: http://stackoverflow.com/comment/90980446
type: Answer
has comment: http://stackoverflow.com/comment/90981583
score: 2
has comment: http://stackoverflow.com/comment/90988689
downvote count: 0
has body: Here is the working code that accepts more than one variables: def remove_stopwords(*args): with open('myownstopwords.txt','r') as my_stopwords: stopwords_list = my_stopwords.read() new_list = [] for arg in args: if str(arg) not in stopwords_list: new_list.append(arg) else: pass # You can write something to do if the stopword is found my_stopwords.close() print(new_list) remove_stopwords('axe','alien','a') Here is the code with only one variable: def remove_stopwords(param): with open('myownstopwords.txt','r') as my_stopwords: stopwords_list = my_stopwords.read() new_list = [] if str(param) not in stopwords_list: new_list.append(param) else: pass # You can write something to do if the stopword is found my_stopwords.close() print(new_list) remove_stopwords('axe') Code to accept list: def remove_stopwords(params): with open('myownstopwords.txt','r') as my_stopwords: stopwords_list = my_stopwords.read() new_list = [] for param in params: if str(param) not in stopwords_list: new_list.append(param) else: pass # You can write something to do if the stopword is found my_stopwords.close() print(new_list) remove_stopwords(['axe','a']) I removed the redundant return statement and the new_list.close() as lists cannot be closed and got rid of the for loop. EDIT: for supporting lists, I just added a for loop to loop over the parameter list provided Welcome to stackoverflow! Please, when writing a question in future, be more clear with what you want to achieve and include all variables and sources linked to your query. I would suggest reading this to guide you to writing a clear question
accepted answer of: http://stackoverflow.com/q/52014762
has comment: http://stackoverflow.com/comment/90982613
has comment: http://stackoverflow.com/comment/90980541
has comment: http://stackoverflow.com/comment/90988075
has comment: http://stackoverflow.com/comment/90983945
answers question: http://stackoverflow.com/q/52014762
has comment: http://stackoverflow.com/comment/90981713
has comment: http://stackoverflow.com/comment/90980468

http://stackoverflow.com/comment/90913061
type: QuestionComment
comment on: http://stackoverflow.com/q/51980856
score: 0
has text: Did you checked this https://stackoverflow.com/questions/7667567/can-i-patch-a-python-decorator-before-it-wraps-a-function ?
type: Comment

http://stackoverflow.com/comment/90985700
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52017705
has text: Nice idea but this fails when the rows have more than two lists in them... `rows = [[[1], [2], [3]], [[4], [5], [6]]]` throws a TypeError.
score: 1

http://stackoverflow.com/comment/90974180
type: Comment
type: QuestionComment
has text: @bigbounty yes bro but when i try this i am getting other error of `sqlite3.OperationalError: near "%": syntax error`
score: 0
comment on: http://stackoverflow.com/q/52011219

http://stackoverflow.com/comment/91150083
score: 0
has text: Edit your original post and put the two datetimes in
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52099464

http://stackoverflow.com/comment/91098311
comment on: http://stackoverflow.com/a/52062172
score: 0
type: Comment
has text: You're welcome. Goodluck!
type: AnswerComment

http://stackoverflow.com/comment/90870553
has text: You've tried to index into a list with a string as the index `"5"`. Convert it to an integer. Also, you're putting not the variable `character`, but the literal string `"character"` into that position (once you fix the first problem).
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51960176

http://stackoverflow.com/comment/91065463
has text: @brunodesthuilliers please check now
type: QuestionComment
comment on: http://stackoverflow.com/q/52056526
score: 0
type: Comment

http://stackoverflow.com/a/52042531
score: 1
downvote count: 0
answers question: http://stackoverflow.com/q/52041823
type: Answer
has body: One way is to build a regex string to identify any keyword in your string... this example is case insensitive and will find any substring matches - not just whole words... import pandas as pd import re keywords = ['python', 'C++', 'admin', 'Developer'] rx = '(?i)(?P&lt;keywords&gt;{})'.format('|'.join(re.escape(kw) for kw in keywords)) Then with a sample DF of: df = pd.DataFrame({ 'job_description': ['C++ developer', 'traffic warden', 'Python developer', 'linux admin', 'cat herder'] }) You can find all keywords for the relevant column... matches = df['job_description'].str.extractall(rx) Which gives: keyword match 0 0 C++ 1 developer 2 0 Python 1 developer 3 0 admin Then you want to get a list of "dummies" and take the max (so you always get a 1 where a word was found) using: dummies = pd.get_dummies(matches).max(level=0) Which gives: keyword_C++ keyword_Python keyword_admin keyword_developer 0 1 0 0 1 2 0 1 0 1 3 0 0 1 0 You then left join that back to your original DF: result = df.join(dummies, how='left') And the result is: job_description keyword_C++ keyword_Python keyword_admin keyword_developer 0 C++ developer 1.0 0.0 0.0 1.0 1 traffic warden NaN NaN NaN NaN 2 Python developer 0.0 1.0 0.0 1.0 3 linux admin 0.0 0.0 1.0 0.0 4 cat herder NaN NaN NaN NaN
upvote count: 1

http://stackoverflow.com/q/52023979
tagged with: mysql
tagged with: web-scraping
has body: I wrote a code every time every hour, it takes information like, price-profile-photo, etc. from sites and stores in the database. But the problem is that the information is repeated every two hours and the data volume is increased in the database. Is there a way to pinpoint, for example, if the price of a TV on the main site is changed, only the price of the TV in the database will be updated?
has title: Updating the data stored in the database(python+ Beautiful Soup+mysql)
type: Question
score: 0
has comment: http://stackoverflow.com/comment/90998305
tagged with: beautifulsoup
tagged with: python-3.x
type: UnansweredQuestion
tagged with: python
answer count: 0
has comment: http://stackoverflow.com/comment/90999562

http://stackoverflow.com/comment/91076215
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52048053
has text: So I got rid of the time.sleep(2) and while True and the code runs ok, but only gets the date once and doesn't continuously update. The HTML code doesn't display anything other than "new data goes here", do I need to change anything in the HTML code you have posted? I have also tried updating the date value using app scheduler, when I run this code in the python file on its own it works OK, as soon as I import this module to my flask file, it says Pythn can find the apscheduler model. I will keep trying, let me know where I am going wrong. Thanks
type: AnswerComment

http://stackoverflow.com/q/52015321
downvote count: 2
upvote count: 1
has body: I'm trying to porting a project 2to3 on python, and stuck in tkinter. In python2, there is no problem with adding menu bar to Frame in tkinter, but python3 occured attribute error. (Frame object has no attribute 'tk_menuBar') Is there any differences between python2 and python3 about adding menu bar to Frame in tkinter? class TkMap(Map, tkinter.Tk): """ Map with Tkinter GUI functions """ def __init__(self, cols, rows, value, width, height, widthMM, heightMM, title, menu = None, keybindings = []): """ TkMap extends Map and Tkinter """ Map.__init__(self, cols, rows, widthMM, heightMM) tkinter.Tk.__init__(self) self.title(title) if menu == None: menu = [('File','Exit',self.destroy)] keybindings.append( ("&lt;Configure&gt;", self.changeSize)) self.menuButtons = {} self.debug = 0 self.application = 0 self.width = width self.height = height self.colScale = self.width / self.cols self.rowScale = self.height / self.rows self.addMenu(menu) def addMenu(self, menu): """ Create a menu """ self.mBar = tkinter.Frame(self,relief=tkinter.RAISED,borderwidth=2) self.mBar.pack(fill=tkinter.X) *for entry in menu: self.mBar.tk_menuBar(self.makeMenu(self.mBar, entry[0],entry[1]))* self.mBar.pack(side = "top") PS. It's my first question, so i will be appreciated that if you point out my mistake about bad manners.
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/90983660
has comment: http://stackoverflow.com/comment/90985011
tagged with: python-3.x
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/52017490
has title: Is there any differences between python2 and python3 about adding menu bar to Frame in tkinter?
tagged with: python
tagged with: tkinter
has comment: http://stackoverflow.com/comment/90991252
type: Question
score: -1

http://stackoverflow.com/comment/90954100
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52001249
type: AnswerComment
has text: Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/178675/discussion-between-andie31-and-henry-yuan).

http://stackoverflow.com/a/52048219
has comment: http://stackoverflow.com/comment/91048207
type: Answer
answers question: http://stackoverflow.com/q/52048176
score: 1
has body: There's no timezone in the string you've provided: &gt;&gt;&gt; sample_datetime = "2015-07-25T21:45:00" &gt;&gt;&gt; obj = dt.datetime.strptime(sample_datetime, TIMESTAMP_FORMAT) Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "/Users/mm92400/anaconda3/envs/py36/lib/python3.6/_strptime.py", line 565, in _strptime_datetime tt, fraction = _strptime(data_string, format) File "/Users/mm92400/anaconda3/envs/py36/lib/python3.6/_strptime.py", line 362, in _strptime (data_string, format)) ValueError: time data '2015-07-25T21:45:00' does not match format '%Y-%m-%dT%H:%M:%SZ' Removing Z from your format string obj = dt.datetime.strptime(sample_datetime, '%Y-%m-%dT%H:%M:%S') &gt;&gt;&gt; obj datetime.datetime(2015, 7, 25, 21, 45)
has comment: http://stackoverflow.com/comment/91047993
upvote count: 2
downvote count: 1

http://stackoverflow.com/comment/90966252
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52007931
has text: What is the `message`?

http://stackoverflow.com/q/52009873
answer count: 1
has answer: http://stackoverflow.com/a/52012155
score: 0
type: UnansweredQuestion
tagged with: python
has body: Within Google Cloud Storage Bucket, I'm trying to move a file from it's original folder to the archived folder. Once the file move is 'successfully' completed, I want to then delete the file from it's original folder. ## Assigning the bucket to the bucket object bucket = storage.Bucket(&lt;Bucket_Name&gt;) ## Enumerating and finding the required file object in the bucket and ##assigning that to my_file object for obj in bucket.objects(): if obj.key.find(&lt;file_name&gt;) &gt; 0: my_file = obj print(my_file.key) ## Taking the current timestamp timestamp = str(datetime.now()) ## Copying the file to the new location my_file.copy_to( &lt;archive folder&gt; + &lt;file name&gt; + &lt;timestamp&gt;) I now want to check if the "my_file.copy_to()" has executed successfully or not before I want to delete the file object. How can I check this?
tagged with: google-cloud-storage
type: Question
has title: Python for google.datalab.storage - Checking for successful file copy

remote-debugging
tag name: remote-debugging
tags question: http://stackoverflow.com/q/51982200
type: Tag
tags question: http://stackoverflow.com/q/52093988

http://stackoverflow.com/comment/90965468
comment on: http://stackoverflow.com/q/52007555
score: 0
type: Comment
type: QuestionComment
has text: By difference, do you mean just the 'ID' found in the table, or do you also need to compare the values in columns associated with the same 'ID'.

http://stackoverflow.com/comment/91041693
type: AnswerComment
comment on: http://stackoverflow.com/a/52042991
type: Comment
has text: from the linked article
score: 0

http://stackoverflow.com/q/52087219
linked to: http://stackoverflow.com/q/10487563
has answer: http://stackoverflow.com/a/52088173
tagged with: file
has title: How to address: Python import of file with .csv Dictreader fails on undefined character
downvote count: 1
has comment: http://stackoverflow.com/comment/91125121
type: Question
has comment: http://stackoverflow.com/comment/91190670
has comment: http://stackoverflow.com/comment/91162516
upvote count: 4
has comment: http://stackoverflow.com/comment/91126420
linked to: http://stackoverflow.com/q/38019379
accepted answer: http://stackoverflow.com/a/52088173
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/91124784
has body: First of all, I found the following which is basically the same as my question, but it is closed and I'm not sure I understand the reason for closing vs. the content of the post. I also don't really see a working answer. I have 20+ input files from 4 apps. All files are exported as .csv files. The first 19 files worked (4 others exported from the same app work) and then I ran into a file that gives me this error: UnicodeDecodeError: 'charmap' codec can't decode byte 0x8f in position 5762: character maps to &lt;undefined&gt; If I looked that up right it is a &amp;lt ctrl &amp;gt. The code below are the relevant lines: with open(file, newline = '') as f: reader = csv.DictReader(f, dialect = 'excel') for line in reader: I know I'm going to be getting a file. I know it will be a .csv. There may be some variance in what I get due to the manual generation/export of the source files. There may also be some strange characters in some of the files (e.g. Japanese, Russian, etc.). I provide this information because going back to the source to get a different file might just kick the can down the road until I have to pull updated data (or worse, someone else does). So the question is probably multi-part: 1) Is there a way to tell the csv.DictReader to ignore undefined characters? (Hint for the codec: if I can't see it, it is of no value to me.) 2) If I do have "crazy" characters, what should I do? I've considered opening each input as a binary file, filtering out offending hex characters, writing the file back to disk and then opening the new file, but that seems like a lot of overhead for the program and even more for me. It's also a few JCL statements from being 1977 again. 3) How do I figure out what I'm getting as an input if it crashes while I'm reading it in. 4) I chose the "dialect = 'excel'"; because many of the inputs are Excel files that can be downloaded from one of the source applications. From the docs on dictreader, my impression is that this just defines delimite…
has comment: http://stackoverflow.com/comment/91124719
tagged with: http://stackoverflow.com/tag/csv
has comment: http://stackoverflow.com/comment/91126555
score: 3
linked to: http://stackoverflow.com/q/30750843
tagged with: python
type: AnsweredQuestion
tagged with: python-3.x

http://stackoverflow.com/comment/91140429
type: AnswerComment
comment on: http://stackoverflow.com/a/52095213
has text: See the dup I found. This happens because the code executed in the REPL.
type: Comment
score: 0

http://stackoverflow.com/comment/90936821
type: Comment
type: QuestionComment
has text: Are you intentionally not allowing repeated values? For example, `(5, 5, 5)` or `(3, 6, 6)`
comment on: http://stackoverflow.com/q/51993466
score: 0

http://stackoverflow.com/q/52065501
possible better answer: http://stackoverflow.com/a/52065597
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/52065592
has title: Add column identifying original data frame when using pd.concat
type: Question
score: 5
upvote count: 5
answer count: 2
tagged with: pandas
has answer: http://stackoverflow.com/a/52065592
has body: I have a dictionary of data frames like the following: test = {'df1':pd.DataFrame({'col1':[3, 5, 1, 4], 'col2':[3, 5, 1, 4]}), 'df2':pd.DataFrame({'col1':[3, 5, 1, 4], 'col2':[3, 5, 1, 4]}), 'df3':pd.DataFrame({'col1':[3, 5, 1, 4], 'col2':[3, 5, 1, 4]}), 'df4':pd.DataFrame({'col1':[3, 5, 1, 4], 'col2':[3, 5, 1, 4]})] I want to concatenate these data frames, but add a new column which gives 'identity' (dictionary key name) of which data frame the value came from. How can this be done? If I do pd.concat(test.values()), I get the concatenation which I want but no identity column. Thanks, Jack
has answer: http://stackoverflow.com/a/52065597
downvote count: 0
favorite count: 0
tagged with: python-3.x

http://stackoverflow.com/q/51987651
has body: I have a dataframe that looks like this: df4 = pd.DataFrame({'Q':['chair', 'desk', '-----monitor', 'chair'], 'R':['red', '-- use blue or dark blue', 'yellow', 'purple'], 'S': ['-- is english spoken?', 'german', 'spanish', 'english']}) Q R S 0 chair Red -- is english spoken? 1 desk -- blue or dark blue german 2 -----monitor yellow spanish 3 chair purple english what I want to be returned: Q R S 3 chair purple english I want to filter out the entire row if any column has a "-" value that appears 2 or more times at the beginning. I found a thread for filtering numerical values, but is there any way to filter out special characters? Particularly with regex? Edit #1: I am only looking to remove rows if "-" appears 2 or more times at the very beginning. If that value appears in the middle of some text, that's fine. Let's say my dataframe looks like this: Q R S 0 chair Red -- is english spoken? 1 desk blue or dark blue ger--man 2 -----monitor yellow spanish 3 chair purple english I would have this returned: Q R S 1 desk blue or dark blue ger--man 3 chair purple english Edit #2: I have tried this: df4[~df4.Q.str.startswith(('--'))] But this only works on 1 column, not all.
type: Question
has answer: http://stackoverflow.com/a/51987693
tagged with: python
answer count: 1
upvote count: 3
accepted answer: http://stackoverflow.com/a/51987693
downvote count: 0
tagged with: pandas
type: AnsweredQuestion
has title: Pandas Filtering Data Based on what appears at the start
score: 3
favorite count: 0
tagged with: python-3.x

http://stackoverflow.com/comment/90988459
type: QuestionComment
comment on: http://stackoverflow.com/q/52019063
has text: open_restaurant will take self as argument or make it static.
score: 0
type: Comment

http://stackoverflow.com/a/52031925
upvote count: 4
has body: I think for loop should be fast enough [[df.loc[z,y] for z,y in zip(x,df.columns)] for x in l ] Out[981]: [[5, 7, 3], [4, 2, 5]]
downvote count: 0
has comment: http://stackoverflow.com/comment/91014539
type: AcceptedAnswer
type: Answer
accepted answer of: http://stackoverflow.com/q/52031908
score: 4
has comment: http://stackoverflow.com/comment/91015574
answers question: http://stackoverflow.com/q/52031908

http://stackoverflow.com/a/52085104
type: Answer
has body: It seems the response you get maybe empty sometimes. I've tried (which can be a possibility within your random range) https://danbooru.donmai.us/posts.json?tags=shimakaze_(kantai_collection)%20rating:s&amp;limit=1000&amp;page=796 and get a response with empty list. So calling on an index with empty list will give you the index error. Check if the response is not empty.
accepted answer of: http://stackoverflow.com/q/52084719
answers question: http://stackoverflow.com/q/52084719
type: AcceptedAnswer
score: 0

http://stackoverflow.com/comment/90962801
type: Comment
has text: Thanks for you answer! I was wondering if I could avoid to create the grid... But i no other solution, I'll accept yours !
type: AnswerComment
comment on: http://stackoverflow.com/a/52006437
score: 0

http://stackoverflow.com/q/52093562
tagged with: python
has title: How to resize my label Tensor so I can us it in tf.nn.sigmoid_cross_entropy_with_logits
score: 1
has comment: http://stackoverflow.com/comment/91151622
tagged with: tensorflow
type: Question
upvote count: 1
has body: I have the following problem: cross_entropy = tf.nn.sigmoid_cross_entropy_with_logits(labels=labels, logits=logits) This gives me tensorflow.python.framework.errors_impl.InvalidArgumentError: Can not squeeze dim[1], expected a dimension of 1, got 18000 for 'remove_squeezable_dimensions/Squeeze' (op: 'Squeeze') with input shapes: [1024,18000] which makes sense because the function expects something one dimensional. So I tried: cross_entropy = tf.nn.sigmoid_cross_entropy_with_logits(labels=tf.argmax(labels, axis=1), logits=logits) which gives me ValueError: logits and labels must have the same shape ((1024, 18000) vs (1024,)) So my labels are just images of a certain size, so I am a bit lost here how I should give the function something onedimensional when my labels have more dimensions :/
favorite count: 0
answer count: 0
downvote count: 0
type: UnansweredQuestion

http://stackoverflow.com/comment/90944863
type: AnswerComment
score: 4
has text: I’m pretty sure should be able to not only write your own answer, but also accept it. If so, you should, for the benefit of future searchers with the same problem, and so people can link future duplicate questions here, and I think you even get some rep points.
type: Comment
comment on: http://stackoverflow.com/a/51997420

brainfuck
tags question: http://stackoverflow.com/q/52003620
type: Tag
tag name: brainfuck

http://stackoverflow.com/q/52109361
has body: I have a Primary dataframe D1: PRCESS_NO VALUE COUNT TIME 18 25855 69 13:41:56 19 10254 8 13:42:14 20 10254 4 13:42:20 21 68522 18 13:42:29 22 68522 75 13:42:33 23 25855 21 13:42:37 24 10254 658 13:42:53 25 10254 84 13:42:59 D2 dataframe: PRCESS_NO VALUE COUNT TIME 21 68522 12 14:32:25 22 68522 10 14:42:39 23 25855 54 14:38:25 I want to update primary dataframe D1 with values from D2 dataframe as per the below mentioned condition: Add the Values of VALUE &amp; COUNT Column (D1.VALUE + D2.VALUE, D1.COUNT + D2.COUNT) Update the D1 TIME Column with Values from D2 TIME Column. Final D1 Dataframe: PRCESS_NO VALUE COUNT TIME 18 25855 69 13:41:56 19 10254 8 13:42:14 20 10254 4 13:42:20 21 68522 30 14:32:25 22 68522 85 14:42:39 23 25855 75 14:38:25 24 10254 658 13:42:53 25 10254 84 13:42:59
tagged with: python
score: 2
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52109571
upvote count: 2
type: Question
has title: Multiple Operation in Pandas dataframe simultaneously
tagged with: dataframe
accepted answer: http://stackoverflow.com/a/52109571
tagged with: pandas
answer count: 1
downvote count: 0
favorite count: 0
tagged with: python-3.x

http://stackoverflow.com/q/52087743
tagged with: python
has body: I'm running Flask Restful on a server in production mode using Python 3.6 and hitting an endpoint that requires jwt auth, but I keep getting a "NoAuthorizationError Missing Authorization Header" error. The strange part is that the very same request is sent using Postman to the local version of the exact same Flask app on my mac and it works just fine without any errors. The problem only occurs on the live server and all of the pip packages are the exact same version as well. UPDATE I am using Gunicorn on the live server and when I stop the app and run normally using python run.py the error goes away and returns the correct response. I have the following handlers set for jwt errors and again, it is caught on the local version of my app: jwt.token_in_blacklist_loader jwt.expired_token_loader jwt.invalid_token_loader jwt.revoked_token_loader jwt.needs_fresh_token_loader jwt.unauthorized_loader jwt.claims_verification_failed_loader For testing purposes I'm not sending a token in the request itself. Even if I do, the error still persists. Here is the response locally on my mac: { "errors": { "application": "Missing Authorization Header", "validation": null }, "http_status": 401, "message": "There was a problem authenticating your token.", "status": 0, "time": 20 } Here is the response on the live server: Aug 29 17:15:15 [5168]: return self.dispatch_request(*args, **kwargs) Aug 29 17:15:15 [5168]: File "/home/domain.com/apps/core-api/env/lib/python3.6/site-packages/flask_restful/__init__.py", line 595, in dispatch_request Aug 29 17:15:15 [5168]: resp = meth(*args, **kwargs) Aug 29 17:15:15 [5168]: File "/home/domain.com/apps/core-api/env/lib/python3.6/site-packages/flask_jwt_extended/view_decorators.py", line 102, in wrapper Aug 29 17:15:15 [5168]: verify_jwt_in_request() Aug 29 17:15:15 [5168]: File "/home/domain.com/apps/core-api/env/lib/python3.6/site-packages/flask_jwt_extended/view_decorators.py", line 31, in verify_jwt_in_request Aug 29 17:15:15 [5168]: jwt_data = _…
tagged with: gunicorn
accepted answer: http://stackoverflow.com/a/52102884
tagged with: jwt
has answer: http://stackoverflow.com/a/52098866
type: AnsweredQuestion
has title: Flask Restful NoAuthorizationError Missing Authorization Header
tagged with: flask-restful
has answer: http://stackoverflow.com/a/52208185
type: Question
upvote count: 4
linked to: http://stackoverflow.com/q/26549250
answer count: 3
possible better answer: http://stackoverflow.com/a/52208185
downvote count: 0
score: 4
tagged with: flask
favorite count: 0
has answer: http://stackoverflow.com/a/52102884

http://stackoverflow.com/comment/91063148
has text: it is giving expected results if both data frame records are in same order. if we change the order of the records in a data frame it won't give the expected result.can you check it once?
comment on: http://stackoverflow.com/a/52052408
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/a/51961443
has body: I'm assuming you're using hunkim's tutorial. mnist.train.next_batch(batch_size) basically returns the next batch to train. This probably would be MNIST CNN/DNN, which means you need the input and the label to feed into the network, namely the image of the handwritten digit (input) and what the correct prediction (label) should be. These respectively are batch_xs and batch_ys. m1.train returns two objects, and the first is the cost of the step. _ is a variable name conventionally used for something that you won't use. avg_cost is printed only after an entire epoch is run. This suggests that avg_cost is the average cost of the epoch. Now, c is the average cost of one step. The total number of steps per epoch is total_batch. Then to compute the average cost of one epoch, you should add all the cs returned every step and divide that by total_batch. This is what's essentially being done; avg_cost += c / total_batch.
answers question: http://stackoverflow.com/q/51961175
type: Answer
score: 3
upvote count: 3
downvote count: 0

http://stackoverflow.com/a/52002678
accepted answer of: http://stackoverflow.com/q/51998936
has body: Since you don't want to increase the figure size, here is a manual cheap hack to get what you want. I am just pasting the code modified. Rest everything stays the same as your code. I also shortened you set_color part at the end. P.S: The width of the bars looks different because of some visualization/saving the figure. On my screen, they all look same width. def autolabel(rects): for i, rect in enumerate(rects): height = rect.get_height() if i == 2 or i ==7: ax.text(rect.get_x() + rect.get_width()/1., 1.07*height, '%.2f' %(height), ha='center', va='bottom') ax.vlines(rect.get_x() + rect.get_width()/3., 1.005*height, 1.07*height, lw=1, color='gray') else: ax.text(rect.get_x() + rect.get_width()/1., 1.01*height, '%.2f' %(height), ha='center', va='bottom') autolabel(rects1) c = 7*['r'] + 5*['g'] + ['b'] for i, r in enumerate(rects1): r.set_color(c[i]) Output
upvote count: 1
type: AcceptedAnswer
type: Answer
answers question: http://stackoverflow.com/q/51998936
downvote count: 0
score: 1

http://stackoverflow.com/comment/90943798
has text: What would be your workaround @hpaulj?
score: 0
comment on: http://stackoverflow.com/q/51996989
type: Comment
type: QuestionComment

http://stackoverflow.com/a/52084845
downvote count: 0
answers question: http://stackoverflow.com/q/52084735
score: 3
has comment: http://stackoverflow.com/comment/91120680
type: AcceptedAnswer
has body: Method 1: Convert df['Date'] to string before giving it to np.is_busday: df['Is_Business_Day'] = [np.is_busday(x) for x in df['Date'].astype(str)] Method 2: You could just use pandas instead of numpy, and check if Date is in the range of business days from your minimum date to your maximum date: bus_days = pd.bdate_range(df['Date'].min(), df['Date'].max()) df['Is_Business_Day'] = df['Date'].isin(bus_days) Examples: &gt;&gt;&gt; df = pd.DataFrame({'Date':pd.date_range(pd.to_datetime('today'), pd.to_datetime('2018-09-15'))}) &gt;&gt;&gt; df Date 0 2018-08-29 1 2018-08-30 2 2018-08-31 3 2018-09-01 4 2018-09-02 5 2018-09-03 6 2018-09-04 7 2018-09-05 8 2018-09-06 9 2018-09-07 10 2018-09-08 11 2018-09-09 12 2018-09-10 13 2018-09-11 14 2018-09-12 15 2018-09-13 16 2018-09-14 17 2018-09-15 You can do: Method 1: &gt;&gt;&gt; df['Is_Business_Day'] = [np.is_busday(x) for x in df['Date'].astype(str)] &gt;&gt;&gt; df Date Is_Business_Day 0 2018-08-29 True 1 2018-08-30 True 2 2018-08-31 True 3 2018-09-01 False 4 2018-09-02 False 5 2018-09-03 True 6 2018-09-04 True 7 2018-09-05 True 8 2018-09-06 True 9 2018-09-07 True 10 2018-09-08 False 11 2018-09-09 False 12 2018-09-10 True 13 2018-09-11 True 14 2018-09-12 True 15 2018-09-13 True 16 2018-09-14 True 17 2018-09-15 False Method 2: &gt;&gt;&gt; bus_days = pd.bdate_range(df['Date'].min(), df['Date'].max()) &gt;&gt;&gt; df['Is_Business_Day'] = df['Date'].isin(bus_days) &gt;&gt;&gt; df Date Is_Business_Day 0 2018-08-29 True 1 2018-08-30 True 2 2018-08-31 True 3 2018-09-01 False 4 2018-09-02 False 5 2018-09-03 True 6 2018-09-04 True 7 2018-09-05 True 8 2018-09-06 True 9 2018-09-07 True 10 2018-09-08 False 11 2018-09-09 False 12 2018-09-10 True 13 2018-09-11 True 14 2018-09-12 True 15 2018-09-13 True 16 2018-09-14 True 17 2018-09-15 False
upvote count: 3
type: Answer
has comment: http://stackoverflow.com/comment/91122938
accepted answer of: http://stackoverflow.com/q/52084735

http://stackoverflow.com/q/52093892
has comment: http://stackoverflow.com/comment/91137766
type: UnansweredQuestion
tagged with: python
has body: In for loop I want store my output in string object. For that i tried the following, But i didn't get a solution. here out is some user_defined function. for i in range(1,2): 'out_put%s'%i+'_ests'=out(data) i can do the same thing in R by using the following code. for(i in c(1,2)) { assign(paste0('out_put',i,'_ests'),out(data)) } Please anyone help me to tackle this. Thanks in advance.
answer count: 0
upvote count: 1
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/91137937
has comment: http://stackoverflow.com/comment/91137858
has comment: http://stackoverflow.com/comment/91138840
has title: Store pandas data in string in python
tagged with: dataframe
score: 0
tagged with: pandas
tagged with: string
favorite count: 0

http://stackoverflow.com/q/52085200
has body: I have the following dataframe of dtype object: col1 col2 col3 0 1.1 3.3 spam 1 2.2 foo eggs 2 bar 4.4 5.5 I would like to cast all the floats to integers then convert everything to strings, so the output would be of dtype string: col1 col2 col3 0 1 3 spam 1 2 foo eggs 2 bar 4 5 Is there something that allows me to cast a dataframe to an int but ignore errors? Or achieve this in a different way? (using the errors = 'ignore', seems to ignore the entire thing)
has title: In dataframe of strings AND floats, cast floats to integer then string
has comment: http://stackoverflow.com/comment/91327673
tagged with: pandas
favorite count: 0
upvote count: 0
possible better answer: http://stackoverflow.com/a/52085314
accepted answer: http://stackoverflow.com/a/52086279
tagged with: python
downvote count: 1
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52086279
tagged with: dataframe
score: -1
type: Question
has answer: http://stackoverflow.com/a/52085314
answer count: 2

http://stackoverflow.com/comment/90872648
type: QuestionComment
has text: pyuic4 -x mainwindow.ui > mainwindow.py also i tried using pycui4 -o mainwindow.ui mainwindow,py
comment on: http://stackoverflow.com/q/51960617
score: 0
type: Comment

http://stackoverflow.com/comment/91053398
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52050282
score: 0
has text: No, there is no keyboard shortcut. Just an area to click to invoke a pop-up to select folder.

http://stackoverflow.com/a/52021212
has comment: http://stackoverflow.com/comment/90993495
has comment: http://stackoverflow.com/comment/90998680
accepted answer of: http://stackoverflow.com/q/52012488
score: 15
has comment: http://stackoverflow.com/comment/90995204
upvote count: 15
answers question: http://stackoverflow.com/q/52012488
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/91046590
has comment: http://stackoverflow.com/comment/91052563
has body: The traceback is generated by asyncio's implementation of the SSL protocol, which invokes the event loop's exception handler. Through a maze of interactions between the transport/protocol and the streaming layers, this exception gets logged by the event loop and propagated to the API user. The way that happens is as follows: An exception occurs during the SSL handshake. SSLProtocol._on_handshake_complete receives non-None handshake_exc and treats it as a "fatal error" (in the handshake context), i.e. invokes self._fatal_error and returns. _fatal_error calls the event loop's exception handler to log the error. The handler is normally invoked for exceptions that occur in queued callbacks where there is no longer a caller to propagate them to, so it just logs the traceback to standard error to ensure that the exception doesn't pass silently. However... _fatal_error goes on to call transport._force_close, which calls connection_lost back on the protocol. The stream reader protocol's connection_lost implementation sets the exception as the result of the stream reader's future, thus propagating it to the users of the stream API that await it. It is not obvious if it is a bug or a feature that the same exception is both logged by the event loop and passed to connection_lost. It might be a workaround for BaseProtocol.connection_lost being defined a no-op, so the extra log ensures that a protocol that simply inherits from BaseProtocol doesn't silence the possibly sensitive exceptions occurring during SSL handshake. Whichever the reason, the current behavior leads to the problem experienced by the OP: catching the exception is not enough to suppress it, a traceback will still be logged. To work around the issue, one can temporarily set the exception handler to one that doesn't report SSLCertVerificationError: @contextlib.contextmanager def suppress_ssl_exception_report(): loop = asyncio.get_event_loop() old_handler = loop.get_exception_handler() old_handler_fn = old_handler o…
has comment: http://stackoverflow.com/comment/91046720
type: Answer

http://stackoverflow.com/comment/91164598
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/52106307
has text: I have edited my question with some improvements now. How Can I implement pcolormesh?
type: Comment

python-imaging-library
tags question: http://stackoverflow.com/q/52100460
tags question: http://stackoverflow.com/q/52027382
tags question: http://stackoverflow.com/q/52016407
tags question: http://stackoverflow.com/q/52091437
tags question: http://stackoverflow.com/q/51996121
tag name: python-imaging-library
tags question: http://stackoverflow.com/q/52029870
type: Tag
tags question: http://stackoverflow.com/q/51966558
tags question: http://stackoverflow.com/q/52065249
tags question: http://stackoverflow.com/q/52085525
tags question: http://stackoverflow.com/q/51979554
tags question: http://stackoverflow.com/q/52053761
tags question: http://stackoverflow.com/q/52060306
tags question: http://stackoverflow.com/q/52000807
tags question: http://stackoverflow.com/q/52037755

http://stackoverflow.com/q/52092917
has body: I have read similar questions but couldn't come to a solution or a conclusion about it. I got this error while creating a new model class in the same app as well as creating a new model class in a new app. The error django.db.utils.IntegrityError: UNIQUE constraint failed: auth_permission.content_type_id, auth_permission.codename my models.py from django.db import models from django.contrib.auth.models import User CHOICES = (('Earned Leave','Earned Leave'),('Casual Leave','Casual Leave'),('Sick Leave','Sick Leave'),('Paid Leave','Paid Leave')) STATUS_CHOICES = (('0', 'Rejected'),('1', 'Accepted'),) MANAGER_CHOICES = (('0001_manager', '0001_manager'),('0002_manager', '0002_manager')) class Leave(models.Model): employee_ID = models.CharField(max_length = 20) name = models.CharField(max_length = 50) user = models.ForeignKey(User, on_delete = models.CASCADE, null =True) def __str__(self): return self.name class B(models.Model): state = models.CharField(max_length=50)
has comment: http://stackoverflow.com/comment/91141704
tagged with: django
tagged with: python
has title: Why I'm getting an error while creating a new model class in django?
accepted answer: http://stackoverflow.com/a/52147939
type: AnsweredQuestion
score: 0
type: Question
has answer: http://stackoverflow.com/a/52147939
has comment: http://stackoverflow.com/comment/91135803
answer count: 1
has comment: http://stackoverflow.com/comment/91135902
tagged with: model

http://stackoverflow.com/q/52096110
score: 0
tagged with: api
tagged with: eve
answer count: 1
linked to: http://stackoverflow.com/q/40681689
has answer: http://stackoverflow.com/a/52100491
type: UnansweredQuestion
duplicate of: http://stackoverflow.com/q/40681689
tagged with: python
type: Question
has title: Python eve api access in client machine
has body: I want to access the rest api of the python eve in client machine. Here is my code, MONGO_HOST = 'localhost' MONGO_PORT = 27017 MONGO_USERNAME = '' MONGO_PASSWORD = '' MONGO_DBNAME = 'test' RESOURCE_METHODS = ['GET', 'POST', 'DELETE'] cust = { 'item_title': 'Custmer Detail', 'cache_control': 'max-age=10,must-revalidate', 'cache_expires': 10, 'resource_methods': ['GET', 'POST'], 'schema': { "CUSTOMERID" : { 'type': 'string' }, "COMPANYNAME": { 'type': 'string' } } } DOMAIN = {'Customers': cust} I get the output in my local machine but I want to know how to configure the Host and Port to access this table in client or another machine.

http://stackoverflow.com/q/51982990
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90925819
type: Question
has title: Training Sci-kit Learn Neural Network with 2D inputs
has body: I am trying to train a neural network using sci-kit learn in Python to recognize shapes in an image. I have a list of points which lie on edges, each edge represented with an x and y coordinate, in the form [x,y]. So, I want to train the net using a list in the format [[x,y],[x,y],[x,y],[x,y],[x,y],[x,y],etc.]. I tried this with the following code, but I get the following error: from sklearn.neural_network import MLPClassifier X = [[[0., 0.], [0., 0.]], [[1., 1.], [1., 1.]]] y = [0, 1] clf = MLPClassifier(solver='lbfgs', alpha=1e-5, hidden_layer_sizes=(5, 2), random_state=1) clf.fit(X, y) ValueError: Found array with dim 3. Estimator expected &lt;= 2. Does anyone have any advice on how I can approach this, if its even possible. By the definition and logic of neural networks, I'm not so sure if it's possible. Please let me know of any advice. Thanks!
has answer: http://stackoverflow.com/a/51983804
accepted answer: http://stackoverflow.com/a/51983804
tagged with: neural-network
tagged with: scikit-learn
score: 0
has comment: http://stackoverflow.com/comment/90916038
answer count: 1
favorite count: 0
upvote count: 1
tagged with: machine-learning
tagged with: python
downvote count: 1

http://stackoverflow.com/a/52052408
type: Answer
has comment: http://stackoverflow.com/comment/91066431
has comment: http://stackoverflow.com/comment/91063148
downvote count: 0
has body: Use merge with left join first, get columns names of added columns from df2 and filter out all non NaNs rows by them: df = df1.merge(df2, on=['x1', 'x2', 'x3'], how='left', suffixes=('','_')) print (df) x1 x2 x3 x4 x5 x6 x4_ x5_ 0 SM 1 1 2 3 3 3.0 3.0 1 RK 2 2 3 4 5 NaN NaN 2 NB 1 2 2 5 6 3.0 2.0 3 CB 2 5 6 7 8 NaN NaN 4 VSB 5 6 4 2 1 3.0 2.0 5 SB 6 2 3 2 1 4.0 1.0 cols = df.columns.difference(df1.columns) print (cols) Index(['x4_', 'x5_'], dtype='object') df = df.loc[df[cols].isnull().all(axis=1), df1.columns.tolist()] print (df) x1 x2 x3 x4 x5 x6 1 RK 2 2 3 4 5 3 CB 2 5 6 7 8 EDIT: With your sample data I get: df = df1.merge(df2, on=['x1', 'x2', 'x3'], how='left', suffixes=('','_')) print (df) x1 x2 x3 x4 x5 x6 x4_ x5_ 0 SM 1 1 2 3 3 3.0 3.0 1 RK 2 2 3 4 5 NaN NaN 2 NBR 1 2 2 5 6 NaN NaN 3 CBK 2 5 6 7 8 NaN NaN 4 VSB 5 6 4 2 1 3.0 2.0 5 SB 6 2 3 2 1 4.0 1.0 cols = df.columns.difference(df1.columns) print (cols) Index(['x4_', 'x5_'], dtype='object') df = df.loc[df[cols].isnull().all(axis=1), df1.columns.tolist()].x1.tolist() print (df) x1 x2 x3 x4 x5 x6 1 RK 2 2 3 4 5 2 NBR 1 2 2 5 6 3 CBK 2 5 6 7 8
has comment: http://stackoverflow.com/comment/91063444
has comment: http://stackoverflow.com/comment/91064257
answers question: http://stackoverflow.com/q/52042732
score: 1
has comment: http://stackoverflow.com/comment/91067228
has comment: http://stackoverflow.com/comment/91064107
upvote count: 1
has comment: http://stackoverflow.com/comment/91064687
has comment: http://stackoverflow.com/comment/91063412
has comment: http://stackoverflow.com/comment/91063188
has comment: http://stackoverflow.com/comment/91064205
has comment: http://stackoverflow.com/comment/91066516

http://stackoverflow.com/comment/91084914
score: 0
type: Comment
type: QuestionComment
has text: Can you please explain downvotes when leaving them?
comment on: http://stackoverflow.com/q/52067136

http://stackoverflow.com/a/51989053
type: Answer
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/51988800
has comment: http://stackoverflow.com/comment/90936006
downvote count: 0
has body: For the first question, you could sort the zip of both lists, i.e. sort a list of tuple: indexList = [5,3,2,2,7,1] valueList = [1,2,3,4,5,6] sorted(zip(indexList, valueList)) # [(1, 6), (2, 3), (2, 4), (3, 2), (5, 1), (7, 5)] Quote from this answer: Python sorts tuples and lists like these lexicographically; compare the first element, and only if that doesn't differ, compare the second element, etc. And if you want to pack the values again into two lists: indexList, valueList = list(zip(*sorted(zip(indexList, valueList)))) print( indexList, valueList ) # (1, 2, 2, 3, 5, 7) (6, 3, 4, 2, 1, 5)

http://stackoverflow.com/q/52080433
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91110849
has answer: http://stackoverflow.com/a/52080465
has comment: http://stackoverflow.com/comment/91110824
has title: Listing 2 items at once using short version of list-making python
type: Question
has comment: http://stackoverflow.com/comment/91111040
score: 0
answer count: 1
linked to: http://stackoverflow.com/q/18072759
tagged with: python
has body: Is there a way to list 2 items at one line using the short version of making lists. For example I want to write something like G3 = [(i,j) for i in Primes and j in G2 if dig_sum(i,j) == True and con_test(i,j) == True ] Edit: I should have mentioned this gives me error of NameError: name 'j' is not defined here i is an int and j is tuple My main purpose is to get something like G = [(i,j,k),(g,h,k)...] I know that my uppser code will give something like G = [(i,(j,k)),(g,(h,k))...] but I can change it later I guess. Here is the long version G3 = [] for i in Primes: for j in G2: if dig_sum(i,j) == True and con_test(i,j) == True: G3.append((i,j[0],j[1])) print(G3)

temperature
tags question: http://stackoverflow.com/q/52003609
type: Tag
tags question: http://stackoverflow.com/q/52098988
tag name: temperature

http://stackoverflow.com/q/52105389
tagged with: scipy
has title: Reproduce Matlab's SVD in python
tagged with: numpy
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/91162326
favorite count: 0
has answer: http://stackoverflow.com/a/52105622
tagged with: python
tagged with: svd
upvote count: 3
accepted answer: http://stackoverflow.com/a/52105622
tagged with: matlab
type: Question
type: AnsweredQuestion
score: 3
has body: I'm trying to reproduce some large project that was written in Matlab, using python. I managed to reproduce most of the results, but I have a problem specifically with SVD decomposition. (I'm looking only on the last, V, part.) In Matlab: [~, ~, V] = svd([4.719, -17.257, -11.5392; -17.2575, 63.9545, 40.5581; -11.5392, 40.5581, 31.3256]); This gets me the following V: -0.2216 0.0241 -0.9748 0.8081 -0.5549 -0.1974 0.5457 0.8316 -0.1035 in numpy: np.linalg.svd(np.array([[4.71993, -17.2575, -11.539], [-17.257, 63.954, 40.558], [-11.539, 40.558, 31.325]]))[2] Gets me: array([[-0.22159139, 0.80814521, 0.54570924], [ 0.02407525, -0.55491709, 0.83155722], [ 0.97484237, 0.19740401, 0.10350855]]) Which is transposed (as I think is expected between numpy and matlab) but also different on some minus signs. even using opencv (cv2) or scipy (even with lapack_driver="gesvd") still gets the same result scipy.linalg.svd(np.array([[4.71993, -17.2575, -11.539], [-17.257, 63.954, 40.558], [-11.539, 40.558, 31.325]]), lapack_driver="gesvd")[2] I also tried to transpose the input matrix, which didn't change much. I understand that both answers are correct. But I really need to get the exact same result to be able to reproduce the project.

python-watchdog
tags question: http://stackoverflow.com/q/51986961
tags question: http://stackoverflow.com/q/52099156
tag name: python-watchdog
type: Tag

http://stackoverflow.com/q/52046179
has title: How to auto "OK" or bypass pop up message in Excel with win32com in Python?
score: 2
has comment: http://stackoverflow.com/comment/91043544
favorite count: 0
tagged with: python-3.x
upvote count: 2
type: UnansweredQuestion
tagged with: python
tagged with: excel
tagged with: win32com
has answer: http://stackoverflow.com/a/77527309
has comment: http://stackoverflow.com/comment/91043697
type: Question
downvote count: 0
answer count: 1
linked to: http://stackoverflow.com/q/20278363
has body: I'm attempting to change the file types of a large group of .xls files to .xlsm, and keep getting pop up messages that I have to "OK" or "YES" out of before the script proceeds. I've already attempted the time.sleep SendKeys method, and the "ENTER" command does not register in the window created by Excel. I've also attempted DisplayAlerts = False, but no luck with that either. Below is the code I've used with the comment lines being what I attempted: os.chdir(r'C:\my\directory\location') doc_path = r'C:\my\directory\location' for root, dirs, files in os.walk(doc_path, topdown=False): for file in files: fname = file if fname.endswith('.xls'): excel = win32.gencache.EnsureDispatch('Excel.Application') #excel.DisplayAlerts = False wb = excel.Workbooks.Open(os.path.abspath(fname)) #time.sleep(4) #excel.SendKeys("~",0) #excel.DisplayAlerts = False wb.SaveAs(fname+"m", FileFormat = 52) #excel.DisplayAlerts = False wb.Close() #excel.DisplayAlerts = False excel.Application.Quit() #excel.DisplayAlerts = False else: continue Any insight on how I might be able to solve this?

http://stackoverflow.com/a/52040893
has comment: http://stackoverflow.com/comment/91032946
upvote count: 1
has body: Welcome to StackOverflow! This code worked for me: [div.find("div", {"class": "inner"}) for div in soup.findAll("div", {"class": "outer"})] That is, a one-line version of the same thing.
has comment: http://stackoverflow.com/comment/91032717
has comment: http://stackoverflow.com/comment/91033144
has comment: http://stackoverflow.com/comment/91032984
type: Answer
answers question: http://stackoverflow.com/q/52040677
has comment: http://stackoverflow.com/comment/91032799
has comment: http://stackoverflow.com/comment/91033091
downvote count: 0
score: 1

google-api-python-client
tags question: http://stackoverflow.com/q/52071239
tags question: http://stackoverflow.com/q/52091664
type: Tag
tags question: http://stackoverflow.com/q/52057302
tag name: google-api-python-client
tags question: http://stackoverflow.com/q/51968495
tags question: http://stackoverflow.com/q/52047974
tags question: http://stackoverflow.com/q/52031044
tags question: http://stackoverflow.com/q/52085054

http://stackoverflow.com/a/52151959
type: Answer
has comment: http://stackoverflow.com/comment/91260316
score: 2
downvote count: 0
has body: As described in the comments above, I made you some sample code. It is based on Redis and I am suggesting you run Redis on your cluster manager node which is presumably close to the nodes of your cluster and always up - so a good candidate for a statistics gathering service. The sample code is a dummy job, written in Python, and a monitoring routine written in bash, but the job could just as easily be written in C/C++ and the monitoring routine in Perl - there are all sorts of bindings for Redis - don't get hung up on a language. Even if you can't read Python, it is very easy to understand. There are 3 threads that run in parallel. One just updates a string in Redis with the total elapsed processing time. The other two update Redis lists with time series data - a synthesised triangular wave - one running at 5 Hz and the other at 1 Hz. I used a Redis string where variables don't need to record a history and a Redis list where a history is needed. Other data structures are available. In the code below, the only 3 interesting lines are: # Connect to Redis server by IP address/name r = redis.Redis(host='localhost', port=6379, db=0) # Set a Redis string called 'processTime' to value `processsTime` r.set('processTime', processTime) # Push a value to left end of Redis list r.lpush(RedisKeyName, value) Here is the dummy job that is being monitored. Start reading where it says ###### # Main ###### Here is the code: #!/usr/local/bin/python3 import redis import _thread import time import os import random ################################################################################ # Separate thread periodically updating the 'processTime' in Redis ################################################################################ def processTimeThread(): """Calculate time since we started and update every so often in Redis""" start = time.time() while True: processTime = int(time.time() - start) r.set('processTime', processTime) time.sleep(0.2) #################################…
answers question: http://stackoverflow.com/q/52074716
upvote count: 2

http://stackoverflow.com/a/51984452
has comment: http://stackoverflow.com/comment/90918237
has body: the key driverId is nested within array with Results which in turn is inside Races which in turn is inside RaceTable that is inside MRData. So to get the first driveId you'll have to use the following code print(data['MRData']['RaceTable']['Races'][0]['Results'][0]['Driver']["driverId"]) If you want get all the values of driverId then you'll write a for loop for driver in data['MRData']['RaceTable']['Races'][0]['Results']: print(driver['Driver']["driverId"])
accepted answer of: http://stackoverflow.com/q/51984318
upvote count: 2
answers question: http://stackoverflow.com/q/51984318
type: Answer
has comment: http://stackoverflow.com/comment/90920001
score: 2
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/90920246

http://stackoverflow.com/comment/119427327
score: 0
has text: `# input_shape = (64,64,1)` `input_tensor = Input(shape=image_shape)` `model_input = Conv2D(filters = 3, kernel_size=3, padding='same', name="input_conv")(input_tensor)` Now I import the VGG16 model `vgg16 = VGG16(include_top=False, weights='imagenet',input_tensor=model_input)` Then I try to add a Conv layer `X = Conv2D(channels, kernel_size=3, padding='same')(vgg16.output)` `X = Activation('tanh')(X)` And the final model: `model = Model(inputs = input_tensor, outputs = X)`
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/59959369

http://stackoverflow.com/comment/91030468
has text: A good way to see the efficiency of the network is to print the losses of the discriminator and the generator. Post the pictures
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52035918

http://stackoverflow.com/comment/91184908
has text: it does work for me, however I noticed iframe disappears from the screen if I use url with 'page-10' at the end. I was trying with 'page-1' at the end and it worked fine for me. Don't forget to add wait time as Andersson suggested. I will update my answer with what I tried. Another thing to note, I have tried it in Firefox not Safari, you may have check wait time if its still not working for you.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52103914
type: Comment

http://stackoverflow.com/a/51992041
type: Answer
upvote count: 4
has comment: http://stackoverflow.com/comment/90934335
has comment: http://stackoverflow.com/comment/90933911
has comment: http://stackoverflow.com/comment/90934736
score: 4
has body: Do this elementwise using a list comprehension. df[[y.lower() in x.lower() for x, y in zip(df['everything'], df['searching_for'])]] Or, dfy.lower() in x.lower() for x, y in df'everything', 'searching_for'.values.tolist() file_names searching_for everything 0 a.txt where Dave Ran Away. Where is Dave? 1 a.txt candy mmmm, candy 3 b.txt where where the red fern grows
has comment: http://stackoverflow.com/comment/90934802
answers question: http://stackoverflow.com/q/51991966
has comment: http://stackoverflow.com/comment/90933848
downvote count: 0
has comment: http://stackoverflow.com/comment/90934267

http://stackoverflow.com/q/52081929
has comment: http://stackoverflow.com/comment/91125507
score: 15
has answer: http://stackoverflow.com/a/67112402
tagged with: pdb
possible better answer: http://stackoverflow.com/a/52100128
upvote count: 15
answer count: 2
has comment: http://stackoverflow.com/comment/91136646
downvote count: 0
has comment: http://stackoverflow.com/comment/91114386
favorite count: 0
tagged with: exception
tagged with: python
accepted answer: http://stackoverflow.com/a/67112402
has title: Pdb go to a frame in exception within exception
type: Question
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52100128
has comment: http://stackoverflow.com/comment/91133758
has body: I am debugging a program named a.py using pdb def f(x) : x / x def g(x) : try : f(x) except Exception as e : assert 0 g(0) When I run the program using python3 -m pdb a.py, the program stops at assert 0 line, and I get the following error information: Traceback (most recent call last): File "/tmp/a.py", line 6, in g f(x) File "/tmp/a.py", line 2, in f x / x ZeroDivisionError: division by zero During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/usr/lib64/python3.6/pdb.py", line 1667, in main pdb._runscript(mainpyfile) File "/usr/lib64/python3.6/pdb.py", line 1548, in _runscript self.run(statement) File "/usr/lib64/python3.6/bdb.py", line 434, in run exec(cmd, globals, locals) File "&lt;string&gt;", line 1, in &lt;module&gt; File "/tmp/a.py", line 11, in &lt;module&gt; g(0) File "/tmp/a.py", line 9, in g assert 0 AssertionError and the stack is (shown using bt command): (Pdb) bt /usr/lib64/python3.6/pdb.py(1667)main() -&gt; pdb._runscript(mainpyfile) /usr/lib64/python3.6/pdb.py(1548)_runscript() -&gt; self.run(statement) /usr/lib64/python3.6/bdb.py(434)run() -&gt; exec(cmd, globals, locals) &lt;string&gt;(1)&lt;module&gt;()-&gt;None /tmp/a.py(11)&lt;module&gt;()-&gt;None -&gt; g(0) &gt; /tmp/a.py(9)g() -&gt; assert 0 (Pdb) The problem is, I cannot go to function f to debug x / x simply using up and down, because my stack ends at the g function. How should I debug such exceptions within exceptions? What about exceptions within exceptions within exceptions ...?

http://stackoverflow.com/a/51978685
downvote count: 0
has comment: http://stackoverflow.com/comment/90907111
answers question: http://stackoverflow.com/q/51978420
upvote count: 2
type: Answer
score: 2
has comment: http://stackoverflow.com/comment/90907383
has body: You can use set differencing df'start', 'end'.agg(set,1) - df.data.transform(lambda k: set([item for z in k for item in z])) 1 {} 2 {2004} 3 {2001} dtype: object
has comment: http://stackoverflow.com/comment/90907087
has comment: http://stackoverflow.com/comment/90907150

http://stackoverflow.com/comment/91121325
has text: @mir Sorry for misinterpreting. I edited the answer.
comment on: http://stackoverflow.com/a/52084512
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/a/52094193
upvote count: 5
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/52094075
has body: Simply: yes, there is a definite difference, and b.a_id is faster than b.a.id. The latter retrieves the entire a object from the database as an additional query. (You can save that query by adding .select_related('a'), but doing .a.id instead of .a_id is still unnecessary.)
score: 5
type: Answer
accepted answer of: http://stackoverflow.com/q/52094075

http://stackoverflow.com/q/52050924
possible better answer: http://stackoverflow.com/a/52051039
has comment: http://stackoverflow.com/comment/91052048
has title: Find and replace strings in a dataframe
tagged with: python
has body: Hi I want to find specific terms within a dataframe values then replace them by matching with dictionary keys. The dataframe: Search term Application safe high school trip 1 spring break trips 2 gap year trips 1 I have a list of words that I want to replace in a dictionary, keys are the terms to find then replace by the values. {'high school': ['high-school'], 'spring break': ['spring-break'], 'gap year': ['gap-year']} Idea output: Search term Application safe high-school trip 1 spring-break trips 2 gap-year trips 1 I cannot find a way to replace part of the string within a dataframe value so at the moment I read dataframes as strings with open('df.csv','r',encoding='UTF-8') as f: s = f.read() + '\n' then using str.replace to replace them one by one like this, it does the job but inefficient. s = str.replace(s, 'gap year', 'gap-year') If there is a way to replace spaces in specific terms by "-", then using dictionary is unnecessary Thank you
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/52051041
type: Question
has answer: http://stackoverflow.com/a/52051041
tagged with: dataframe
score: 0
has answer: http://stackoverflow.com/a/52051039
answer count: 2

http://stackoverflow.com/q/52007247
accepted answer: http://stackoverflow.com/a/52016792
linked to: http://stackoverflow.com/q/8560440
tagged with: unique
has comment: http://stackoverflow.com/comment/90968553
upvote count: 2
has comment: http://stackoverflow.com/comment/90970708
tagged with: python
has body: I have a mesh of triangles stored in numpy. Some triangles are duplicates and I want to remove them. An example of my numpy array: # Some points a=(-2,-2,0) b=(1,-2,0) c=(1, 1,0) d=(-2,1,0) e=(-2,-2,1) f=(1,-2,1) g=(1,1,1) h=(-2,1,1) # Some triangles t1=(a,b,c) t2=(c,d,a) t3=(e,f,g) t4=(g,h,e) # The numpy array with duplicated t1 and t3 points=numpy.array([t1,t2,t3,t4,t1,t3]) I tried using intersect1d and unique but could not figure out a way to remove all triangles which occure more than once. What am I missing?
score: 2
type: AnsweredQuestion
tagged with: mesh
type: Question
tagged with: numpy
possible better answer: http://stackoverflow.com/a/52008252
downvote count: 0
has answer: http://stackoverflow.com/a/52008252
favorite count: 0
has answer: http://stackoverflow.com/a/52016792
has answer: http://stackoverflow.com/a/52009116
has title: Numpy unique triangles in mesh
has comment: http://stackoverflow.com/comment/90965117
answer count: 3
has comment: http://stackoverflow.com/comment/90968675

http://stackoverflow.com/q/52043920
downvote count: 0
has comment: http://stackoverflow.com/comment/91039153
score: 1
has comment: http://stackoverflow.com/comment/91039189
has comment: http://stackoverflow.com/comment/91038888
type: Question
has title: Specific Columns Operation in Excel using Pandas
has answer: http://stackoverflow.com/a/52044165
has comment: http://stackoverflow.com/comment/91039271
possible better answer: http://stackoverflow.com/a/52044073
has comment: http://stackoverflow.com/comment/91039182
has answer: http://stackoverflow.com/a/52044282
accepted answer: http://stackoverflow.com/a/52044282
has body: I have excel(test.xlsx) sheet having multiple columns,col1,col2,col3,col4 and so on.. I want to perform some operation on col2,col3 and then the output output.xlsx having all the columns again with the updated col2,col3.. What I was trying.. df = pd.read_xlsx('test.xlsx') col = ['col2','col3'] df_with_some_operation = df[col].&lt;some_op&gt; df_with_some_operation.to_excel(output.xlsx) Need help on this code so that all the columns including col2,col3 get included in final output.xlsx For better visualisation ... Check below, I do not want to change the column names, only want to update the content.. I picked this example to made it simplify .. col2 and col3 - > multiplied by 2 . just a note, there are multiple columns in actual, but only on 2 I have to do some work.. input.xlsx col1 col2 col3 1 2 3 output.xls col1 col2 col3 1 4 6
answer count: 3
tagged with: pandas
upvote count: 1
has comment: http://stackoverflow.com/comment/91038949
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/91038992
has answer: http://stackoverflow.com/a/52044073
has comment: http://stackoverflow.com/comment/91038916
tagged with: python
has comment: http://stackoverflow.com/comment/91039098
tagged with: excel
type: AnsweredQuestion

http://stackoverflow.com/comment/90950884
score: 0
has text: Can you add some code so it's clear what you've done so far and what you're trying to do.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52000882

http://stackoverflow.com/a/52099937
has comment: http://stackoverflow.com/comment/91150819
upvote count: 3
accepted answer of: http://stackoverflow.com/q/52099796
type: AcceptedAnswer
downvote count: 0
has body: From the docs (emphasis mine): Numbers are created by numeric literals or as the result of built-in functions and operators. Unadorned integer literals (including hex, octal and binary numbers) yield integers. Source: https://docs.python.org/3.5/library/stdtypes.html#numeric-types-int-float-complex
has comment: http://stackoverflow.com/comment/91159670
answers question: http://stackoverflow.com/q/52099796
type: Answer
score: 3

http://stackoverflow.com/q/52059580
upvote count: 3
tagged with: tensorflow
type: Question
score: 3
tagged with: time-series
tagged with: lstm
downvote count: 0
tagged with: keras
has body: I am working on a path prediction problem where I am predicting the path (Latitude, Longitude) one time step ahead. I have the path data for nearly 1500 "events", which I use for training the LSTM model. For training, since I know the path a priori, I shift the time series by one step, and use it as a target vector. For example: Event 1: Lat (t), Lon (t) --> Lat (t+1), Lon (t+1) Lat (t+1), Lon (t+1) --> Lat (t+2), Lon (t+2) However, for testing since the path is not known a priori, I take the trained LSTM model, and predict one time step at a time, and feed the predicted value as an input for the next time step. Below are the snippets from my code- # Extract only the Lat, Lon values to arrays train_full = train_df'LatNor','LonNor','LatLag1Nor','LonLag1Nor'.values test_full = test_df'LatNor','LonNor','LatLag1Nor','LonLag1Nor'.values print('train_full.shape = ', train_full.shape) print('test_full.shape = ', test_full.shape) # Separate the Inputs and Targets x_train_full = train_full[:,0:2] y_train_full = train_full[:,2:4] x_test_full = test_full[:,0:2] y_test_full = test_full[:,2:4] # Defining the LSTM model model = Sequential() model.add(LSTM(40,input_shape=(None,2), return_sequences=True)) model.add(Dropout(0.1)) model.add(LSTM(20,input_shape=(None,2), return_sequences=True)) model.add(Dropout(0.1)) model.add(Dense(2)) model.add(Activation('linear')) model.compile(loss='mean_squared_error', optimizer='rmsprop', metrics=['accuracy']) model.summary() epochs = 50 for i in range(epochs): print ('Running Epoch No: ', i) for stormID, data in train_df.groupby('EventID'): train = data'LatNor','LonNor','LatLag1Nor','LonLag1Nor' train = train.values x_train = np.expand_dims(train[:,0:2], axis=0) y_train = np.expand_dims(train[:,2:4], axis=0) #print (x_train.shape, y_train.shape) model.train_on_batch(x_train,y_train) model.reset_states() print('Model training done.....') #Use the optimized weights to estimate target values for training data train_pred = new_model.p…
favorite count: 0
has comment: http://stackoverflow.com/comment/91162860
type: UnansweredQuestion
tagged with: python
has title: Time series prediction using LSTM - batch train and real-time prediction
answer count: 0

http://stackoverflow.com/a/51991573
accepted answer of: http://stackoverflow.com/q/51991483
score: 3
upvote count: 3
has comment: http://stackoverflow.com/comment/90933511
has body: Using str.contains for case insensitive selection, and assignment with loc. dfn.loc[dfn.c2.str.contains(r'\.Edu', case=False), 'c2'] = 'Edu' dfn c1 c2 0 10 gedua.com 1 11 Edu 2 12 Edu If it's only the emails ending with .edu you want to replace, then dfn.loc[dfn.c2.str.contains(r'\.Edu$', case=False), 'c2'] = 'Edu' Or, as suggested by piR, dfn.loc[dfn.c2.str.endswith('.Edu'), 'c2'] = 'Edu' dfn c1 c2 0 10 gedua.com 1 11 Edu 2 12 wewewe.edu.ney
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/51991483
type: Answer

http://stackoverflow.com/comment/90998018
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52014619
has text: thinking I could get this done using a meta class, though I am under the impression I shouldn't use these if it can be done using inheritance.

http://stackoverflow.com/a/52167159
downvote count: 0
upvote count: 6
type: Answer
answers question: http://stackoverflow.com/q/52093695
has comment: http://stackoverflow.com/comment/136700171
score: 6
has body: Normally if you chose a large learning rate you may have a similar problem. I have tried to examine your code and my observations are: your cost function J seems alright. but in your backwards function you seem to subtract your actual results from your guesses. By doing so you may get negative weights and since you are subtracting multiplication of your learning rate and your rate from the weights and gradients you end up getting increased cost function results

http://stackoverflow.com/comment/91167016
type: QuestionComment
comment on: http://stackoverflow.com/q/52065812
type: Comment
has text: @JoshRumbut thanks. What I'm seeing now does not seem to suggest an undertrain/overtrain issue (edited the OP with more info), I think it's more likely to be related to an activation or regularization.
score: 0

http://stackoverflow.com/a/52059995
has comment: http://stackoverflow.com/comment/91071252
has body: try with // and % operators! for //, you would do Result = (Input // Multiple) * Multiple This way you get how many times Multiple Fits into Input - this number is then multiplied with the Multiple itself and therefore gives you the expected results! EDIT: how to do it with modulo %? Result = Input - (Input % Multiple) taken from MCO's answer!
answers question: http://stackoverflow.com/q/52059934
downvote count: 0
has comment: http://stackoverflow.com/comment/91070720
has comment: http://stackoverflow.com/comment/91070807
type: Answer
has comment: http://stackoverflow.com/comment/91070839
score: 8
upvote count: 8
has comment: http://stackoverflow.com/comment/91070679

http://stackoverflow.com/comment/90963405
comment on: http://stackoverflow.com/a/52005031
type: Comment
has text: use order = 5, and check
score: 0
type: AnswerComment

http://stackoverflow.com/comment/90920940
comment on: http://stackoverflow.com/q/51985766
score: 1
has text: Just add `np.array` for you dict values.
type: Comment
type: QuestionComment

http://stackoverflow.com/a/52031021
has comment: http://stackoverflow.com/comment/91012577
score: 0
upvote count: 1
type: Answer
downvote count: 1
answers question: http://stackoverflow.com/q/52030954
has comment: http://stackoverflow.com/comment/91013000
has body: in this order: File---settings---project:xxx---project Interpreter--(choose your dir) in the right have a project Interpreter,choose your python

http://stackoverflow.com/q/52060483
type: Question
has title: Approach of training a large image data set using keras, running out of memory
has comment: http://stackoverflow.com/comment/91895983
has comment: http://stackoverflow.com/comment/91873307
downvote count: 0
score: 1
tagged with: keras
has comment: http://stackoverflow.com/comment/91141804
tagged with: deep-learning
has comment: http://stackoverflow.com/comment/91570371
tagged with: python
favorite count: 0
has body: I'm new in computer vision and ML area, I'm trying to develop an image recognition model that I'm training with a large data set of images (50 000 images, 18 GB in size) but on a laptop like Acer Predator that has 16 GB memory and 7th gen Core i7 cpu, GTX 1060 Nvidia, I'm running out of memory even though I'm using GPU on tensorflow. If I train this model with few images like 2000, to 4000 then it's working fine. It seems there is some wrong approach I'm using to train this model but I'm not able to figure out the right approach. I think if I load images into small multiple batches and then train then it could help but I don't know how to achieve this. Below is the code snippet of my train model request. My train.py is as below import matplotlib matplotlib.use("Agg") from keras.preprocessing.image import ImageDataGenerator from keras.optimizers import Adam from keras.preprocessing.image import img_to_array from keras.preprocessing import image from sklearn.preprocessing import MultiLabelBinarizer from sklearn.model_selection import train_test_split from pyimagesearch.smallervggnet import SmallerVGGNet import matplotlib.pyplot as plt from imutils import paths import numpy as np import random import pickle import os import json import tensorflow as tf with tf.device('/device:CPU:0'): a = tf.constant([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], shape=[2, 3], name='a') b = tf.constant([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], shape=[3, 2], name='b') c = tf.matmul(a, b) #config = tf.ConfigProto(log_device_placement=True) session = tf.Session(config=tf.ConfigProto(log_device_placement=True)) print(session.run(c)) with open('conf/conf.json') as f: config = json.load(f) # config variables dataset = config["dataset"] model_path = config["model"] labelbin = config["labelbin"] plot = config["plot"] test_image = config["test_image"] print('dataset: %s '+dataset) EPOCHS = 75 INIT_LR = 1e-3 BS = 32 IMAGE_DIMS = (96, 96, 3) # grab the image paths and randomly shuffle them print("[INFO] loading images...…
answer count: 0
has comment: http://stackoverflow.com/comment/91141895
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91255647
has comment: http://stackoverflow.com/comment/91462758
tagged with: machine-learning
upvote count: 1
tagged with: computer-vision
has comment: http://stackoverflow.com/comment/91570516
has comment: http://stackoverflow.com/comment/91131136
has comment: http://stackoverflow.com/comment/91072057

http://stackoverflow.com/a/52081682
has comment: http://stackoverflow.com/comment/91114399
has comment: http://stackoverflow.com/comment/91114312
has comment: http://stackoverflow.com/comment/91113753
upvote count: 3
answers question: http://stackoverflow.com/q/52081588
has comment: http://stackoverflow.com/comment/91113778
has body: You can create a series of your code-value pairs, and use that to map: my_map = df[df['value'].notnull()].set_index('code')['value'].drop_duplicates() df['value'] = df['code'].map(my_map) &gt;&gt;&gt; df code value 0 1 red 1 2 blue 2 3 yellow 3 1 red 4 4 pink 5 4 pink 6 2 blue Just to see what is happening, you are passing the following series to map: &gt;&gt;&gt; my_map code 1 red 2 blue 3 yellow 4 pink Name: value, dtype: object So it says: "Where you find 1, give the value red, where you find 2, give blue..."
type: Answer
score: 3
downvote count: 0
has comment: http://stackoverflow.com/comment/91113700

http://stackoverflow.com/q/52086652
type: AnsweredQuestion
tagged with: snakemake
type: Question
has answer: http://stackoverflow.com/a/52087224
accepted answer: http://stackoverflow.com/a/52087224
score: 0
has title: Snakemake rule is not picked up and can not specify the output files
answer count: 1
has body: I have a folder where the outputs of the rule are generated. I am having a real trouble running snakemake with it. If I do not specify the outputs in rule all, the rule (called neo4j) is not run at all. If I try running it manually with snakemake neo4j (which I would prefer not to), then I get an error: WorkflowError: Target rules may not contain wildcards. Please specify concrete files or a rule without wildcards. I tried specifying the outputs of the rule in different ways but none of them worked. Using expand: expand('results/neo4j/{sample}/cells.csv', sample=samples), expand('results/neo4j/{sample}/genes.csv', sample=samples), expand('results/neo4j/{sample}/cl_nodes.csv', sample=samples), expand('results/neo4j/{sample}/cl_contains.csv', sample=samples), expand('results/neo4j/{sample}/cl_isin.csv', sample=samples), expand('results/neo4j/{sample}/expr_by.csv', sample=samples), expand('results/neo4j/{sample}/expr_ess.csv', sample=samples) Generates a very weird error for a completely different unrelated rule (called umap): Missing input files for rule umap: data_files/normalized/minus_2/cl_nodes.csv.csv The path generation is completely messed up even though the folders are not connected in any way except for the results being the root folder of all of the outputs. Using dynamic: dynamic('results/neo4j/{sample}/cells.csv', sample=samples), dynamic('results/neo4j/{sample}/genes.csv', sample=samples), dynamic('results/neo4j/{sample}/cl_nodes.csv', sample=samples), dynamic('results/neo4j/{sample}/cl_contains.csv', sample=samples), dynamic('results/neo4j/{sample}/cl_isin.csv', sample=samples), dynamic('results/neo4j/{sample}/expr_by.csv', sample=samples), dynamic('results/neo4j/{sample}/expr_ess.csv', sample=samples) Gives an error: dynamic() got an unexpected keyword argument 'sample' Ok, I tried removing sample=samples but no luck Just directory: directory('results/neo4j/{sample}/', sample=samples) Gives error: directory() got an unexpected keyword argument 'sample' …
linked to: http://stackoverflow.com/q/52088953
has comment: http://stackoverflow.com/comment/91126688
tagged with: python
has comment: http://stackoverflow.com/comment/91127516

http://stackoverflow.com/q/52102616
tagged with: h5py
has answer: http://stackoverflow.com/a/52340477
tagged with: python
type: AnsweredQuestion
tagged with: hdf5
type: Question
has body: Im currently working on a program that converts text files and jpg-images into the HDF5-Format. Opened with the HDFView 3.0, it seems that the Images are only saved in greyscales. hdf = h5py.File("Sample.h5") img = Image.open("Image.jpg") data = np.asarray((img), dtype="uint8") hdf.create_dataset("Photos/Image 1", data=data, dtype='uint8') dset = hdf.get("Photos/Image 1") dset.attrs['CLASS'] = 'IMAGE' dset.attrs['IMAGE_VERSION'] = '1.2' arr = np.asarray([0, 255], dtype=np.uint8) dset.attrs['IMAGE_MINMAXRANGE'] = list(arr) dset.attrs['IMAGE_SUBCLASS'] = 'IMAGE_TRUECOLOR' dset.attrs['INTERLACE_MODE'] = 'INTERLACE_PIXEL' In python it is possible to show the original colored image with the Image.show() method: hdf = h5py.File("Sample.h5") array = np.array(list(hdf.get("Photos/Image 1"))) img = Image.fromarray(array.astype('uint8')) img.show()
tagged with: hdf
score: 4
tagged with: image
upvote count: 4
accepted answer: http://stackoverflow.com/a/52340477
answer count: 1
downvote count: 0
has title: Images saved as HDF5 arent colored
favorite count: 0
has comment: http://stackoverflow.com/comment/91159107

http://stackoverflow.com/q/52103552
favorite count: 0
has answer: http://stackoverflow.com/a/52103951
has title: How to click on the Close icon of the popup as per the url provided through Selenium
tagged with: webdriverwait
has answer: http://stackoverflow.com/a/52105238
tagged with: python
has comment: http://stackoverflow.com/comment/91158808
has comment: http://stackoverflow.com/comment/91163016
answer count: 4
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91160085
tagged with: iframe
has comment: http://stackoverflow.com/comment/91160182
tagged with: selenium
tagged with: webdriver
has answer: http://stackoverflow.com/a/52103914
type: Question
score: 0
has answer: http://stackoverflow.com/a/52110587
accepted answer: http://stackoverflow.com/a/52110587
linked to: http://stackoverflow.com/q/7534622
upvote count: 1
has body: I'm trying to get rid of the pop-up window showing up when first visiting this page: https://www.realestate.com.kh/buy/?listing_type=sale&amp;categories=Condo&amp;order_by=relevance&amp;is_certified=1&amp;private_seller=1#page-10 According to the html code, the id of the "x" element which I'd like Selenium to "click" is "leadpages-close-button" So I'm trying to click on it with this code: from selenium import webdriver from selenium.webdriver.support.ui import WebDriverWait driver = webdriver.Safari() driver.get("https://www.realestate.com.kh/buy/?listing_type=sale&amp;categories=Condo&amp;order_by=relevance&amp;is_certified=1&amp;private_seller=1#page-10") driver.find_element_by_id("leadpages-close-button").close() But it results in an error: File "Untitled.py", line 6, in &lt;module&gt; driver.find_element_by_id("leadpages-close-button") File "/usr/local/lib/python3.7/site-packages/selenium/webdriver/remote/webdriver.py", line 359, in find_element_by_id return self.find_element(by=By.ID, value=id_) File "/usr/local/lib/python3.7/site-packages/selenium/webdriver/remote/webdriver.py", line 966, in find_element 'value': value})['value'] File "/usr/local/lib/python3.7/site-packages/selenium/webdriver/remote/webdriver.py", line 320, in execute self.error_handler.check_response(response) File "/usr/local/lib/python3.7/site-packages/selenium/webdriver/remote/errorhandler.py", line 242, in check_response raise exception_class(message, screen, stacktrace) selenium.common.exceptions.NoSuchElementException: Message: What am I doing wrong?
downvote count: 1
possible better answer: http://stackoverflow.com/a/52103914

http://stackoverflow.com/q/51958242
answer count: 4
has answer: http://stackoverflow.com/a/69796311
type: AnsweredQuestion
tagged with: selenium
has body: --user-data-dir option I tried to open Chromedriver with --user-data-dir option but following error comes out. I've tried this in many ways for 1 month and still don't have clue. Please help me! Error message is: Traceback (most recent call last): File "C:\Users\owner\Desktop\MouseWithoutBorders\AutoCheckin.py", line 15, in driver = webdriver.Chrome(executable_path=r"C:\Users\owner\Desktop\MouseWithoutBorders\chromedriver.exe", chrome_options=opts) File "C:\Users\owner\AppData\Local\Programs\Python\Python37\lib\site-packages\selenium\webdriver\chrome\webdriver.py", line 75, in init desired_capabilities=desired_capabilities) File "C:\Users\owner\AppData\Local\Programs\Python\Python37\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 156, in init self.start_session(capabilities, browser_profile) File "C:\Users\owner\AppData\Local\Programs\Python\Python37\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 251, in start_session response = self.execute(Command.NEW_SESSION, parameters) File "C:\Users\owner\AppData\Local\Programs\Python\Python37\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 320, in execute self.error_handler.check_response(response) File "C:\Users\owner\AppData\Local\Programs\Python\Python37\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 242, in check_response raise exception_class(message, screen, stacktrace) selenium.common.exceptions.WebDriverException: Message: unknown error: Could not remove old devtools port file. Perhaps the given user-data-dir at C:\Users\owner\AppData\Local\Google\Chrome\ is still attached to a running Chrome or Chromium process. (Driver info: chromedriver=2.41.578737 (49da6702b16031c40d63e5618de03a32ff6c197e),platform=Windows NT 10.0.17738 >x86_64) and My python test code is: import time from selenium import webdriver from selenium.webdriver.common.keys import Keys from selenium.webdriver.common.action_chains import ActionChains from selenium.webdriver.chrome.option…
upvote count: 10
type: Question
has comment: http://stackoverflow.com/comment/96659641
has answer: http://stackoverflow.com/a/74921035
downvote count: 0
score: 10
has title: Python Selenium --user-data-dir option ERROR: could not remove old devtools port file
favorite count: 0
has answer: http://stackoverflow.com/a/55245846
has answer: http://stackoverflow.com/a/70591835
tagged with: selenium-chromedriver
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/55245846
possible better answer: http://stackoverflow.com/a/74921035
tagged with: chromium
tagged with: python

jpype
tag name: jpype
type: Tag
tags question: http://stackoverflow.com/q/52011684

http://stackoverflow.com/comment/90908822
type: QuestionComment
has text: Since OP is using random seeds, even with re-runs, the same initializations should be used (pseudo-randomness). Therefore, we should expect the same outcome every run. As a sidenode from my point: What system are you running on? Windows/Linux? GPU training? CPU?
score: 0
comment on: http://stackoverflow.com/q/51972909
type: Comment

http://stackoverflow.com/a/52018228
answers question: http://stackoverflow.com/q/52016616
type: Answer
accepted answer of: http://stackoverflow.com/q/52016616
score: 1
upvote count: 1
has body: Similar to @SilverMonkey's suggestion: Gaussian blur followed by Otsu thresholding.
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/90910840
has text: You might want to do the imports outside your loop as well.
comment on: http://stackoverflow.com/q/51980534
score: 1
type: QuestionComment
type: Comment

http://stackoverflow.com/q/51976832
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/51976887
has body: I am trying to use a virtualenv to use opencv with python on OSX. I created a virtualenv with virtualenv --system-site-packages venv I then installed numpy and opencv with pip install numpy opencv-python However when I run my code using the virtualenv I get an error from the imports: import cv2 import numpy as np I get this error: ImportError: No module named cv2 I haven't been able to find any information on this issue, but I can't seem to import any third party modules. It doesn't work with pandas, scipy, etc. either. Originally I was not using a virtualenv, but the other sources I found told me to try one.
has title: ImportError on installed Python modules
has answer: http://stackoverflow.com/a/51976914
tagged with: python
tagged with: macos
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90903851
type: Question
tagged with: opencv

http://stackoverflow.com/q/52006414
has answer: http://stackoverflow.com/a/52007353
tagged with: dataframe
has body: I have data like below: id movie details value 5 cane1 good 6 5 wind2 ok 30.3 5 wind1 ok 18 5 cane1 good 2 5 cane22 ok 4 5 cane34 good 7 5 wind2 ok 2 I want the output with below criteria: If movie name starts with 'cane' - sum the value If movie name starts with 'wind' - count the occurrence. So - the final output will be: id movie value 5 cane1 8 5 cane22 4 5 cane34 7 5 wind1 1 5 wind2 2 I tried to use: movie_df.groupby(['id']).apply(aggr) def aggr(x): if x['movie'].str.startswith('cane'): y = x.groupby(['value']).sum() else: y = x.groupby(['movie']).count() return y But It's not working. Can anyone please help?
type: Question
downvote count: 0
linked to: http://stackoverflow.com/q/22588316
accepted answer: http://stackoverflow.com/a/52006778
favorite count: 0
has comment: http://stackoverflow.com/comment/90963571
tagged with: pandas
tagged with: python
answer count: 4
has answer: http://stackoverflow.com/a/52007070
upvote count: 2
has answer: http://stackoverflow.com/a/52006598
possible better answer: http://stackoverflow.com/a/52007070
has title: panda aggregate by functions
has answer: http://stackoverflow.com/a/52006778
score: 2
type: AnsweredQuestion

http://stackoverflow.com/comment/90951120
comment on: http://stackoverflow.com/q/52000052
score: 0
type: Comment
type: QuestionComment
has text: after i changed that and changed my html to just {{ test }} it still does not display the record.

http://stackoverflow.com/q/52088112
duplicate of: http://stackoverflow.com/q/14087598
linked to: http://stackoverflow.com/q/52127997
tagged with: python
answer count: 0
has comment: http://stackoverflow.com/comment/91206259
type: UnansweredQuestion
tagged with: django
tagged with: heroku
tagged with: mysql
has body: I try to push the Python project (Python 3.7.0) to Heroku. It's a django project with mysql database linked. But it keeps show that the error: ModuleNotFoundError: No module named 'ConfigParser'. Is really the version 3.7.0 not compatible to Heroku? I try to pip install ConfigParser in the command, but it still not work. Does anyone meet this problem? Here's the error when pushing project in Heroku: remote: Complete output from command python setup.py egg_info: remote: Traceback (most recent call last): remote: File "&lt;string&gt;", line 1, in &lt;module&gt; remote: File "/tmp/pip-build-1fjjz1dy/MySQL-python/setup.py", line 13, in &lt;module&gt; remote: from setup_posix import get_config remote: File "/tmp/pip-build-1fjjz1dy/MySQL-python/setup_posix.py", line 2, in &lt;module&gt; remote: from ConfigParser import SafeConfigParser remote: ModuleNotFoundError: No module named 'ConfigParser' remote: remote: ---------------------------------------- remote: Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-build-1fjjz1dy/MySQL-python/ remote: ! Push rejected, failed to compile Python app. remote: remote: ! Push failed remote: Verifying deploy... remote: remote: ! Push rejected to fathomless-citadel-89649. I checked the other solution and installed the mysqlclients but it still cannot be pushed. Can anyone help me?
has title: Cannot push Django Python project in Heroku
has comment: http://stackoverflow.com/comment/91206032
type: Question
linked to: http://stackoverflow.com/q/14087598
has comment: http://stackoverflow.com/comment/91206387
has comment: http://stackoverflow.com/comment/91127862
score: 0

http://stackoverflow.com/comment/91014431
has text: Yes lol. I tried that and it didn't work. Anyway, I solved it by using my bot's token. THANKS
score: 3
type: Comment
comment on: http://stackoverflow.com/q/52031952
type: QuestionComment

http://stackoverflow.com/comment/91165078
comment on: http://stackoverflow.com/q/52105606
type: Comment
has text: Well one problem I notice is you are using 3 `?`'s seeming like you want to pass in parameters to the query, but you never actually specify what those paremeters are supposed to be.
score: 0
type: QuestionComment

http://stackoverflow.com/q/52096933
has body: I am new to PyTorch and LSTMs and I am trying to train a classification model that takes a sentences where each word is encoded via word2vec (pre-trained vectors) and outputs one class after it saw the full sentence. I have four different classes. The sentences have variable length. My code is running without errors, but it always predicts the same class, no matter how many epochs I train my model. So I think the gradients are not properly backpropagated. Here is my code: class LSTM(nn.Module): def __init__(self, embedding_dim, hidden_dim, tagset_size): super(LSTM, self).__init__() self.hidden_dim = hidden_dim self.lstm = nn.LSTM(embedding_dim, hidden_dim) self.hidden2tag = nn.Linear(hidden_dim, tagset_size) self.hidden = self.init_hidden() def init_hidden(self): # The axes semantics are (num_layers, minibatch_size, hidden_dim) return (torch.zeros(1, 1, self.hidden_dim).to(device), torch.zeros(1, 1, self.hidden_dim).to(device)) def forward(self, sentence): lstm_out, self.hidden = self.lstm(sentence.view(len(sentence), 1, -1), self.hidden) tag_space = self.hidden2tag(lstm_out.view(len(sentence), -1)) tag_scores = F.log_softmax(tag_space, dim=1) return tag_scores EMBEDDING_DIM = len(training_data[0][0][0]) HIDDEN_DIM = 256 model = LSTM(EMBEDDING_DIM, HIDDEN_DIM, 4) model.to(device) loss_function = nn.NLLLoss() optimizer = optim.SGD(model.parameters(), lr=0.1) for epoch in tqdm(range(n_epochs)): for sentence, tag in tqdm(training_data): model.zero_grad() model.hidden = model.init_hidden() sentence_in = torch.tensor(sentence, dtype=torch.float).to(device) targets = torch.tensor([label_to_idx[tag]], dtype=torch.long).to(device) tag_scores = model(sentence_in) res = torch.tensor(tag_scores[-1], dtype=torch.float).view(1,-1).to(device) # I THINK THIS IS WRONG??? print(res) # tensor([[-10.6328, -10.6783, -10.6667, -0.0001]], device='cuda:0', grad_fn=&lt;CopyBackwards&gt;) print(targets) # tensor([3], device='cuda:0') loss = loss_function(res, targets) loss.backward() optimi…
tagged with: python
tagged with: nlp
tagged with: pytorch
score: 1
upvote count: 1
has title: PyTorch n-to-1 LSTM does not learn anything
type: Question
has answer: http://stackoverflow.com/a/54640171
tagged with: lstm
downvote count: 0
answer count: 1
favorite count: 0
type: UnansweredQuestion

http://stackoverflow.com/comment/91074588
comment on: http://stackoverflow.com/q/52059294
score: 0
type: Comment
type: QuestionComment
has text: @desertnaut I doublechecked that code, and it gives me the error above.

http://stackoverflow.com/a/52112607
type: Answer
accepted answer of: http://stackoverflow.com/q/52108096
has body: Supposing that Distance is km, use this to get your speed in km/h: import pandas as pd df=pd.DataFrame({'DISTANCE':[9.5,11.1,11.1],'TIME':['51:50.92','55:59.70','49:25.20'],'DATE':['09/08/18','24/08/18','29/08/18']}) df['TIME'] = '00:' + df['TIME'] df['TIME'] = pd.to_timedelta(df['TIME']) df['SPEED (km/h)']=[df['DISTANCE'][i]/(df['TIME'][i].total_seconds()/3600) for i in df.index]#total_seconds() won't work with a pandas column so you need to apply it to each TIME cell
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/52108096
has comment: http://stackoverflow.com/comment/91192500
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/52057964
downvote count: 0
favorite count: 0
upvote count: 2
type: UnansweredQuestion
tagged with: python
answer count: 0
tagged with: parquet
tagged with: amazon-s3
tagged with: pyarrow
has title: Error opening a parquet file on Amazon S3 using pyarrow
type: Question
has body: I have this code, which is supposed to read a single column data from a parquet file stored on S3: fs = s3fs.S3FileSystem() data_set = pq.ParquetDataset(f"s3://{bucket}/{key}", filesystem=fs) column_data = data_set.read(columns=[col_name]) and I get this excption: validate_schemas self.schema = self.pieces[0].get_metadata(open_file).schema IndexError: list index out of range I upgraded to the latest version of pyarrow but it did not help
score: 2

http://stackoverflow.com/q/52027956
upvote count: 1
has answer: http://stackoverflow.com/a/52045497
type: Question
downvote count: 0
has comment: http://stackoverflow.com/comment/91007845
has comment: http://stackoverflow.com/comment/91039973
has body: I use combine_first to combine two DataFrames based on two keys, the goal is to append the indices of df2 that are not contained in df1 to the result and to overwrite indices that are contained in both with the values from df2. Example df1: df1 = pd.DataFrame({ "key1": ["A", "A", "A", "B", "B", "C", "C"], "id": ["a1", "a2", "a3", 1, 2, "c1", "c2"], "data1": [pd.np.random.randint(5) for i in range(7)], "data2": [pd.np.random.randint(1000) for i in range(7)] }) Example df2: df2 = pd.DataFrame({ "key1": ["B", "B", "B"], "id": [2, 3, 4], "data1": [pd.np.random.randint(5) for i in range(3)], "data2": [pd.np.random.randint(1000) for i in range(3)] }) df1.set_index(["key1", "id"]).combine_first(df2.set_index(["key1", "id"])) gives the desired result: data1 data2 key1 id A a1 0.0 588.0 a2 2.0 709.0 a3 3.0 877.0 B 1 3.0 468.0 2 0.0 612.0 3 2.0 139.0 4 3.0 154.0 C c1 4.0 855.0 c2 4.0 564.0 However, after storing the result as csv, loading it again and running the same command I get the following error: TypeError: '&lt;' not supported between instances of 'str' and 'int' But only for a df2 where id is int only. When id contains characters it works without a problem. I found this in the Pandas docs: The different indexing operation can potentially change the dtype of a Series. Which explains why the problem persists if I change the dtype of df2.id to object before setting the index and combining. How can I specifically set the dtype of a MultiIndex level so that the combination works? EDIT To further illustrate the problem: df = df1.set_index(["key1", "id"]).combine_first(df2.set_index(["key1", "id"])) df.to_csv("tests/combtest2.csv", sep=";") df_loaded = pd.read_csv("tests/combtest2.csv", sep=";", index_col=["key1", "id"]) Looks fine: data1 data2 key1 id A a1 0.0 588.0 a2 2.0 709.0 a3 3.0 877.0 B 1 3.0 468.0 2 0.0 612.0 3 2.0 139.0 4 3.0 154.0 C c1 4.0 855.0 c2 4.0 564.0 But df_loaded.combine_first(df2.set_index(["key1", "id"])) results in: data1 data2 key1 id A a1 0.0 588.0 a…
tagged with: pandas
answer count: 1
accepted answer: http://stackoverflow.com/a/52045497
has comment: http://stackoverflow.com/comment/91040615
has title: How to force MultiIndex level to dtype
favorite count: 0
has comment: http://stackoverflow.com/comment/91041658
tagged with: python
has comment: http://stackoverflow.com/comment/91025623
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91041708
has comment: http://stackoverflow.com/comment/91025670
score: 1

http://stackoverflow.com/comment/90946998
has text: Sorry maybe I wasn't clear enough but I was expecting you to provide the logic behind your function with input and expected output(not line to line explanation). You will get better response if you provide that. [How to ask question on SO](https://stackoverflow.com/help/mcve)
score: 0
comment on: http://stackoverflow.com/q/51998466
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52002849
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52047472
type: Question
tagged with: aws-xray
has body: To create a sub-segment aws-xray requires that a valid segment is opened. By default remote lambda execution opens a segment for you and you just have to add a subsegment but while running locally we need to open segment manually before adding sub-segment. I can put things in try-except block to initiate subsegments only when segments are available but is there any method that checks if segment is open. Right now working with this: try: xray_recorder.current_segment() except: xray_recorder.begin_segment(self.segment_name)
score: 4
upvote count: 4
answer count: 1
downvote count: 0
accepted answer: http://stackoverflow.com/a/52047472
favorite count: 0
tagged with: aws-lambda
has title: AWS Xray: How to check if Xray Segment is open?
tagged with: python

http://stackoverflow.com/q/52026933
type: Question
type: AnsweredQuestion
tagged with: docker-compose
has comment: http://stackoverflow.com/comment/91014454
upvote count: 4
answer count: 1
has answer: http://stackoverflow.com/a/52028188
downvote count: 0
score: 4
tagged with: flask
favorite count: 0
tagged with: docker
has body: I'm dockerizing a Flask app. To run the app without docker, i first run "export FLASK_APP=app", then "flask run", so I transferred that over to the Dockerfile. This is the error message after running docker-compose -f docker-compose.yml up --build Cannot start service app: b'OCI runtime create failed: container_linux.go:348: starting container process caused "exec: \"flask\": executable file not found in $PATH": unknown' Upon checking the logs by typing docker-compose -f docker-compose.yml logs -f, I see this error and the container is exited with code 127: /bin/sh: 1: flask: not found Folder structure tree - app - __init__.py - Dockerfile - docker-compose.yml docker-compose.yml version: '2' services: app: restart: always build: context: . dockerfile: Dockerfile ports: - "5000:5000" volumes: - .:/app depends_on: - redis redis: image: redis command: redis-server ports: - '6379:6379' Dockerfile # Pull base image. FROM ubuntu # Install Supervisor. RUN \ mkdir /var/log/celery &amp;&amp; \ mkdir /home/ubuntu &amp;&amp; \ apt-get update &amp;&amp; \ apt-get install -y supervisor python-pip wget vim git &amp;&amp; \ rm -rf /var/lib/apt/lists/* &amp;&amp; \ sed -i 's/^\(\[supervisord\]\)$/\1\nnodaemon=true/' /etc/supervisor/supervisord.conf # needs to be set else Celery gives an error (because docker runs commands inside container as root) ENV C_FORCE_ROOT=1 # expose port 80 of the container (HTTP port, change to 443 for HTTPS) EXPOSE 80 # Create virtualenv. RUN \ pip2 install --upgrade pip &amp;&amp; \ pip install --upgrade virtualenv &amp;&amp; \ virtualenv -p /usr/bin/python2.7 /home/ubuntu/.virtualenvs WORKDIR /home/ubuntu/celery-scheduler ADD requirements.txt /home/ubuntu/tree/ # Install app requirements RUN \ . /home/ubuntu/.virtualenvs/bin/activate &amp;&amp; \ pip install -r requirements.txt COPY . /home/ubuntu/tree # Copy supervisor configs RUN \ cp configs/supervisord.conf /etc/supervisor/supervisord.conf &amp;&amp; \ cp configs/conf.d/*.conf /etc/supervisor/conf.…
has comment: http://stackoverflow.com/comment/91004769
tagged with: python
has title: Docker container build failed: /bin/sh: 1: flask: not found
accepted answer: http://stackoverflow.com/a/52028188

http://stackoverflow.com/q/51999065
tagged with: google-cloud-storage
upvote count: 4
answer count: 3
tagged with: google-cloud-platform
possible better answer: http://stackoverflow.com/a/53562074
downvote count: 0
has answer: http://stackoverflow.com/a/53562074
favorite count: 0
tagged with: google-app-engine
has answer: http://stackoverflow.com/a/52045850
has comment: http://stackoverflow.com/comment/91014559
tagged with: python
has comment: http://stackoverflow.com/comment/90961727
tagged with: app.yaml
type: AnsweredQuestion
has body: I am trying to deploy my app using Google App Engine. I have edited app.yaml to reflect the flexible environment and also gave all the app information. Below is the app.yaml file. runtime: python env: flex entrypoint: gunicorn -b :$PORT main:app runtime_config: python_version: 3 Once the deployment is in progress, I am getting the following error [2018-08-24 06:57:14 +0000] [1] [INFO] Starting gunicorn 19.7.1 [2018-08-24 06:57:14 +0000] [1] [INFO] Listening at: http://0.0.0.0:8080 (1) [2018-08-24 06:57:14 +0000] [1] [INFO] Using worker: sync [2018-08-24 06:57:14 +0000] [7] [INFO] Booting worker with pid: 7 App Deployed Failed to find application: 'main' [2018-08-24 06:57:14 +0000] [7] [INFO] Worker exiting (pid: 7) [2018-08-24 06:57:14 +0000] [1] [INFO] Shutting down: Master [2018-08-24 06:57:14 +0000] [1] [INFO] Reason: App failed to load. Please note that App Deployed is the line in my print statement. It is getting executed. But the deployment is getting failed Thank you in advance
type: Question
has title: Google App Engine deployment issue- main app not found
has answer: http://stackoverflow.com/a/67355000
accepted answer: http://stackoverflow.com/a/52045850
score: 4

http://stackoverflow.com/a/51986744
answers question: http://stackoverflow.com/q/51985455
accepted answer of: http://stackoverflow.com/q/51985455
type: AcceptedAnswer
downvote count: 0
has body: Here is the working code @bot.command(pass_context=True) async def permissions(ctx, user: discord.Member): embed = discord.Embed(name="USER_PERMISSIONS", description="------------------------------------------------------", color=0x0099ff) embed.set_author(name="USER_PERMISSIONS: {}'s Permissions".format(user.name)) if user.server_permissions.administrator == True: embed.add_field(name="Administrator", value=":white_check_mark: Permission Granted!", inline=True) if user.server_permissions.administrator == False: embed.add_field(name="Administrator", value=":x: Permission Denied!", inline=True) if user.server_permissions.view_audit_logs == True: embed.add_field(name="View Audit Logs", value=":white_check_mark: Permission Granted!", inline=True) if user.server_permissions.view_audit_logs == False: embed.add_field(name="View Audit Logs", value=":x: Permission Denied!", inline=True) embed.set_thumbnail(url=user.avatar_url) embed.set_footer(text="Requested by {}".format(ctx.message.author), icon_url=ctx.message.author.avatar_url) await bot.say(embed=embed) A couple of things, first off you don't need to use ctx.message.user.server_permissions if you've already initialised what the user is so just use user.server_permissions as ctx.message has no attribute called "user" Secondly author is not defined, use ctx.author to display who sent the message And lastly you misspelt :white_check_mark: Hopefully this helped!
type: Answer
score: 1
upvote count: 1

http://stackoverflow.com/q/52059893
downvote count: 0
score: 1
has title: How to set exceptions inside "yield" for Scrapy?
type: Question
answer count: 2
accepted answer: http://stackoverflow.com/a/52060277
tagged with: javascript
has answer: http://stackoverflow.com/a/52060277
upvote count: 1
tagged with: http://stackoverflow.com/tag/html
has body: Good day, I'm trying to scrape GitHub using Scrapy. It works for the most part, but some pages load "contributors" after the page itself is done loading. When Scrapy encounters such a page it throws the following error: AttributeError: 'NoneType' object has no attribute 'strip' and discards everything else from that URL. Is there a way to make an exception inside "yield" so Scrapy puts "None" into the resulting .CSV instead of throwing all the data away? Here's the relevant code: rules = [ Rule(LinkExtractor(allow=('Repositories'), restrict_xpaths=('//a[@rel="next"]'))), Rule(LinkExtractor(allow=('github'), restrict_xpaths=('//h3/a[@class="v-align-middle"]')), callback='parse_project'), Rule(LinkExtractor(allow=('commits/master'), restrict_xpaths=('//*[@class="commits"]/a')), follow=True, callback='parse_commits_page'), Rule(LinkExtractor(deny=('\+174'), restrict_xpaths=('//a[contains(text(), "Older")]')), follow=True, callback='parse_commits_page') ] # Parse the main page of the project def parse_project(self, response): yield { 'author': response.xpath('//a[@rel="author"]/text()').extract(), 'name': response.xpath('//strong[@itemprop="name"]/a/text()').extract(), 'tags': [x.strip() for x in response.xpath('//a[contains(@class, "topic-tag")]/text()').extract()], 'about': response.xpath('//*[@itemprop="about"]/text()').extract_first().strip(), 'lang_name': response.xpath('//span[@class = "lang"]/text()').extract(), 'lang_perc' : response.xpath('//span[@class = "percent"]/text()').extract(), 'stars': response.xpath('//a[contains(@aria-label, "starred")]/text()').extract_first().strip(), 'forks': response.xpath('//a[contains(@aria-label, "forked")]/text()').extract_first().strip(), 'commits': response.xpath('//a[contains(., "commits")]/span/text()').extract_first().strip(), 'contributors': response.xpath('//a[contains(., "contributor")]/span/text()').extract_first().strip(), 'last_commits': None } In particular,'contributors': response.xpath('//a[contains(., "contribu…
favorite count: 0
possible better answer: http://stackoverflow.com/a/52067549
tagged with: web-scraping
tagged with: python
tagged with: scrapy
has answer: http://stackoverflow.com/a/52067549
type: AnsweredQuestion

http://stackoverflow.com/a/51996631
type: Answer
answers question: http://stackoverflow.com/q/51996545
has body: This should work I think import numpy as np l = [{"from": "Location1", "to": "Location2"}, {"from": "Location1", "to": "Location3"}, {"from": "Location1", "to": "Location4"}, {"from": "Location1", "to": "Location5"}] from_to = np.array(([d['from'] for d in l],[d['to'] for d in l])).T froms = set(from_to[:,0]) out = [] for f in froms: d = {} mask = from_to[:,0]==f d['from']=f d['to'] = from_to[:,1][mask] out.append(d)
score: 0

http://stackoverflow.com/a/52032301
has body: You need to have a separate method that does the database checking for you. def printNewTable(): db = dqsqlite3.connect('usio.db') for row in db.execute('select * from rates'): print row printNewTable()
downvote count: 0
answers question: http://stackoverflow.com/q/52032149
accepted answer of: http://stackoverflow.com/q/52032149
has comment: http://stackoverflow.com/comment/91014917
has comment: http://stackoverflow.com/comment/91014871
score: 1
type: AcceptedAnswer
upvote count: 1
type: Answer

http://stackoverflow.com/a/52050040
accepted answer of: http://stackoverflow.com/q/52045413
answers question: http://stackoverflow.com/q/52045413
has comment: http://stackoverflow.com/comment/91113347
upvote count: 1
type: AcceptedAnswer
has body: There's a nice module called gradients.py by DR0ID. Here's the simpler vertical gradient function which uses linear interpolation: def vertical(size, startcolor, endcolor): """ Draws a vertical linear gradient filling the entire surface. Returns a surface filled with the gradient (numeric is only 2-3 times faster). """ height = size[1] bigSurf = pygame.Surface((1,height)).convert_alpha() dd = 1.0/height sr, sg, sb, sa = startcolor er, eg, eb, ea = endcolor rm = (er-sr)*dd gm = (eg-sg)*dd bm = (eb-sb)*dd am = (ea-sa)*dd for y in range(height): bigSurf.set_at((0,y), (int(sr + rm*y), int(sg + gm*y), int(sb + bm*y), int(sa + am*y)) ) return pygame.transform.scale(bigSurf, size) There's also a more versatile vertical_func function which allows you to pass different functions for each color channel.
type: Answer
downvote count: 0
score: 1

http://stackoverflow.com/comment/91022104
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/52035779
score: 0
has text: import operator, test=sorted(test, key=operator.itemgetter(0))

http://stackoverflow.com/q/52055856
favorite count: 0
has answer: http://stackoverflow.com/a/55397285
type: UnansweredQuestion
tagged with: python
upvote count: 4
type: Question
has body: I'm on macOS 10.13 and I've a problem after installed aws-cli. I can't use aws command in my CLI. I've installed aws-cli with pip 18.0 used this command: pip install awscli --upgrade --user After that, aws command didn't work so I've checked the aws-cli install directory with this command: python -c 'import awscli; print(awscli)' Output:/Users/XXXXX/Library/Python/2.7/lib/python/site-packages/awscli/__init__.pyc And I add it the output in my PATH directory, under the PATH for python. PATH="/Library/Frameworks/Python.framework/Versions/3.7/bin/python3:${PATH} export PATH=$HOME/Library/Python/2.6/bin:$PATH Unfortunate, aws commands still doesn't works. I've checked and followed steps at https://docs.aws.amazon.com/cli/latest/userguide/installing.html but wasn't resolve my problem. What's wrong with my process ? Do you have solution for me ?
has title: aws-cli not found on macOS
tagged with: aws-cli
score: 4
has answer: http://stackoverflow.com/a/52055944
answer count: 3
downvote count: 0
has answer: http://stackoverflow.com/a/52058595
tagged with: amazon-web-services

http://stackoverflow.com/comment/91177884
type: AnswerComment
has text: @EkinEkinEkin can you please share what you mean by "working sometimes, not working properly"? What are you receiving? What are you not receiving? What is the behavior you are experiencing and why it is not what you expect?
comment on: http://stackoverflow.com/a/52074921
type: Comment
score: 0

http://stackoverflow.com/q/52008294
upvote count: 0
score: -2
tagged with: mxnet
answer count: 1
favorite count: 0
type: UnansweredQuestion
tagged with: python
has title: How to test neural network on entire testset using mxnet's dataset object?
downvote count: 2
has body: I have trained a 3D convnet using mxnet. I saved the network architecture and parameters with an intention of testing more data with it to check its performance. Since I am not training, I do not want to obtain batches of the dataset. How do I get the network to read in the entire dataset as input? Just passing the network the dataset object directly is only a 4D tensor whereas the network wants 5D. Right now I am using the dataloader but setting batch size as the entire dataset, and I feel like there is a more efficient way to do this.
has answer: http://stackoverflow.com/a/52047712
tagged with: machine-learning
type: Question

http://stackoverflow.com/q/52041076
has comment: http://stackoverflow.com/comment/91035965
answer count: 0
has title: Graphviz command '['dot', '-Tdot']' returned non-zero exit status -11
type: Question
has comment: http://stackoverflow.com/comment/91033072
tagged with: graphviz
tagged with: python-2.7
score: 0
has body: I want to extract the coordinates calculated for my graph by Graphviz. However, I'm running into the following error with Python 2.7 and Graphviz 0.9: Graphviz command '['dot', '-Tdot']' returned non-zero exit status -11 I cannot find any documentation on these error codes. Below is the code I'm using: gvz = GraphUtils.toGraphvizGraph(graph) parsed_dot = gvz.pipe('dot') The first line turns my own graph representation into a Graphviz Digraph instance. result = Digraph() # By hashing the ids, we get rid of any potential special characters graphviz does not like # A graphviz ID always needs to start with a character for node in graph.nodes.to_dict(orient='records'): result.node('id_{}'.format(abs(hash(node[node_name_key]))), 'label for width') # END LOOP for edge in graph.edges.to_dict(orient='records'): result.edge('id_{}'.format(abs(hash(edge[edge_source_key]))), 'id_{}'.format(abs(hash(edge[edge_target_key])), edge[edge_label_key])) # END LOOP return result The second line transforms the graph into DOT, which contains the coordinates I need. However, this is where my error occurs. While testing, I found that occasionally my node ids would contain illegal characters (as defined here). I eliminated these cases by transforming all my ids into hashes. Now all my node ids look like this: ['id_7598267142946574759', 'id_2914022568081909736', 'id_2112657658742367456', 'id_2416843868423017323'] This has eliminated the error for some of my graphs, but not for all of them. Since the error code is still the same, I'm thinking there must still be something wrong with these ids. However, since the error code is not actually defined anywhere, I might also be looking in the wrong direction. What am I missing?
has comment: http://stackoverflow.com/comment/91033253
has comment: http://stackoverflow.com/comment/91032943
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91032848
tagged with: python

http://stackoverflow.com/comment/91134797
has text: As has been stated in the blog post, the `Y` should be a 3D matrix of shape `(NIMG, MAX_CHAR, NC)` and not `(NIMG, MAX_CHAR)`. You need to one-hot encode the characters in `Y`.
comment on: http://stackoverflow.com/q/52087578
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52062060
type: UnansweredQuestion
has body: How to convert an image with .jpg format into a matrix of pixels using Python (NumPy). I have searched the internet but I can't find a way to use Python; most of the results in the search use Matlab, but I want to do it with Python.
tagged with: python
tagged with: image-processing
linked to: http://stackoverflow.com/q/384759
linked to: http://stackoverflow.com/q/7762948
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/91074632
has comment: http://stackoverflow.com/comment/91074578
duplicate of: http://stackoverflow.com/q/7762948
has comment: http://stackoverflow.com/comment/91075631
score: 0
has title: JPG image into matrix using Python
answer count: 0

http://stackoverflow.com/q/51978974
has answer: http://stackoverflow.com/a/51987469
tagged with: python
has answer: http://stackoverflow.com/a/70539644
type: UnansweredQuestion
type: Question
has title: How to mention a sender of a command? discord.py
tagged with: discord.py
has body: I created a super simple .report &lt;person&gt; command. I have it so it will be sent to a certain channel when someone types it. What I wanted to do is have it display the name of the user who reported the other user. I don't know how to go about doing that. Does anyone know the best way? @bot.command() async def report(*, message): await bot.delete(message) await bot.send_message(bot.get_channel("479177111030988810"), message)
score: 0
answer count: 2

http://stackoverflow.com/comment/101525945
has text: I believe, my final solution was to use [joblib](https://joblib.readthedocs.io) instead of multiprocessing, and instead of transferring large objects, I used [joblib.dump](https://joblib.readthedocs.io/en/latest/generated/joblib.dump.html) and [joblib.load](https://joblib.readthedocs.io/en/latest/generated/joblib.load.html) to save them into a file and then read in the worker processes.
type: Comment
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/51971983

http://stackoverflow.com/a/63650101
downvote count: 0
type: Answer
has body: Here is a great example from "Ten Essays on Fizz Buzz" book by Joel Grus by using recursion. from typing import List, Tuple, Union def shape(ndarray: Union[List, float]) -> Tuple[int, ...]: if isinstance(ndarray, list): # More dimensions, so make a recursive call outermost_size = len(ndarray) row_shape = shape(ndarray[0]) return (outermost_size, *row_shape) else: # No more dimensions, so we're done return () Example: three_d = [ [[0, 0, 0], [1, 1, 1], [2, 2, 2]], [[0, 0, 0], [1, 1, 1], [2, 2, 2]], [[0, 0, 0], [1, 1, 1], [2, 2, 2]], [[0, 0, 0], [1, 1, 1], [2, 2, 2]], [[0, 0, 0], [1, 1, 1], [2, 2, 2]], ] result = shape(three_d) print(result) >>> (5, 3, 3)
score: 4
answers question: http://stackoverflow.com/q/51960857
upvote count: 4

eclipse
tag name: eclipse
tags question: http://stackoverflow.com/q/52077174
tags question: http://stackoverflow.com/q/52021100
tags question: http://stackoverflow.com/q/51963626
type: Tag

http://stackoverflow.com/a/52094480
upvote count: 2
score: 2
downvote count: 0
answers question: http://stackoverflow.com/q/52094370
type: Answer
has body: Show environment from commandline linux: export windows: set Setting an environment variable linux: export foo=bar windows: set foo=bar Printing env var: linux: echo $foo windows: echo %foo%

http://stackoverflow.com/comment/110856388
type: AnswerComment
has text: Thank you @Starwarswii , I have added this information to the answer
type: Comment
comment on: http://stackoverflow.com/a/52191687
score: 0

http://stackoverflow.com/a/51976543
answers question: http://stackoverflow.com/q/51976328
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/90913965
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51976328
score: 22
type: Answer
has body: Your file almost certainly has actual U+00AD soft-hyphen characters in it. These are characters that mark places where a word could be split when fitting lines to a page. The idea is that the soft hyphen is invisible if the word doesn't need to be split, but printed the same as a U+2010 normal hyphen if it does. Since you don't care about rendering this text in a book with nicely flowing text, you're never going to hyphenate anything, so you just want to remove these characters. The way to do this is not to fiddle with the encoding. Just remove them from the Unicode text, using whichever of these you find most readable: data = data.replace('\xad', '') data = data.replace('\u00ad', '') data = data.replace('\N{SOFT HYPHEN}', '') Notice the single backslash. We're not replacing a literal backslash, x, a, d, we're replacing a literal soft-hyphen character, that is, the character whose code point is hex 0xad. You can either do this to the whole file before splitting into words, or do it once per word after splitting. Meanwhile, you seem to be confused about what encodings are and what to do with them: I've tried encoding the .txt file as iso8859-15 No, you've tried decoding the file as ISO-8859-15. It's not clear why you tried ISO-8859-15 in the first place. But, since the ISO-8859-15 encoding for the character '\xad' is the byte b'\xad', maybe that's correct. Ideally I'd like to encode this data as UTF-8 to avail of the nltk library But NLTK doesn't want UTF-8 bytes, it wants Unicode strings. You don't need to encode it for that. Plus, you're not trying to encode your Unicode text to UTF-8, you're trying to decode your bytes from UTF-8. If that's not what those bytes are… if you're lucky, you'll get an error like this one; if not, you'll get mojibake that you don't notice until you've screwed up a 500GB corpus and thrown away the original data.1 1. UTF-8 is specifically designed so you'll get early errors whenever possible. In this case, reading ISO-8859-15 text with so…
upvote count: 22

http://stackoverflow.com/a/51977496
downvote count: 0
answers question: http://stackoverflow.com/q/51977475
type: Answer
score: 1
upvote count: 1
has body: Try doing """: html_doc = """ Title of hte page H1 Tag H2 Tag with link First Paragraph Second Paragraph """
accepted answer of: http://stackoverflow.com/q/51977475
type: AcceptedAnswer

http://stackoverflow.com/a/52112313
score: 4
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/52111627
has body: You can simply use sublist a = codes[0: 21] b = codes[21:42] c = codes[42:63] d = codes[63:84] This will be fine for your requirement
answers question: http://stackoverflow.com/q/52111627
type: Answer
upvote count: 4
downvote count: 0
has comment: http://stackoverflow.com/comment/91176004

http://stackoverflow.com/q/52046701
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91070071
upvote count: 1
tagged with: outlook
has comment: http://stackoverflow.com/comment/91069188
score: 1
type: Question
downvote count: 0
has title: ExtractMsg.py checking for attachments and returning name
favorite count: 0
has comment: http://stackoverflow.com/comment/91044742
tagged with: python
has body: I am using a small script for reading a .msg file and printing the name of the attachment. I know the email has an attachment but it only returns "None". I cannot figure out what I am doing wrong. Can anyone help me? The script is supposed to return the long filename based on information from the following link. print sender prints the sender information fine, just always get a None for attachments https://github.com/jbfuzier/msg-analyzer/blob/master/ExtractMsg.py import ExtractMsg import glob for message in glob.glob('C:\Desktop\EMAILS\email_test\*.msg'): msg = ExtractMsg.Message(message) attach = msg._getStringStream('__substg1.0_3707') sender = msg._getStringStream('__substg1.0_0C1F') print attach print sender
answer count: 0
has comment: http://stackoverflow.com/comment/91070373

http://stackoverflow.com/comment/91121371
score: 0
comment on: http://stackoverflow.com/q/52084843
has text: A quick look at praat's documentation indicates that you must add a `--run` argument to get it to work reliably from a command line with redirection.
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51995490
has body: I'm trying to sample a random number using a log normal distribution fitted to a data set of ages. Age_abscess = numpy.random.lognormal(mean=numpy.log(29.9090909), sigma=numpy.log(11.6574484),size=None) I sometimes get answers to the tune of something ^23 and smaller than 1. Given that I want these to be ages, is there a way to restrict the draw to be between 0 and 100? Edit: After some brainstorming I came up with: def lognormal(mean,sigma): age = numpy.random.lognormal(mean=numpy.log(mean),sigma=numpy.log(sigma),size=None) if 0&gt;= age &lt;= 100: age=age return age However, this will only run once, so I'll have to figure out how to loop it until it satisfies the condition. This has probably been asked before-will update if I find the answer.
favorite count: 0
has answer: http://stackoverflow.com/a/51995691
has answer: http://stackoverflow.com/a/51995970
accepted answer: http://stackoverflow.com/a/51995691
tagged with: python
has comment: http://stackoverflow.com/comment/90941225
possible better answer: http://stackoverflow.com/a/51995970
type: AnsweredQuestion
upvote count: 0
type: Question
tagged with: numpy
has answer: http://stackoverflow.com/a/55411066
score: -1
has title: Restricting numpy.random.lognormal to a given range, Python
tagged with: random
answer count: 3
downvote count: 1

http://stackoverflow.com/q/52055484
favorite count: 0
has comment: http://stackoverflow.com/comment/91061272
upvote count: 2
has comment: http://stackoverflow.com/comment/91062204
tagged with: python
has comment: http://stackoverflow.com/comment/91061120
downvote count: 1
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52056224
score: 1
has title: What would be the most efficient or useful way to store attendance data?
accepted answer: http://stackoverflow.com/a/52056224
type: Question
has answer: http://stackoverflow.com/a/52056164
has answer: http://stackoverflow.com/a/52055617
has body: I want to move my schools attendance records away from excel sheets and into python, but I'm not sure what the best way to store that data would be. Method 1 Create a dictionary with student names as keys, and the dates they attended as items in a list. Or perhaps a list of the days they were absent would be more efficient. attendance = {} attendance["student_1"] = [2018-08-10, 2018-08-15, 2018-08-20] Method 2 Create a dictionary of dates and append a list of students who were present on that day: attendance = {} attendance["2018-08-10"] = [student_1, student_2, student_3] Method 3 Created nested dictionaries. Students names as the outer keys. All dates as inner keys with a boolean as a value. attendance = {} attendance["student_1"]= {} attendance["student_1"]["1018-08-10"] = 'True' All of these would probably work, but there must be a better way of storing this data. Can anyone help? I should add that I want to be able to access the student's attendance record from name and retrieve all the student names that were present given a particular date.
answer count: 3
possible better answer: http://stackoverflow.com/a/52055617
has comment: http://stackoverflow.com/comment/91061078

http://stackoverflow.com/a/52035787
type: Answer
has comment: http://stackoverflow.com/comment/91021824
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/52035673
has comment: http://stackoverflow.com/comment/91021974
downvote count: 0
has body: I believe what was requested from you is to create a virtual environment with the latest python version. You can do by executing the command: conda create -n my_env python=3.7 Here my_env is simply the name of the environment so you can replace it with anything. Also python 3.7 is the latest python version as of the time of this writing but may need to be changed with later version in the future. Once you've created the environment you can activate it by typing source activate my_env (as the helpful conda message will point out).

http://stackoverflow.com/q/52001974
answer count: 2
tagged with: arrays
downvote count: 0
has answer: http://stackoverflow.com/a/52002476
has title: Fast iteration over numpy array for squared residuals
accepted answer: http://stackoverflow.com/a/52002476
favorite count: 0
has comment: http://stackoverflow.com/comment/90956105
upvote count: 3
linked to: http://stackoverflow.com/q/51887316
tagged with: python
has body: I like to least-squares match data (a numpy array of floats) with many known signal shapes. My code works but is too slow for the many runs I plan to do: import numpy import time samples = 50000 width_signal = 100 data = numpy.random.normal(0, 1, samples) signal = numpy.random.normal(0, 1, width_signal) # Placeholder t0 = time.clock() for i in range(samples - width_signal): data_chunk = data[i:i + width_signal] residuals = data_chunk - signal squared_residuals = residuals**2 summed_residuals = numpy.sum(squared_residuals) t1 = time.clock() print('Time elapsed (sec)', t1-t0) EDIT: Corrected a mistake: First square residuals, then sum them. This takes about 0.2 sec to run on my machine. As I have many datasets and signal shapes, this is too slow. My specific problem does not allow for typical MCMC methods because the signal shapes are too different. It has to be brute force. Typical volumes are 50,000 floats for the data and 100 for the signal. These can vary by a factor of a few. My tests show that: The summing of the data numpy.sum(residuals) eats 90% of the time. I tried Python's sum(residuals) and it is faster for small arrays (~&lt;50 elements) and slower for bigger arrays. Should I insert an if condition? I tried numpy.roll() instead of fetching data directly, and .roll() is slower. Questions: Is there a logical improvement for speed-up? Is there a faster way to sum arrays? I know no C, but if it is much faster I could try that. Can a GPU help? I have many runs to do. If so, where could I find a code snippet to do this?
has comment: http://stackoverflow.com/comment/90954177
has comment: http://stackoverflow.com/comment/90955547
possible better answer: http://stackoverflow.com/a/52004413
has comment: http://stackoverflow.com/comment/90954918
has comment: http://stackoverflow.com/comment/90954798
has comment: http://stackoverflow.com/comment/90960186
type: AnsweredQuestion
score: 3
tagged with: performance
linked to: http://stackoverflow.com/q/41330517
has comment: http://stackoverflow.com/comment/90953763
has comment: http://stackoverflow.com/comment/90958887
has comment: http://stackoverflow.com/comment/90955324
type: Question
tagged with: numpy
has answer: http://stackoverflow.com/a/52004413

http://stackoverflow.com/a/68731926
answers question: http://stackoverflow.com/q/52095337
has comment: http://stackoverflow.com/comment/121480850
has body: An option is to create a single plot then just offset the data. So one set plots above the other.
downvote count: 0
type: Answer
score: 2
upvote count: 2

http://stackoverflow.com/a/51989354
has comment: http://stackoverflow.com/comment/90928356
type: Answer
has body: The third function has a function as a parameter so when called it runs the parameter-function with a 3 as a paramater. try_f(f=square) resolves as square(x=3) which resolves as x*x= 3*3 = 9
answers question: http://stackoverflow.com/q/51989164
score: 0

http://stackoverflow.com/q/52002236
has body: If I have a document like this, with the column names repeated in row 1 and row 2 and the unit of the parameter in row 3, how do I call pd.read_csv such that it creates a data frame with the headers having the column name and unit and the values? Time Speed Torque time speed torque seconds m/s Nm 1 4000 229,5 2 4000 228,7 3 4000 230,1
has title: Combining parameter and value while reading in csv files
type: Question
upvote count: 2
has answer: http://stackoverflow.com/a/52002263
tagged with: pandas
answer count: 1
downvote count: 1
favorite count: 0
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
score: 1

http://stackoverflow.com/comment/91111517
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52080525
type: Comment
has text: Also, just to give you a hard time, this includes "a:c:d" which is *not* in OP's example output

protocol-buffers
tags question: http://stackoverflow.com/q/51967552
tag name: protocol-buffers
tags question: http://stackoverflow.com/q/52067427
type: Tag

http://stackoverflow.com/comment/90998335
type: QuestionComment
has text: yes try removing that geckodriver from the path and then tell me the error
type: Comment
comment on: http://stackoverflow.com/q/52023371
score: 0

http://stackoverflow.com/a/51973054
answers question: http://stackoverflow.com/q/51972716
score: 0
type: Answer
has body: Daniel Roseman's answer succinctly but completely explains both what's wrong with your code, and how to make your code work. But whenever you find yourself trying to use the string names of things instead of the things themselves, there's often a better way in Python. So, it's worth looking for that better way, and deciding if you want to use it. In this case, what you really want is a list of string methods. And in fact, you can directly create a list of string methods: for k in [str.isalnum, str.isalpha, str.isdigit, str.islower, str.isupper]: That's great; these methods are first-class objects in Python, just like strings, or regular functions. (In fact, under the covers, unless you're using Python 2, they just are functions.) But what can you do with them? You can call them, just like functions: for c in s: print(k(c)) If you want to understand how this works, you need to know how normal method calls work. When you write this: s.isalpha() … there are two parts to that. First, s.isalpha looks up the isalpha method on type(s), and binds it to the s instance, returning a bound method object that knows that it wants to call isalpha and that it wants to call it on s. Next, you call that bound method, which is does by calling isalpha and passing s as the first (self) argument. So, you're just doing the same thing manually: str.isalpha just is the isalpha function, and you're calling it with s as the first (self) argument.

http://stackoverflow.com/a/51982605
has body: I am not a Python developper but I can help you get a clue on how to get that working. In theory you can make a POST HTTP request to a local (or remote) Python server who would get the mouse data every x seconds. Example on how to do the client with JS (as I don't know how to do the server part with Python): let pageCoords = []; let isNewDataCaptured = false; // make a request every 1s setInterval(() =&gt; { // checks if the browser captured new mouse data if (isNewDataCaptured) { // create a new vanilla XHR request but can be simplified // with the Axios package. const XHR = new XMLHttpRequest(); // listener for the request completion // resets everything after the data was sent to the Python server XHR.addEventListener( 'load', () =&gt; { isNewDataCaptured = false; pageCoords = [] }); // the server URL and port is an example, // you can replace them with whatever suits you the most XHR.open('POST', 'http://localhost:3000') XHR.send(JSON.stringify(pageCoords)) } }, 1000) document.onmousemove = (e) =&gt; { isNewDataCaptured = true; pageCoords.push({ x: e.pageX, y: e.pageY }) }; All you have to do now is figure out a way to get this data on your Python server and save them via Python as an array or whatever you like to do with them. :D
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/51982047
downvote count: 0
type: Answer

http://stackoverflow.com/a/52026297
has comment: http://stackoverflow.com/comment/91003629
upvote count: 3
has comment: http://stackoverflow.com/comment/91003667
accepted answer of: http://stackoverflow.com/q/52024594
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/52024594
has comment: http://stackoverflow.com/comment/91003441
type: Answer
has body: After simplifying your script to something like this, import ast with open(self.path, "r") as file: for conf in file: conf = conf.replace(": ", "|") conf = conf.replace("\n", "") conf1, conf2 = conf.split("|") conf2 = ast.literal_eval(conf2) print(conf2) It's clear that ast.literal_eval() method throws ValueError exception: Traceback (most recent call last): File "/usr/local/Cellar/python3/3.6.3/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/IPython/core/interactiveshell.py", line 2910, in run_code exec(code_obj, self.user_global_ns, self.user_ns) File "&lt;ipython-input-214-f993e6585bcd&gt;", line 7, in &lt;module&gt; conf2 = ast.literal_eval(conf2) File "/usr/local/Cellar/python3/3.6.3/Frameworks/Python.framework/Versions/3.6/lib/python3.6/ast.py", line 85, in literal_eval return _convert(node_or_string) File "/usr/local/Cellar/python3/3.6.3/Frameworks/Python.framework/Versions/3.6/lib/python3.6/ast.py", line 84, in _convert raise ValueError('malformed node or string: ' + repr(node)) ValueError: malformed node or string: &lt;_ast.Name object at 0x111f50f28&gt; And since you handling it here: try: conf2 = ast.literal_eval(conf2) except (ValueError, SyntaxError): self.new_config() break You getting less config entries than expected, thus InvalidIndex error. Now ast.literal_eval() throws exception since your input can't be evaluated to any known python type or method. Please check the docs to learn how to use it the right way
has comment: http://stackoverflow.com/comment/91003712
score: 3
has comment: http://stackoverflow.com/comment/91003555

http://stackoverflow.com/comment/91112227
score: 0
comment on: http://stackoverflow.com/q/52053761
has text: My goal is to reach something like this: https://www.flickr.com/photos/166586684@N04/shares/6HJM2H That is made by some diffraction software. But it does not have batch treatming of files. So that is why I am trying do it with python. The blue can be replaced with greyscale or something else.
type: Comment
type: QuestionComment

http://stackoverflow.com/a/51984399
accepted answer of: http://stackoverflow.com/q/51984056
type: Answer
upvote count: 3
score: 3
answers question: http://stackoverflow.com/q/51984056
has comment: http://stackoverflow.com/comment/90924803
type: AcceptedAnswer
downvote count: 0
has body: Best way I've found is to use a (6,3,3) transform matrix to turn the symmetric values into a proper symmetric tensor. transf = np.array([[[1.,0.,0.],[0.,0.,0.],[0.,0.,0.]], #11 [[0.,0.,0.],[0.,1.,0.],[0.,0.,0.]], #22 [[0.,0.,0.],[0.,0.,0.],[0.,0.,1.]], #33 [[0.,1.,0.],[1.,0.,0.],[0.,0.,0.]], #12 &amp; 21 [[0.,0.,1.],[0.,0.,0.],[1.,0.,0.]], #13 &amp; 31 [[0.,0.,0.],[0.,0.,1.],[0.,1.,0.]]]).swapaxes(0,1) #23 &amp; 32 e, v = np.linalg.eigh(input.dot(transf)) NON-PROGRAMMING NOTE: Be careful about whether abaqus is outputting real stress/strain or engineering stress/strain, as the resulting transform is different (if I remember correctly for for "real strain" you need the off-diagonal terms to be 0.5 instead of 1.)

http://stackoverflow.com/comment/90944340
comment on: http://stackoverflow.com/a/51997389
score: 0
type: AnswerComment
type: Comment
has text: I'm not surprised. However, you said vectorized and that is what this is. Turns out, you want something that works/won't break you machine but also finishes sometime this year. That I can give you but it will not be vectorized. Give me a few minutes. I'm supposed to be going to sleep, but...

http://stackoverflow.com/comment/90907414
type: QuestionComment
has text: Please see my additional edit.
score: 0
comment on: http://stackoverflow.com/q/51978421
type: Comment

http://stackoverflow.com/comment/91044805
score: 0
has text: I am not so sure what are you trying to accomplish with the code you provided. Should there be a `GPS_thread.join()` before your script is terminated?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52046697

http://stackoverflow.com/a/52026816
has body: password = 123456 "net user Chris "+ password ^^ This won't work because you set password to an integer. Since Python is strongly typed, it won't coerce an integer to a string for you... you have to be explicit and convert it yourself. However, you probably want to use a string for your password anyways: password = '123456'
type: Answer
answers question: http://stackoverflow.com/q/51989239
accepted answer of: http://stackoverflow.com/q/51989239
score: 0
type: AcceptedAnswer

http://stackoverflow.com/comment/118189020
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51991091
score: 6
has text: If you are lazy and want to get the formatted version of `<:emoji_name:emoji_id>` automatically for your emoji, go in Discord and open type in `\:YourEmoji:` (Be sure to replace "YourEmoji with the name of your emoji!) Discord will automatically return a formatted version of `<:emoji_name:emoji_id>` for your emoji. source: https://github.com/Rapptz/discord.py/issues/390#issuecomment-625929794

mininet
tag name: mininet
tags question: http://stackoverflow.com/q/52012754
type: Tag

http://stackoverflow.com/q/51989572
has answer: http://stackoverflow.com/a/51990606
tagged with: python
has comment: http://stackoverflow.com/comment/90928800
type: AnsweredQuestion
has body: I am new to numpy, So I have some problem visualizing the working of the numpy.tensordot() function. According to the documentation of tensordot, the axes are passed in the arguments where axes=0 or 1 represents a normal matrix multiplication whereas axes=2 represents Contraction. Can somebody please explain on how the multiplication would proceed with the given examples? Example-1: a=[1,1] b=[2,2] for axes=0,1 why does it throw an error for axes=2? Example-2: a=[[1,1],[1,1]] b=[[2,2],[2,2]] for axes=0,1,2
linked to: http://stackoverflow.com/q/41870228
type: Question
tagged with: numpy
answer count: 2
score: 5
has title: How does numpy.tensordot function works step-by-step?
has answer: http://stackoverflow.com/a/51990089
accepted answer: http://stackoverflow.com/a/51990089
downvote count: 2
upvote count: 7
has comment: http://stackoverflow.com/comment/90928847
possible better answer: http://stackoverflow.com/a/51990606
favorite count: 0

http://stackoverflow.com/comment/91189397
comment on: http://stackoverflow.com/a/52025990
type: AnswerComment
has text: @ZakkYang, if my comment helped you?
score: 0
type: Comment

http://stackoverflow.com/comment/93551761
comment on: http://stackoverflow.com/a/52059885
score: 0
type: AnswerComment
has text: I meant the solution using python re. The only case it didn't handle for me was : "collegename != 'A and B'"
type: Comment

http://stackoverflow.com/a/52041925
upvote count: 2
has body: Iterate over list of keywords and extract each column from the description one: for name in keywords: df[name] = df['description'].apply(lambda x: True if name in x else False) EDIT: That doesn't solve the problem with R. To do so you could add a space to make sure it's isolated so the code would be: for name in keywords: df[name] = df['description'].apply(lambda x: True if ' '+str(name)+' ' in x else False) But that's really ugly and not optimised. Regular expression should do the trick but I have to look back into it: found it! [ ]*+[str(name)]+[.?!] is better! (and more appropriate)
type: Answer
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/91039089
answers question: http://stackoverflow.com/q/52041823

http://stackoverflow.com/comment/91164400
has text: Is there any chance you can update the question with some more details?
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52066705
type: Comment

http://stackoverflow.com/q/51975045
tagged with: pandas
has body: I have a csv file that looks as so: "3040",0.24948,-0.89496 "3041",0.25344,-0.89496 "3042",0.2574,-0.891 "3043",0.2574,-0.89496 "3044",0.26136,-0.89892 "3045",0.2574,-0.891 "3046",0.26532,-0.9108 "3047",0.27324,-0.9306 "3048",0.23424,-0.8910 This data is "reference" data intended to validate calculations run on other data. Reading the data in gives me this: In [2]: test = pd.read_csv('test.csv', header=0, names=['lx', 'ly']) In [3]: test Out[3]: lx ly 3041 0.25344 -0.89496 3042 0.25740 -0.89100 3043 0.25740 -0.89496 3044 0.26136 -0.89892 3045 0.25740 -0.89100 3046 0.26532 -0.91080 3047 0.27324 -0.93060 3048 0.23424 -0.89100 Which looks as you might expect. Problem is, these values are not quite as they appear and comparisons with them don't work: In [4]: test.loc[3042,'ly'] Out[4]: -0.8909999999999999 Why is it doing that? It seems to be specific to values in the csv that only have 3 places to the right of the decimal, at least so far: In [5]: test.loc[3048,'ly'] Out[5]: -0.891 In [5]: test.loc[3048,'ly'] Out[5]: -0.891 In [6]: test.loc[3047,'ly'] Out[6]: -0.9306 In [7]: test.loc[3046,'ly'] Out[7]: -0.9108 I just want the exact values from the csv, not an interpretation. Ideas? Update: I set float_precision='round_trip' in the read_csv parameters and that seemed to fix it. Document here. What I don't understand is why by default the data is being changed as read in. This doesn't seem good for comparing data sets. Is there a better way to read in data for testing against other dataframes? Update with answer: Changing float_precision is what i went with, although I still don't understand how pandas can misrepresent the data in this way. I get a conversion happens on the import, but 0.891 should be 0.891. For my comparison case rather than testing equivalence I went with something different: # rather than df1 == df2 # I tested as (df1 / df2) - 1 &gt; 1e-14 This works fine for my purposes.
has title: pandas.read_csv changes values on import
has comment: http://stackoverflow.com/comment/90931104
has comment: http://stackoverflow.com/comment/90901031
has answer: http://stackoverflow.com/a/51975307
tagged with: python
has answer: http://stackoverflow.com/a/51975465
accepted answer: http://stackoverflow.com/a/51975465
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/51975307
type: Question
score: 0
answer count: 2

http://stackoverflow.com/q/52022587
answer count: 2
downvote count: 2
has body: I am trying to tokenize each sentence of my pandas series. I try to do as I see in the documentation, using apply, but didn't work: x.apply(nltk.word_tokenize) If I just use nltk.word_tokenize(x) didn't work too, because x is not a string. Does someone have any idea? Edited: x is a pandas series with sentences: 0 A very, very, very slow-moving, aimless movie ... 1 Not sure who was more lost - the flat characte... 2 Attempting artiness with black &amp; white and cle... With x.apply(nltk.word_tokenize) it returns exactly the same: 0 A very, very, very slow-moving, aimless movie ... 1 Not sure who was more lost - the flat characte... 2 Attempting artiness with black &amp; white and cle... With nltk.word_tokenize(x) the error is: TypeError: expected string or bytes-like object
score: -2
has comment: http://stackoverflow.com/comment/91007695
has comment: http://stackoverflow.com/comment/90995628
has comment: http://stackoverflow.com/comment/90996210
tagged with: pandas
possible better answer: http://stackoverflow.com/a/52022954
tagged with: python
has answer: http://stackoverflow.com/a/52022954
favorite count: 0
upvote count: 0
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/52022990
has title: Apply a function to each element of a pandas series
type: AnsweredQuestion
tagged with: nltk
has comment: http://stackoverflow.com/comment/90996766
has comment: http://stackoverflow.com/comment/90995916
has answer: http://stackoverflow.com/a/52022990
has comment: http://stackoverflow.com/comment/90996761
type: Question
linked to: http://stackoverflow.com/q/47769818

http://stackoverflow.com/comment/90877676
type: Comment
score: 1
has text: It worked, why does this make a difference, at the end you are still returning a list just as I did before ?
type: AnswerComment
comment on: http://stackoverflow.com/a/51963732

http://stackoverflow.com/comment/90866609
type: QuestionComment
comment on: http://stackoverflow.com/q/51958064
has text: @EvanCarroll; sorry; I knew the abbreviation and grabbed a link with a merely *similar* name.
score: 0
type: Comment

http://stackoverflow.com/a/52086412
answers question: http://stackoverflow.com/q/52086096
score: 0
has comment: http://stackoverflow.com/comment/91127422
type: Answer
has body: Guys thanks so much for your feedback. For the record this is how I figure it out; option 1 from string import Template message = Template(""" BI Alert process failure The process $fname has failure in the method $method due the error $error . Please take a look the system log and take the required actions in order to solve the problem ASAP and communicate the end users. For more information contact to BI team. """) print(message.substitute(fname = 'hello',method='two',error='hi')) **Option 2 ** message = """ BI Alert process failure The process $fname has failure in the method $method due the error $error . Please take a look the system log and take the required actions in order to solve the problem ASAP and communicate the end users. For more information contact to BI team. """ print(message.format('1','2','3')) By the way, I think option 1 is cleaner. thanks

http://stackoverflow.com/q/51989470
has body: I have this dataframe. a b 0 NaN 2 1 2.0 4 2 NaN 7 I'm trying to create a new column, by checking the type of value in column 'a' and assigning a new label accordingly. The result should look like this: a b c 0 NaN 2 incomplete 1 2.0 4 complete 2 NaN 7 incomplete The code is: if data_frame['a'].isna() == True: data_frame['c'] = 'incomplete' else: data_frame['c'] = 'complete' I'm trying to use a simple if / else statement but I get this error: *** SyntaxError: unexpected EOF while parsing Can someone suggest a solution? Many thanks
accepted answer: http://stackoverflow.com/a/51989769
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/90928794
tagged with: python
has comment: http://stackoverflow.com/comment/90928698
has answer: http://stackoverflow.com/a/51989553
score: 2
type: AnsweredQuestion
upvote count: 2
has title: if value in column is NaN create new column with label incomplete
type: Question
has answer: http://stackoverflow.com/a/51989769
possible better answer: http://stackoverflow.com/a/51989576
has answer: http://stackoverflow.com/a/51989576
has comment: http://stackoverflow.com/comment/90928834
has comment: http://stackoverflow.com/comment/90928683
answer count: 3
tagged with: pandas
downvote count: 0

http://stackoverflow.com/q/51986128
score: 1
has title: Python: Tkinter TclError: can't invoke "image" command
answer count: 2
upvote count: 1
favorite count: 0
possible better answer: http://stackoverflow.com/a/51986582
tagged with: spyder
tagged with: python
has answer: http://stackoverflow.com/a/51986582
tagged with: python-3.x
tagged with: compiler-errors
tagged with: tkinter
downvote count: 0
accepted answer: http://stackoverflow.com/a/51987911
type: Question
type: AnsweredQuestion
has body: preface: I have currently tried most things and there are few qusestions asked on stackoverflow on this question and i cant seem to wrap my head around it so im going to need some help application: the purpose of this program is to animate an oval and a picture, the oval works fine, but the picture is struggling, you could remove the image or alien2 and the program should run fine. CODE image form from tkinter import * import time from PIL import Image,ImageFilter from PIL import ImageTk class alien(object): def __init__(self): self.root = Tk() self.canvas = Canvas(self.root, width=400, height = 400) self.canvas.pack() self.cardPath = Image.open('bubble.png') self.resCard = cardPath.resize((100,100)) self.CardVar = ImageTk.PhotoImage(resCard,master=root) self.alien1 = self.canvas.create_oval(20, 260, 120, 360, outline='white',fill='blue') self.alien2 = self.canvas.create_image(100,100,CardVar,anchor=CENTER) self.canvas.pack() self.root.after(0, self.animation) self.root.mainloop() def animation(self): track = 0 while True: x = 5 y = 0 if track == 0: for i in range(0,51): time.sleep(0.025) self.canvas.move(self.alien1, x, y) self.canvas.move(self.alien2, x, y) self.canvas.update() track = 1 print("check") else: for i in range(0,51): time.sleep(0.025) self.canvas.move(self.alien1, -x, y) self.canvas.move(self.alien2, -x, y) self.canvas.update() track = 0 print(track) alien() ERROR: image runfile('/Users/Stian/.spyder-py3/animation_test.py', wdir='/Users/Stian/.spyder-py3') Traceback (most recent call last): File "", line 1, in runfile('/Users/Stian/.spyder-py3/animation_test.py', wdir='/Users/Stian/.spyder-py3') File "/anaconda3/lib/python3.6/site-packages/spyder/utils/site/sitecustomize.py", line 705, in runfile execfile(filename, namespace) File "/anaconda3/lib/python3.6/site-packages/spyder/utils/site/sitecustomize.py", line 102, in execfile exec(compile(f.read(), filename, 'exec'), namespace) File "/Users/Stian/.spyder-py3/animation_test.py", line 57, in alien() F…
has comment: http://stackoverflow.com/comment/90922503
has answer: http://stackoverflow.com/a/51987911

http://stackoverflow.com/comment/137667066
has text: Is "caching" really necessary in hao peng's answer? Won't most interpreters already do this kind of optimization?
type: Comment
comment on: http://stackoverflow.com/a/64717799
score: 0
type: AnswerComment

http://stackoverflow.com/comment/91027780
comment on: http://stackoverflow.com/q/52038755
has text: How would you use this exactly? It seems this is likely to be an XY problem you're trying to address here...
type: Comment
type: QuestionComment
score: 2

http://stackoverflow.com/comment/90866169
has text: Yes, that would be correct, I suppose 4D was not the correct way to describe it.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51957840
score: 0

http://stackoverflow.com/comment/104606323
type: AnswerComment
score: 0
type: Comment
has text: They do, I just tried using tensorflow 2.0 and got intermediate outputs using the first method above.
comment on: http://stackoverflow.com/a/52039648

http://stackoverflow.com/comment/90998687
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52023969
has text: Thanks for reply! i do not want to use celery the way i have implemented the postpone method works perfect!
score: 0

http://stackoverflow.com/comment/91125152
type: QuestionComment
score: 1
has text: Also, what's up with the three year dry spell for accepting answers?
type: Comment
comment on: http://stackoverflow.com/q/52087335

http://stackoverflow.com/q/52095282
tagged with: selenium
type: Question
tagged with: firefox
answer count: 1
tagged with: python-2.7
score: 0
tagged with: download
linked to: http://stackoverflow.com/q/25251583
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/52099779
has body: I just programmed the following code for downloading a document to a specific folder, however it keeps downloading in the default folder Downloads, what is the problem?? THANKS IN ADVANCE FOR HELPING from selenium import webdriver from selenium.webdriver.common.keys import Keys from selenium.webdriver.firefox.options import Options from selenium.webdriver import ActionChains from selenium.webdriver.common.action_chains import ActionChains import time import os options = Options(); options.set_preference("browser.download.dir","/Desktop/test-download"); options.set_preference("browser.download.folderList",2); options.set_preference("browser.download.manager.showWhenStarting", False); options.set_preference("browser.helperApps.neverAsk.saveToDisk", "application/vnd.ms- powerpoint"); driver = webdriver.Firefox(firefox_options=options); driver.get("https://legacy.python.org/doc/essays/ppt/lwnyc2002/intro22.ppt") driver.find_element_by_xpath("**xpath of document**").click()
has title: Downloading documents Selenium and Firefox

http://stackoverflow.com/a/52064361
accepted answer of: http://stackoverflow.com/q/52059974
has body: In the code you have provided I believe the fix you are looking for is to change this: label.after(1000 , lambda: label.destroy()) To this: label.after(1000, label.master.destroy) You need to destroy label.master (I am guessing this is actually a root window) because if you do not then you end up with a big box on the screen that is not transparent. That said I am not sure why you are writing your app in this way. I guess it works and I was not actually aware you could do this but still I personally would write it using a root window to work with. import tkinter as tk root = tk.Tk() label = tk.Label(root, text='Text on the screen', font=('Times New Roman','80'), fg='black', bg='white') label.pack() root.overrideredirect(True) root.geometry("+250+250") root.wm_attributes("-topmost", True) root.wm_attributes("-disabled", True) root.wm_attributes("-transparentcolor", "white") root.after(1000, root.destroy) root.mainloop()
type: Answer
upvote count: 6
answers question: http://stackoverflow.com/q/52059974
score: 5
type: AcceptedAnswer
downvote count: 1

http://stackoverflow.com/a/54092001
downvote count: 1
score: 3
has body: I encountered the same issue using this MANIFEST.in: include setup.json recursive-include . *.coffee the .coffee files were present in the .tar.gz file but not installed the problem was not resolved by adding zip_safe=False it was resolved by switching from recursive-include to individual includes This is using wheel 0.32.3 twine 1.12.1 setuptools 39.2.0
upvote count: 4
answers question: http://stackoverflow.com/q/52013228
type: Answer

http://stackoverflow.com/comment/90899281
type: QuestionComment
comment on: http://stackoverflow.com/q/51973147
type: Comment
has text: Just added the full code of ImageDataGenerator. My Keras is 2.1.6
score: 0

http://stackoverflow.com/comment/90938911
score: 0
type: QuestionComment
has text: If you want to remove the string `Bar:`, why are you calling `replace` with the completely different string `"bar:u`? Even without any other errors, that’s pretty obviously not going to work.
type: Comment
comment on: http://stackoverflow.com/q/51994368

http://stackoverflow.com/comment/90937035
type: QuestionComment
score: 1
has text: provide a [mcve]
comment on: http://stackoverflow.com/q/51993679
type: Comment

http://stackoverflow.com/comment/90965631
comment on: http://stackoverflow.com/q/52007455
has text: @greenapps Logs are too big to copy-paste them to my post.
score: 0
type: QuestionComment
type: Comment

deep-learning
tags question: http://stackoverflow.com/q/51995267
tags question: http://stackoverflow.com/q/52046971
tags question: http://stackoverflow.com/q/52019658
tags question: http://stackoverflow.com/q/52000103
tags question: http://stackoverflow.com/q/52082538
tags question: http://stackoverflow.com/q/52019226
tags question: http://stackoverflow.com/q/52001272
tags question: http://stackoverflow.com/q/52028365
tags question: http://stackoverflow.com/q/52056382
tags question: http://stackoverflow.com/q/51963377
tags question: http://stackoverflow.com/q/52014867
tags question: http://stackoverflow.com/q/52094498
tags question: http://stackoverflow.com/q/51995977
tags question: http://stackoverflow.com/q/52096123
tags question: http://stackoverflow.com/q/51964385
tags question: http://stackoverflow.com/q/51968293
tags question: http://stackoverflow.com/q/52017600
tags question: http://stackoverflow.com/q/51980938
tags question: http://stackoverflow.com/q/52063402
tags question: http://stackoverflow.com/q/51960225
tags question: http://stackoverflow.com/q/52088361
tags question: http://stackoverflow.com/q/52018645
tags question: http://stackoverflow.com/q/52024253
tags question: http://stackoverflow.com/q/52028474
tags question: http://stackoverflow.com/q/52069454
tags question: http://stackoverflow.com/q/52024026
tags question: http://stackoverflow.com/q/51998073
tags question: http://stackoverflow.com/q/51959507
tags question: http://stackoverflow.com/q/52060483
tags question: http://stackoverflow.com/q/51972647
tags question: http://stackoverflow.com/q/52030554
tags question: http://stackoverflow.com/q/52048171
type: Tag
tags question: http://stackoverflow.com/q/52031587
tags question: http://stackoverflow.com/q/51968626
tags question: http://stackoverflow.com/q/52033171
tags question: http://stackoverflow.com/q/52060438
tags question: http://stackoverflow.com/q/52034983
tags question: http://stackoverflow.com/q/52044361
tags question: http://stackoverflow.com/q/52090857
tags question: http://stackoverflow.com/q/52015010
tags question: http://stackoverflow.com/q/52023702
tag name: deep-learning
tags question: http://stackoverflow.com/q/52017665
tags question: http://stackoverflow.com/q/52092999
tags question: http://stackoverflow.com/q/51960471

http://stackoverflow.com/comment/90865851
type: QuestionComment
type: Comment
score: 1
comment on: http://stackoverflow.com/q/51957706
has text: It really comes down to whether you consider `math` to be part of the "public interface" of `my_own_module`. Since you don't have an `__all__`, and it doesn't start with an underscore, the default answer is "yes", but the default doesn't really matter; it's entirely up to how you want to think about it.

http://stackoverflow.com/comment/91060584
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52055086
type: AnswerComment
has text: I down voted because, the fix you have given is also going to throw error for him. In which way it is supportive?

http://stackoverflow.com/comment/91164868
type: Comment
comment on: http://stackoverflow.com/a/52106743
score: 0
type: AnswerComment
has text: No problem. I've updated my question. Take a look http://www.django-rest-framework.org/api-guide/permissions/

http://stackoverflow.com/a/70969822
score: 14
type: Answer
upvote count: 14
has body: Just Uninstall and reinstall the pyodbc to solve your issue it worked for me. use pip uninstall pyodb and confirm with Y to uninstall and then reinstall using pip install pyodbc
answers question: http://stackoverflow.com/q/52085191
downvote count: 0

pyqt5
tags question: http://stackoverflow.com/q/52032036
tags question: http://stackoverflow.com/q/52108256
type: Tag
tags question: http://stackoverflow.com/q/51961472
tags question: http://stackoverflow.com/q/52076299
tags question: http://stackoverflow.com/q/52036021
tags question: http://stackoverflow.com/q/52020988
tags question: http://stackoverflow.com/q/52085223
tags question: http://stackoverflow.com/q/51989918
tags question: http://stackoverflow.com/q/51976683
tags question: http://stackoverflow.com/q/52026571
tags question: http://stackoverflow.com/q/52106515
tags question: http://stackoverflow.com/q/51956660
tags question: http://stackoverflow.com/q/52046551
tags question: http://stackoverflow.com/q/51966124
tags question: http://stackoverflow.com/q/52109130
tags question: http://stackoverflow.com/q/51989523
tags question: http://stackoverflow.com/q/51962262
tags question: http://stackoverflow.com/q/51989785
tags question: http://stackoverflow.com/q/52020539
tags question: http://stackoverflow.com/q/52055350
tags question: http://stackoverflow.com/q/51997428
tags question: http://stackoverflow.com/q/52111372
tags question: http://stackoverflow.com/q/52042070
tags question: http://stackoverflow.com/q/52098156
tags question: http://stackoverflow.com/q/52026352
tags question: http://stackoverflow.com/q/52066040
tags question: http://stackoverflow.com/q/51980787
tags question: http://stackoverflow.com/q/52044772
tags question: http://stackoverflow.com/q/51957955
tags question: http://stackoverflow.com/q/52087527
tags question: http://stackoverflow.com/q/51993679
tags question: http://stackoverflow.com/q/52073747
tags question: http://stackoverflow.com/q/52100621
tag name: pyqt5
tags question: http://stackoverflow.com/q/52071203
tags question: http://stackoverflow.com/q/52040205
tags question: http://stackoverflow.com/q/52082520
tags question: http://stackoverflow.com/q/52004018
tags question: http://stackoverflow.com/q/52040538
tags question: http://stackoverflow.com/q/52031590
tags question: http://stackoverflow.com/q/52010524
tags question: http://stackoverflow.com/q/52049644
tags question: http://stackoverflow.com/q/52087437

http://stackoverflow.com/comment/133946876
type: Comment
has text: You have it in reverse: it's apparently impossible _not_ to fail. I have tried to get `coverage` to run even with some failing testcases and it can't be done afaik. Even have an SOF on it: https://stackoverflow.com/questions/75941872/how-to-run-code-coverage-to-completion-with-the-report-even-if-pytest-is-failing
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/52107910

numerical-methods
tags question: http://stackoverflow.com/q/52020775
type: Tag
tags question: http://stackoverflow.com/q/51957207
tag name: numerical-methods

http://stackoverflow.com/q/52022790
has title: can’t inherit from superclass
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/91615808
downvote count: 2
has comment: http://stackoverflow.com/comment/91616220
score: -2
tagged with: inheritance
has answer: http://stackoverflow.com/a/52022807
accepted answer: http://stackoverflow.com/a/52022807
tagged with: class
has comment: http://stackoverflow.com/comment/90995846
favorite count: 0
upvote count: 0
tagged with: python
has body: I have a simple code like below where the class Employee should inherit from the class Person. class Person: def __init__(self, firstname, lastname, age): self.firstname = firstname self.lastname = lastname self.age = age def getname(self): return self.firstname, self.lastname def getage(self): return self.age class Employee(Person): def __init__(self, first, last, empid, age): Person.__init__(self, first, last, age): self.empid = empid def getemp(self): return self.getname() + ", " + self.empid employee = Employee("Bart", "Simpson", 1006, 16) print(employee.getemp()) It gives me this error: File "/tmp/pyadv.py", line 156 Person.__init__(self, first, last, age): ^ SyntaxError: invalid syntax I checked Python documentation about classes and it didn’t have that superclass initialization inside the __init__() of the subclass. But I found that in other websites like here, where Dog inherits from Pet. So, what am I missing?
possible better answer: http://stackoverflow.com/a/52022804
tagged with: superclass
tagged with: instantiation
has answer: http://stackoverflow.com/a/52022804
type: AnsweredQuestion

http://stackoverflow.com/a/51996618
downvote count: 0
upvote count: 2
has comment: http://stackoverflow.com/comment/90981304
has comment: http://stackoverflow.com/comment/90972526
has comment: http://stackoverflow.com/comment/90989114
has body: The collections.defaultdict might be a good approach to solve this problem. from collections import defaultdict d = defaultdict(list) a = [{"from": "Location1", "to": "Location2"}, {"from": "Location1", "to": "Location3"}, {"from": "Location1", "to": "Location4"}, {"from": "Location1", "to": "Location5"}] for o in a: d[o['from']].append(o['to']) print(d)
has comment: http://stackoverflow.com/comment/90985834
type: Answer
answers question: http://stackoverflow.com/q/51996545
score: 2

http://stackoverflow.com/q/52051802
tagged with: python-3.x
type: UnansweredQuestion
tagged with: django
tagged with: python
has body: I have these models: class Unit(AppModel): name = models.CharField(max_length=255) def __str__(self): return self.name class Item(AppModel): title = models.CharField(max_length=255) units = models.ManyToManyField("Unit", symmetrical=False, related_name="items") def __str__(self): return self.title + self.units class Invoice(AppModel): items = models.ManyToManyField("Item", symmetrical=False, related_name="invoices") def __str__(self): return "invoice_" + self.id As you can see, we have an Item with multiple units and an Invoice with multiple items. But, I want each item in an Invoice to have a single unit only. How to achieve that? i.e, some_item.units should return all its type of units. Whereas, for item in some_invoice.items: return item.units should return a single unit. Is there any other way to implement it? A new database design?? Then How? Help.. Note: I was not able to frame the title of this Post. Feel free to do so. Thanks.
has answer: http://stackoverflow.com/a/52052524
has answer: http://stackoverflow.com/a/52052414
tagged with: django-models
tagged with: django-forms
type: Question
has title: Django: ManyToMany Field on a model
score: 0
answer count: 3
has answer: http://stackoverflow.com/a/52067903

http://stackoverflow.com/comment/91309077
score: 0
comment on: http://stackoverflow.com/q/52057307
type: Comment
type: QuestionComment
has text: Nice happy to help. I made a quick answer out of my comment, could you please mark is as correct. So that everybody sees that your issue is resolved.

http://stackoverflow.com/a/52762805
accepted answer of: http://stackoverflow.com/q/52029827
upvote count: 3
answers question: http://stackoverflow.com/q/52029827
score: 3
type: AcceptedAnswer
downvote count: 0
has body: You are using an older Tensorflow version, which is probably not compatible with your current python version. check your computer configuration and install a matching Tensorflow version with the help of the following table: https://www.tensorflow.org/install/pip#package-location Install a python version that matches your Tensorflow version (also can be found in the link provided above) Check your python version: $ python3 --version Check your Tensorflow version:$ pip3 list | grep tensorflow If versions are matching as stated in the table above you'd probably get rid of the error I've encountered a similar problem when I was trying to run the Tensorflow image retraining script: https://github.com/tensorflow/hub/raw/master/examples/image_retraining/retrain.py In my case the problem was caused by Tensorflow 1.11.0 not being compatible with python 3.7.0. Steps that solved the problem for me: Uninstall python 3.7.0. Install python 3.6.0. I run the script again, and now it run properly Hope it will hellp :)
type: Answer

http://stackoverflow.com/q/51994481
tagged with: dataframe
score: 0
answer count: 1
has title: select rows in dataframe not in different dataframe with different shape arrays and where object is not iterable
tagged with: python
has comment: http://stackoverflow.com/comment/90938760
type: AnsweredQuestion
tagged with: uuid
has answer: http://stackoverflow.com/a/51995485
accepted answer: http://stackoverflow.com/a/51995485
has comment: http://stackoverflow.com/comment/90940291
tagged with: select
type: Question
linked to: http://stackoverflow.com/q/50284375
has body: I'm trying to select rows in a dataframe that don't share a uniqueID with an interim dataframe but when I use the following NotProcessed= FileListDF.loc[FileListDF['DocID'] != InterimDF.DocID.tolist()] I get ValueError: Arrays were different lengths: 255 vs 246 when I'm expecting a dataframe containing 9 rows that are in FileListDF but not in InterimDF This question appears to have encountered a similar issue but the answer isn't clear and when I try it I get 'UUID' object is not iterable I'm not sure if its connected to me using uuid.uuid4() to create the DocID in the 1st instance Sample Data FileListDF..to_json &lt;bound method NDFrame.to_json of Class DocID 0 CC c2571c68-0705-4c87-a42b-0971a73fedf4 1 CC ab317908-8720-47ce-a8f6-453169259e48 2 CC 2b3d1aee-b4f6-4278-9db2-c7b6819bd14f 3 CC 9d4b9084-f623-445c-86d9-0458d6fb4135 4 CC afe9dbb5-38a2-4c4e-9640-b1da1d37b66f 5 CC 56fa7edb-5020-44e7-98bc-5b0878fbf9ac 6 CC 7c27bcb8-b381-465e-a6e9-edc38cf24e5a 7 CC a56e6f13-bf05-474a-9930-5f0ebad33eba 8 CC 81c31d76-cec3-4f1c-8ec1-107ecc1169d4 9 CC 1f8acf61-0a08-4b42-8ad1-38eeebc85ff2 10 CC d6a6704c-21c6-4dc5-b9bd-de9e67ee7970 11 CC d63dde24-9a2b-410d-aa7d-6a854b646a12 12 CC a80367f9-36af-45bd-878e-d19461a3d3df 13 CC 31f74aff-e8df-43bb-a7d4-314caea6de20 14 CC 99052ee4-2481-4c81-92dd-81b446e76c15 15 CC 3827d0b4-5d0a-490a-a561-bf631bae6492 16 CC fdbde364-776d-4532-8aca-874144a85df8 17 CC 4dfa630f-20b0-4a9e-bcf0-cdd4f18bb215 18 CC f5b16b14-a058-4f2d-8461-25e68b02c68b 19 CC a9f23eee-5b44-4d4e-baf8-19b78b4e3508 20 CC 344bfb49-3b22-4e2a-b815-a9eb46cbed1b 21 CC ade5b2c3-5962-4d6d-9252-4f670b127682 22 CC 43fa1fb2-3681-4372-ab5a-f12059b3741c 23 CC 77f19056-fef8-4353-9740-01afa5557f47 24 CC 1c7cfc8a-57c6-4ad3-bce7-63b006352ed1 25 CC e6db5e3c-4b3e-4b27-9558-e7334032c9c0 26 CC 68adb3b6-dfeb-4645-8ed2-610ae896e8c4 27 CC c0163ee2-9e34-4636-a734-051151c50f29 28 CC 7b7d8549-8697-4b19-a033-e0068f5aa4d7 29 CC 7a976925-57c5-4972-a9e6-278dd322f6b4 .. ... ... 225 JA cd3a901e-a077-472e-a100-f082f011c…

http://stackoverflow.com/q/52080948
has comment: http://stackoverflow.com/comment/92057744
has comment: http://stackoverflow.com/comment/92074163
has title: call a python script from ElasticSearch daily
tagged with: logstash
tagged with: logstash-jdbc
score: 0
tagged with: elasticsearch
tagged with: python
answer count: 0
type: UnansweredQuestion
tagged with: django
has body: I have logstash scheduled to read data from database every day at 3:00 A.M.. What I want to do is whenever the index is read I want to call a Python Function defined in my Django Project that will process index and then update another index in ElasticSearch. Basically, I am fetching all transactions done daily via logstash and then want to run python script, if fetch was successful then process transactions (apply some machine learning stuff) and save result as another index in Elasticsearch so I want help with: Call a python script from Elasticsearch when index is updated I was reading: ElasticSearch docs for python script but couldn't get as am new to ES and couldn't get how I will schedule it. Though I can make the script running as separate thread in Django, and process ES data, I want to call it from ES, either daily or whenever the index is called. If I can call multiple scripts that will be great add, as different scripts prcodess differently. Question on ES faq UPDATED also tried: script_lang =&gt; "python" script_type =&gt; "file" # inline script =&gt; "script.py" in the output of Logstash.conf file, didn't seem to work. My Script is saved in config/scripts folder Script tag in output plugin of logstash docs here. UPDATED 2 Also did: bin/logstash-plugin install logstash-output-exec and then: output { stdout { codec =&gt; json_lines } exec { command =&gt; "echo hi" # This works but for each document, hi, hi, hi... -- If I replace with python path\script.py } } As there is no way to execute exec only once as by Elastic discussion
type: Question

http://stackoverflow.com/comment/90935134
has text: @Aparajuli, In todays NN architecture hundreds of biases are negligible compare to millions of parameters. Unfortunately, I couldn't find mathematical reason.
comment on: http://stackoverflow.com/a/51988522
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/q/51988224
accepted answer: http://stackoverflow.com/a/51988533
upvote count: 2
tagged with: pandas
answer count: 1
linked to: http://stackoverflow.com/q/32213219
has comment: http://stackoverflow.com/comment/90926624
favorite count: 0
tagged with: python
type: AnsweredQuestion
score: 2
has title: transpose pandas df column data to rows
downvote count: 0
type: Question
has body: I have a df as the following email | date | type _________________________ xy@xy.com | 6/1 | order xy@xy.com | 6/1 | return cd@xy.com | 6/2 | return ab@xy.com | 6/2 | return I'm trying to individualize the type of column into each row keeping the data email | date | order | return _________________________________ xy@xy.com | 6/1 | 1 | 0 xy@xy.com | 6/1 | 0 | 1 cd@xy.com | 6/2 | 0 | 0 ab@xy.com | 6/2 | 0 | 0 I've been trying to use pd.melt but the output doesn't seem to be what i'm looking for. referenced from Pandas dataframe transpose with original row and column values
has answer: http://stackoverflow.com/a/51988533

http://stackoverflow.com/comment/91000207
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52020441
type: AnswerComment
has text: Ok, I do, but your colors are somehow really much darker than mine. Can you post the full code just in case, please.

http://stackoverflow.com/comment/91103794
has text: One: if you can't fit an entire sequence (regarding length in steps) in a single batch. Two: if you want something like predicting the future by taking the outputs as inputs as if you never stopped the processing.
score: 0
type: Comment
comment on: http://stackoverflow.com/q/52071751
type: QuestionComment

amazon-ec2
tags question: http://stackoverflow.com/q/52016352
tags question: http://stackoverflow.com/q/52087698
type: Tag
tags question: http://stackoverflow.com/q/52109398
tags question: http://stackoverflow.com/q/51969465
tags question: http://stackoverflow.com/q/52083327
tags question: http://stackoverflow.com/q/52084215
tags question: http://stackoverflow.com/q/52056897
tags question: http://stackoverflow.com/q/52052946
tags question: http://stackoverflow.com/q/51965420
tag name: amazon-ec2
tags question: http://stackoverflow.com/q/51962092
tags question: http://stackoverflow.com/q/51971441
tags question: http://stackoverflow.com/q/52018545

http://stackoverflow.com/comment/91112738
type: AnswerComment
has text: My training generator returns (32,50,88) for the features and (32,50,88) for the labels. I think It should be this way, in order to learn the continuity of the values. Or should the labels be just (32,88) ? You helped me already, but could you clarify me this detail? Thanks!
type: Comment
comment on: http://stackoverflow.com/a/52080268
score: 0

http://stackoverflow.com/q/51985371
has comment: http://stackoverflow.com/comment/90920168
has comment: http://stackoverflow.com/comment/90920510
type: AnsweredQuestion
has body: I have a program which reverses the order of a list if the list consists of integers alone converts the list items to uppercase if the list contains words only returns the same list if the list members don’t satisfy either of these two criteria I have written it though I want the program to loop through the list, if the value of type int -append and when next value of type string display original list and end loop I think that my code my code doesn't do it well: def is_int(val): if type(val) == int: return True else: return False def is_string(val): if type(val) == str: return True else: return False def is_float(val): if type(val) == float: return True else: return False def invert(val): k = len(val) for i in range(k//2): a = val[i] val[i] = val[k-1] val[k-1] = a print(val) lis = ["a","c",2,7] lim = [] tart = 1 for x in lis: if is_int(x) == True and is_int(lis[tart:]) == True: lim.append(x) tart += 1 elif is_string(x) == True and is_string(lis[tart:]) == True : x = x.upper() lim.append(x) tart += 1 else: print(lis) break invert(lim)
score: 1
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/51985551
downvote count: 0
has title: Check if list consists of integers alone
tagged with: python
favorite count: 0
accepted answer: http://stackoverflow.com/a/51985551
possible better answer: http://stackoverflow.com/a/51985628
has answer: http://stackoverflow.com/a/51985628
upvote count: 1

http://stackoverflow.com/a/51985181
answers question: http://stackoverflow.com/q/51984993
has comment: http://stackoverflow.com/comment/90919930
has body: You can create a series consisting of groupwise "last" ingredients, then filter these out. Note, for this purpose, that NaN ingredients don't get removed. s = df.sort_values('ingredients')\ .groupby('customer')['ingredients']\ .transform('last').sort_index() df = df[df['ingredients'] != s] print(df) ingredients customer ordered 0 eggs Badger 1.0 1 NaN Badger 1.0 3 eggs Shopkeeper 0.0 6 eggs Pepperpots 1.0 8 NaN NaN NaN With this solution, you can omit df.sort_values(['customer', 'ingredients'], inplace=True), as GroupBy + transform as implemented above aligns by index.
downvote count: 0
upvote count: 2
type: Answer
score: 2

cmd
tags question: http://stackoverflow.com/q/52050454
type: Tag
tag name: cmd

http://stackoverflow.com/comment/91096442
comment on: http://stackoverflow.com/a/52073111
type: Comment
has text: I tried to apply it to a dataframe other than the example and it says: `IndexError: index 0 is out of bounds for axis 0 with size 0`. Do you know why?
type: AnswerComment
score: 0

http://stackoverflow.com/comment/90949158
comment on: http://stackoverflow.com/a/51999765
score: 0
type: Comment
has text: What is `result` ? Another df? Or some dict?
type: AnswerComment

http://stackoverflow.com/a/52020583
has body: It is always better to use built-in modules for things sensitive like password. One way of doing is following: import getpass number = 1234567890 first = 'X' * max(0,len(str(number)[:-4])) last = str(number)[-4:] n = first + last print(n) # part 2 p = getpass.getpass(prompt='Enter the number : ') if int(p) == 123: print('Welcome..!!!') else: print('Please enter correct number..!!!') If you don't want to display typed password just print: print('######') It does not have to be of the same length you just have to print something.
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/90991621
accepted answer of: http://stackoverflow.com/q/52020413
answers question: http://stackoverflow.com/q/52020413
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/90991637
type: Answer

http://stackoverflow.com/comment/90935183
has text: @abarnert Yes, I've called the colorama.init() function within my program before using the input() function to display the text. Even with that, the sequence doesn't get translated, and instead gets roughly printed to the console.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51992263

http://stackoverflow.com/comment/91355364
type: AnswerComment
type: Comment
has text: Thanks a lot KaiserKatze! I tried the code and it stuck in load_url() not finishing session.get(url). I will do some debugging, maybe removing some locking or test with a simpler action rather than read url, because I can see first 2 workers launched but immediately other urls also submitted, maybe blocking the queue or something?
comment on: http://stackoverflow.com/a/51985687
score: 0

http://stackoverflow.com/comment/91040334
comment on: http://stackoverflow.com/q/52043153
score: 0
type: Comment
type: QuestionComment
has text: Thanks, @coldspeed. `map` worked. However, why would one prefer `map` over `replace` in this case? Both seem to work.

http://stackoverflow.com/a/52031422
type: Answer
accepted answer of: http://stackoverflow.com/q/52030945
answers question: http://stackoverflow.com/q/52030945
has comment: http://stackoverflow.com/comment/116651653
score: 10
upvote count: 10
has body: Iterating in Python can be quite slow. It's always best to "vectorise" and use numpy operations on arrays as much as possible, which pass the work to numpy's low-level implementation, which is fast. cosine_similarity is already vectorised. An ideal solution would therefore simply involve cosine_similarity(A, B) where A and B are your first and second arrays. Unfortunately this matrix is 500,000 by 160,000 which is too large to do in memory (it throws an error). The next best solution then is to split A (by rows) into large blocks (instead of individual rows) so that the result still fits in memory, and iterate over them. I find for your data that using 100 rows in each block fits in memory; much more and it doesn't work. Then we simply use .max and get our 100 maxes for each iteration, which we can collect together at the end. This way strongly suggests we do an additional time save, though. The formula for the cosine similarity of two vectors is u.v / |u||v|, and it is the cosine of the angle between the two. Because we're iterating, we keep recalculating the lengths of the rows of B each time and throwing the result away. A nice way around this is to use the fact that cosine similarity does not vary if you scale the vectors (the angle is the same). So we can calculate all the row lengths only once and divide by them to make the rows unit vectors. And then we calculate the cosine similarity simply as u.v, which can be done for arrays via matrix multiplication. I did a quick test of this and it was about 3 times faster. Putting it all together: import numpy as np # Example data A = np.random.random([500000, 100]) B = np.random.random([160000, 100]) # There may be a proper numpy method for this function, but it won't be much faster. def normalise(A): lengths = (A**2).sum(axis=1, keepdims=True)**.5 return A/lengths A = normalise(A) B = normalise(B) results = [] rows_in_slice = 100 slice_start = 0 slice_end = slice_start + rows_in_slice while slice_end &lt;= A.shape[0]…
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/a/52032830
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/91089781
has comment: http://stackoverflow.com/comment/91087638
type: Answer
has body: I believe need: df = pd.concat([pd.read_csv(f, na_values = ['#VALUE!', '#DIV/0!'], keep_default_na = True) for f in glob.glob('city Text Files/*.txt')]) #get only numeric columns cols = df.select_dtypes(np.number).columns #create DataFrame with same size as original with means df_average = df.groupby('Date')[cols].transform('mean') print (df_average) $/SQFT DOM 0 218.333333 21.666667 1 216.000000 63.000000 2 294.000000 30.500000 3 218.333333 21.666667 4 216.000000 63.000000 5 294.000000 30.500000 6 218.333333 21.666667 7 294.000000 30.500000 #substract only numeric columns df[cols] = (df[cols] - df_average ).round(1) print (df) Record City Date $/SQFT DOM 0 M12 Memphis 01/01/2018 -118.3 -3.7 1 M13 Memphis 01/02/2018 -104.0 10.0 2 M14 Memphis 01/03/2018 NaN NaN 3 D73 Dallas 01/01/2018 81.7 14.3 4 D74 Dallas 01/02/2018 104.0 -10.0 5 D75 Dallas 01/03/2018 31.0 12.5 6 A19 Atlanta 01/01/2018 36.7 -10.7 7 A20 Atlanta 01/03/2018 -31.0 -12.5
upvote count: 2
accepted answer of: http://stackoverflow.com/q/52032682
answers question: http://stackoverflow.com/q/52032682
score: 2

http://stackoverflow.com/comment/91121049
type: QuestionComment
has text: Would you like to provide which version of python you are using? And could you attach with a link to this Canopy-thing (I haven't heard of it before).
comment on: http://stackoverflow.com/q/52085139
score: 0
type: Comment

http://stackoverflow.com/comment/91142200
type: QuestionComment
comment on: http://stackoverflow.com/q/52081155
has text: Please [edit] your question to explain what the script is trying to do. It would help if you also showed what the output should be for the file you have given (at least the start of it).
score: 0
type: Comment

http://stackoverflow.com/comment/90961855
score: 0
type: AnswerComment
type: Comment
has text: You commented saying thanks that solved my problem, then removed comment, edited post etc. It is fine, you realised on your own.
comment on: http://stackoverflow.com/a/52005599

http://stackoverflow.com/comment/91025967
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52037697
score: 0
has text: OK I managed to see the image. However I did find a snippet that states that in order to use `imshow` you need to also use `cv2.waitKey(0)`

http://stackoverflow.com/a/52064722
answers question: http://stackoverflow.com/q/52064496
type: Answer
accepted answer of: http://stackoverflow.com/q/52064496
score: 2
upvote count: 2
has body: If I'm reading your question and edits right you're looking to return 'readthispart', correct? If so you need to look into using look-behinds in combination with search. See https://docs.python.org/2/library/re.html. re.search("(?&lt;=\^).*",myinput)
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/91080780

http://stackoverflow.com/q/52060597
type: Question
tagged with: numpy
has body: This is Sample Data: import pandas as pd d = {'name': ['john', 'tom', 'phill', 'nero', 'bob', 'rob'], 'date1' :['2015-10-05', '2015-01-05', '2015-07-06', '2015-10-06', '2015-10-06', '2015-12-08'], 'date2' :['2015-10-05', '2015-01-05', '2015-07-06', '2015-08-06', '2015-09-06', '2015-12-08'], 'date3' :['2015-07-05', '2015-11-05', '2015-07-06', '2015-11-06', '2015-05-06', '2015-05-08']} df2 = pd.DataFrame(data = d) df2['date1'] = pd.DatetimeIndex(df2['date1']) df2['date2'] = pd.DatetimeIndex(df2['date2']) df2['date3'] = pd.DatetimeIndex(df2['date3']) This is the table Problem 1 : I want to create a new column max_date, which will have maximum date value for each row. I thought I could create a list of those columns and then apply max on them but it didn't work. I found numpy.amax(), but couldn't make it work. Problem 2 : I must use column names to specify those columns, can't use position index of columns like df2[ , 0:2] Update on problem 2 - When I said ' use column names' - I meant I have a list of column names, which I need to use like [date1, date2, date3]. Sorry if that wasn't clear from my post.
upvote count: 2
answer count: 3
has answer: http://stackoverflow.com/a/52060737
tagged with: pandas
tagged with: datetime
favorite count: 0
tagged with: python-3.x
has title: How to get maximum date value from a group of date columns
tagged with: python
type: AnsweredQuestion
score: 2
has answer: http://stackoverflow.com/a/52060665
downvote count: 0
possible better answer: http://stackoverflow.com/a/52060737
has answer: http://stackoverflow.com/a/52060730
accepted answer: http://stackoverflow.com/a/52060730

http://stackoverflow.com/comment/90975676
type: QuestionComment
comment on: http://stackoverflow.com/q/52012247
score: 2
has text: I cant reproduce this either
type: Comment

http://stackoverflow.com/a/52047431
type: Answer
has comment: http://stackoverflow.com/comment/91049732
answers question: http://stackoverflow.com/q/52047124
has body: For your first question: You can not add docstrings within a function call's parentheses. This means you have to explain it somewhere else (where you do that is a matter of opinion). One alternative would be to leave a comment next to the line explaining the function (since you are using lambdas). Another alternative is to define a function and give that function a docstring. You probably should avoid this in your case, as you're only using lambdas to print, and having a bunch of functions with prints would be redundant when a lambda works. Your second question is kind of vague. I have couple line of code like print('xxxx') but i need the same function (time.sleep(5)) to be executed between them. Lambdas are used when you need a pretty specific function or when you need to give another function a function parameter. In either case, your lambda should be small and simple (i.e. don't use a lambda that does 100 things.) If you're only going to use the lambda as a ways of passing the print() method, then yeah, lambdas will do just fine. If you see yourself having complex lambdas, it might be time for a function. You can pass them the same way you would a lambda (if they don't take parameters): def foo(): [...] [do stuff] [...] add_delay_between_action(foo)
score: 0
has comment: http://stackoverflow.com/comment/91050280

http://stackoverflow.com/comment/90897652
score: 2
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51973570
has text: append in the new_list after creating a new df

http://stackoverflow.com/comment/91058777
score: 0
type: AnswerComment
has text: How did you install cudamat?
type: Comment
comment on: http://stackoverflow.com/a/52032570

http://stackoverflow.com/comment/90897210
comment on: http://stackoverflow.com/a/51972494
type: Comment
has text: I'm kind of new to this; I've still got a ton to learn. I just updated my original post. Can you take a look at the last part of the script and tell me what's wrong with it? Thanks.
score: 0
type: AnswerComment

http://stackoverflow.com/comment/90893604
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51970789
has text: @SachinKukreja I believe I am activating it. I cloned a Django project and am trying to install the requirements.txt .
score: 0

http://stackoverflow.com/comment/91012734
type: Comment
type: QuestionComment
has text: Correction. It should be 2500 instead of 0.0025.
comment on: http://stackoverflow.com/q/52029633
score: 0

http://stackoverflow.com/comment/90941368
score: 0
comment on: http://stackoverflow.com/a/51995564
has text: I think the phrase is *user-defined* classes.
type: Comment
type: AnswerComment

http://stackoverflow.com/a/52053897
has comment: http://stackoverflow.com/comment/91058166
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52053845
score: 1
has body: It returns two values but the loop expects a list of two values. You have this: [x, y] But the code expects this: x, y You could do: from itertools import repeat items = map(str.split, l, repeat(','), repeat(1)) d = {int(k):v for k,v in items} Note that you'll get all the data and not just one item. You may want to parse the list using ast.literal_eval because currently its a string: import ast from itertools import repeat items = map(str.split, l, repeat(','), repeat(1)) d = {int(k):ast.literal_eval(v) for k,v in items}
upvote count: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/91058193
type: Answer
answers question: http://stackoverflow.com/q/52053845

http://stackoverflow.com/q/51981858
tagged with: dereference
downvote count: 0
has answer: http://stackoverflow.com/a/51994062
has comment: http://stackoverflow.com/comment/90914159
has title: dereferencing the whole Data of c_void_p not only the first byte
score: 3
answer count: 1
favorite count: 0
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/51994062
has comment: http://stackoverflow.com/comment/90914859
tagged with: python
type: AnsweredQuestion
upvote count: 3
linked to: http://stackoverflow.com/q/33517410
has body: i have a Question about Pythons ctypes and calling C functions bothering me for a couple days now. I'm working with Python 3.5 and ctypes to wrap a C .dll. I've got a C Function accepting a void ** as an output parameter. This should contain a Pointer to some 8 Bit RGB Data of a Image after the Call. foo(void ** bar) I declare my Python parameter and function call as following: &gt;&gt;bar = c_void_p() &gt;&gt;foo(byref(bar)) And try to recieve the Data: &gt;&gt;data = c_byte(bar.value) &gt;&gt;data.value 20 which actually is a reasonable value for the first Pixels 'R'-Byte But i did not manage to reach any Byte beyond this. For my understandig I now get the value of the first Byte the c_void_p points to(?) I also tried: &gt;&gt;data = (c_byte*3)(bar.value) 3 is only for test purposes (tried and went up to couple thousands): &gt;&gt;data &lt;__main__.c_byte_Array_3 at 0x7faca45de950&gt; #so far so good again? &gt;&gt;data[0] 20 &gt;&gt;data[1] 0 ... &gt;&gt;data[n] 0 for me it seems like i cant acces any further Bytes again? when i Try to define bar as a int Pointer (what is recommend by a lot of guys) i get the following: &gt;&gt;bar = POINTER(c_int)() &gt;&gt;foo(byref(bar)) &gt;&gt;bar &lt;__main__.LP_c_int at 0x7fcf71d9d8c8&gt; #so far so good? &gt;&gt;bar.contents Process finished with exit code 139 (interrupted by signal 11: SIGSEGV) I also worked through anything i found online including: this, this, and a couple more I cant find right now. Any Help is really appreciated! edit: whole code of the python file: from ctypes import * from ctypes_wrapper_dijsdk import * init() guids = find_cameras() handle = c_void_p() open_camera(guids, handle, 0) start_acquisition(handle, 1) imageHandle = c_void_p() VOIDPP = POINTER(c_void_p) imageData = VOIDPP(c_void_p()) get_image(handle, imageHandle, imageData) byte_buf = cast(imageData.contents, POINTER(c_ubyte * (1920))) for x in range(0, (1920)-1 ): print("value: {:3d}".format(byte_buf.contents[x])) dimension = (c_int*2)() …
type: Question
tagged with: ctypes

http://stackoverflow.com/q/52065182
tagged with: python
has comment: http://stackoverflow.com/comment/91089251
has comment: http://stackoverflow.com/comment/91081422
tagged with: django
type: Question
has title: Bootstrap form does not show instance's data
has comment: http://stackoverflow.com/comment/91081703
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52075510
has comment: http://stackoverflow.com/comment/91081187
tagged with: django-forms
has comment: http://stackoverflow.com/comment/91101563
linked to: http://stackoverflow.com/q/5827590
answer count: 2
has body: I am trying to retrieve an instance's current data to bootstrap form for update. When i use {{user_form.as_p}} all current data is filled automatically however replace it with bootstrap forms it seems empty. Here is my python and html files: views.py def update_profile(request): if request.method == 'POST': user_form = RegisterForm(request.POST, instance=request.user) if user_form.is_valid(): user_form.save() return redirect('profile') else: user_form = RegisterForm(instance=request.user) return render(request, 'blog/update_profile.html', { 'user_form': user_form, }) update_profile.html {% csrf_token %} Name ... Save changes forms.py class RegisterForm(UserCreationForm): email = forms.EmailField(max_length=200, help_text='Required') class Meta: model = User fields = ('first_name', 'last_name', 'username', 'email', 'password1', 'password2')
has comment: http://stackoverflow.com/comment/91081590
has comment: http://stackoverflow.com/comment/91081329
tagged with: bootstrap-4
has answer: http://stackoverflow.com/a/52074318
accepted answer: http://stackoverflow.com/a/52074318
score: 0
possible better answer: http://stackoverflow.com/a/52075510
has comment: http://stackoverflow.com/comment/91081476

hessian
tags question: http://stackoverflow.com/q/52004412
type: Tag
tag name: hessian

http://stackoverflow.com/comment/90960612
comment on: http://stackoverflow.com/q/52005471
type: Comment
type: QuestionComment
score: 2
has text: When asking about code that produces an Exception you should always include the complete Traceback in the question. Copy the Traceback and paste it in the question, then format it as code (select it and type ctrl-k)

http://stackoverflow.com/comment/90994964
has text: Im a newbie to python and im using python 3.7.0 using cmd in my windows 10 OS and i dont know if im using a cpython or pypy or anything else.....this is the first time im hearing about "python implementation".
type: QuestionComment
comment on: http://stackoverflow.com/q/52022315
score: 0
type: Comment

flask-sqlalchemy
tags question: http://stackoverflow.com/q/52046077
tags question: http://stackoverflow.com/q/51959268
tags question: http://stackoverflow.com/q/52037060
tags question: http://stackoverflow.com/q/52052454
type: Tag
tags question: http://stackoverflow.com/q/51970542
tags question: http://stackoverflow.com/q/52073561
tags question: http://stackoverflow.com/q/51958039
tags question: http://stackoverflow.com/q/52030023
tag name: flask-sqlalchemy
tags question: http://stackoverflow.com/q/52055490
tags question: http://stackoverflow.com/q/52111363
tags question: http://stackoverflow.com/q/52069057
tags question: http://stackoverflow.com/q/52037226
tags question: http://stackoverflow.com/q/52045801

http://stackoverflow.com/q/51968126
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51970061
has title: Connect to 2 Oracle Databases in Python
type: Question
has answer: http://stackoverflow.com/a/51970061
has comment: http://stackoverflow.com/comment/90886968
tagged with: database
score: 0
tagged with: cx-oracle
answer count: 1
has body: I am trying to connect to 2 Oracle databases in a single Python script and am having some trouble connecting to the second database. The error I am receiving is: "DatabaseError: ORA-01017: invalid username/password; logon denied" My login information is correct so I am confused on why it is not allowing me to access the second database. Any insight would be appreciated. Sample code below: dsnStr = cx_Oracle.makedsn("database1", "port_for_db1", "sid_for_db1") conn = cx_Oracle.connect("myusername","password_db1",dsn=dsnStr) dsnStr2 = cx_Oracle.makedsn("database2", "port_for_db2", "sid_for_db2") conn2 = cx_Oracle.connect("myusername","password_db2",dsn=dsnStr) Thank you!
tagged with: oracle-database

http://stackoverflow.com/a/52046203
type: Answer
score: 0
answers question: http://stackoverflow.com/q/52035117
has body: After Study from this above answer and my own trial and error found a suitable solution through Forward Filling for my problem specifically.

http://stackoverflow.com/q/52101779
type: UnansweredQuestion
upvote count: 1
has title: Explained variance in TruncatedSVD
tagged with: pca
score: 1
tagged with: lsa
type: Question
has comment: http://stackoverflow.com/comment/91154857
downvote count: 0
tagged with: scikit-learn
has body: as I tried to get my head around LSA, I discovered that I am not able to reproduce the result from TruncatedSVD using SVD. Why does this not work. Thank you for your help. import pandas as pd import numpy as np from sklearn.decomposition import TruncatedSVD # Iris data df = pd.read_csv(filepath_or_buffer='https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data', header=None, sep=',') df.columns=['sepal_len', 'sepal_wid', 'petal_len', 'petal_wid', 'class'] df.dropna(how="all", inplace=True) X = df.ix[:,0:4].values # TruncatedSVD lsa = TruncatedSVD(n_components=3) X_proj = lsa.fit_transform(X) #print(lsa.singular_values_) &lt;------- error print('Components:\n', lsa.components_) print('Explained variance:\n', lsa.explained_variance_, '\n') # SVD u, s, vt = np.linalg.svd(X) print('Components:\n', vt) exp_var = (s**2) / (X.shape[0]-1) print('Explained variance:\n', exp_var)
tagged with: python
tagged with: svd
favorite count: 0
answer count: 0

http://stackoverflow.com/comment/90940975
type: AnswerComment
score: 0
type: Comment
has text: I implemented ALollz suggestion from the start, I’m glad he mentioned it. Regarding .astype(), I tried that initially, but it threw an error when I subsequently tried to convert to an integer, which I needed to do.
comment on: http://stackoverflow.com/a/51993219

http://stackoverflow.com/q/51962305
type: Question
accepted answer: http://stackoverflow.com/a/51962378
score: 0
answer count: 1
has body: Can someone please tell me where I am going wrong? Here's my code and the error I am getting. p.s I have given the somefile.mrc path correctly. import numpy import Mrc a = Mrc.bindFile('home/smitha/deep-image-prior/data/Falcon_2015_05_14-20_42_18.mrc') # a is a NumPy array with the image data memory mapped from # somefile.mrc. You can use it directly with any function # that will take a NumPy array. hist = numpy.histogram(a, bins=200) # a.Mrc is an instances of the Mrc class. One thing # you can do with that class is print out key information from the header. a.Mrc.info() wavelength0_nm = a.Mrc.hdr.wave[0] AttributeError Traceback (most recent call last) in () 3 a = Mrc.bindFile('/home/smitha/deep-image-prior/data/Falcon_2015_05_14-20_42_18.mrc') 4 hist = numpy.histogram(a, bins=200) ----> 5 a.Mrc.info() 6 wavelength0_nm = a.Mrc.hdr.wave[0] 7 AttributeError: 'NoneType' object has no attribute 'Mrc' ​
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51962378
has title: AttributeError: 'NoneType' object has no attribute 'Mrc' in python using jupyter notebook
tagged with: python
has comment: http://stackoverflow.com/comment/90874890

http://stackoverflow.com/comment/90983089
type: QuestionComment
comment on: http://stackoverflow.com/q/52016437
has text: When you get an error message you generally need to include it in your question, starting from the `Traceback` line, so that readers can tell what part of the program is causing the problem. But in this case it's obvious: the `raw_input` function has been renamed to `input` in Python 3 (and the old `input` function has been discarded).
score: 0
type: Comment

http://stackoverflow.com/q/52056470
tagged with: python
has body: I am viewing the image on the screen using open cv in python. But the image which I opened with the code is halfway on the screen. But I want you to look full screen. How can I do that? Could you help?
tagged with: pycharm
upvote count: 2
type: UnansweredQuestion
tagged with: screen
has answer: http://stackoverflow.com/a/52076069
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/91070284
tagged with: opencv
has comment: http://stackoverflow.com/comment/91064628
score: 1
has comment: http://stackoverflow.com/comment/91063447
answer count: 2
has title: how can I see image fullscreen in python?
favorite count: 0
has comment: http://stackoverflow.com/comment/91063807
has answer: http://stackoverflow.com/a/52091712

http://stackoverflow.com/q/51972438
score: 0
tagged with: python
tagged with: css
has body: I am rendering a template that I am attempting to style with a custom style sheet. The file structure is as follows: /app - __init__.py /templates - markets.html - base.html /static - custom.css markets.html looks like this: {% extends 'base.html' %} {% block content %} Runeberg {% endblock %} base.html looks like this: {% extends 'bootstrap/base.html' %} {% block styles %} {{ super() }} {% endblock %} And finally, custom.css looks like this: .front-page { margin-top: 25%; } I wrote this code by following this example here. The problem is, the style (front-page) is not being applied.
tagged with: flask-bootstrap
linked to: http://stackoverflow.com/q/2263096
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51973963
tagged with: jinja2
has title: Flask not recognizing my custom style sheet
has answer: http://stackoverflow.com/a/51972662
duplicate of: http://stackoverflow.com/q/2263096
type: Question
answer count: 2
tagged with: flask

http://stackoverflow.com/a/52071275
score: 33
upvote count: 33
downvote count: 0
answers question: http://stackoverflow.com/q/52067058
has comment: http://stackoverflow.com/comment/127955245
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/52067058
type: Answer
has body: You appear to be using this code. It's missing a default for the column. You're emulating this SQL: id UUID PRIMARY KEY DEFAULT uuid_generate_v4() But you've already linked to the correct code. id = Column(UUID(as_uuid=True), primary_key=True, server_default=sqlalchemy.text("uuid_generate_v4()"),) Alternatively if you don't want to load a Postgres UUID extension, you can create the UUIDs in Python. from uuid import uuid4 id = Column(UUID(as_uuid=True), primary_key=True, default=uuid4,)

http://stackoverflow.com/a/51986738
accepted answer of: http://stackoverflow.com/q/51986666
has body: Instead of (which even without the TypeError is still bad python for the reasons explained in the comments): seen_set = set() duplicate_set = set(x for x in original_list if x in seen_set or seen_set.add(x)) unique_set = seen_set - duplicate_set literally all you need is # first just use set to grab all the possible elements (make lists hashable by # passing through tuple) -- this is a set comprehension seen_set = {tuple(x) for x in original_list} # the duplicates are just ones with counts &gt; 1 duplicate_set = {t for t in seen_set if original_list.count(list(t)) &gt; 1} unique_set = seen_set - duplicate_set You function can also simply be written as def readcsv(input_file): ifile = open(combined, "rU") reader = csv.reader(ifile, delimiter=";") return sorted(reader) # don't mutate global variables! original_list = readcsv(input_file)
answers question: http://stackoverflow.com/q/51986666
score: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/90924051
has comment: http://stackoverflow.com/comment/90923713
has comment: http://stackoverflow.com/comment/90923959
type: Answer

http://stackoverflow.com/q/52092332
type: Question
answer count: 2
downvote count: 4
has body: def find_csv(filename, keyvalue): with open(filename, "r") as csv_file: file_name = csv_file keyvalue = input("please enter what you would like to find in the file: ") file = file_name.read() file = file.strip(",") xxx = input("please enter the file: ") print(find_csv(xxx, ""))
has comment: http://stackoverflow.com/comment/91134598
tagged with: http://stackoverflow.com/tag/csv
favorite count: 0
has comment: http://stackoverflow.com/comment/91134693
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/91134892
has answer: http://stackoverflow.com/a/52093282
type: UnansweredQuestion
score: -3
tagged with: python
has answer: http://stackoverflow.com/a/52092564
upvote count: 1
has title: How do I search for a certain character in a text file and say what row and column its in

http://stackoverflow.com/comment/91158371
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52103634
has text: I'm pretty sure perl is not supposed to handle SIGPIPE by default.
type: AnswerComment

http://stackoverflow.com/comment/91111783
type: QuestionComment
has text: That would be latin1, not utf8.
score: 1
comment on: http://stackoverflow.com/q/52080762
type: Comment

http://stackoverflow.com/q/52059934
has answer: http://stackoverflow.com/a/52060054
answer count: 5
tagged with: python
score: 2
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/78249545
type: Question
has answer: http://stackoverflow.com/a/52060050
has title: Math function to find the biggest multiple of a number within a range
tagged with: math
possible better answer: http://stackoverflow.com/a/52059995
upvote count: 3
has body: I want to know if there is a math expression that I can use to find this relation between two numbers. Some examples of the input and expected output are below: Input Multiple Result 4 3 3 6 3 6 8 3 6 4 4 4 12 4 12 16 5 15 Also, the expressions below from Wolfram Alpha show me the expected result but since they don't expand on the explanation on how to do it I can't learn from them... Biggest multiple of 4 from 10 Biggest multiple of 4 from 12
has answer: http://stackoverflow.com/a/52060049
accepted answer: http://stackoverflow.com/a/52060049
downvote count: 1
has answer: http://stackoverflow.com/a/52059995
favorite count: 0

http://stackoverflow.com/q/52023464
type: AnsweredQuestion
score: 1
tagged with: tensorflow
type: Question
accepted answer: http://stackoverflow.com/a/52026936
downvote count: 0
answer count: 1
favorite count: 0
has title: Optimizing parameter in odeint with the output of a neural network in TensorFlow
has answer: http://stackoverflow.com/a/52026936
upvote count: 1
tagged with: python
has body: I would like to optimize the coefficients of an ODE using tensorflow. def odeModel(state, t): x, y, z = tf.unstack(state) dx = y # Here I want to define dy and dz as follows: # [dy, dz] = tf.nn.relu(tf.matmul([y, z], W) + b) return tf.stack([dx, dy, dz]) Basically, I aim to define [dy, dz] as a map from [y, z] that depends on appropriately sized TensorFlow variables 'W' and 'b'. Then, I would like to find 'W' and 'b' that minimizes a loss function that depends on the trajectory starting from 'state0'. Is that possible? I aim to write the rest of the code along the following lines. t = np.linspace(0, 5, 100) state0 = #Appropriate starting point, e.g., tf.constant([0, 1, 3], dtype=tf.float64) states = tf.contrib.integrate.odeint(odeModel, state0, t) loss = tf.reduce_mean(tf.pow(states[:, 2], 2)) optimizer = tf.train.AdagradOptimizer(0.05).minimize(loss) Of course, I need to the create a session and run the optimizer. The details are omitted for brevity. I am wondering if there is a way to achieve what I am shooting for.

http://stackoverflow.com/comment/91012805
score: 0
type: Comment
type: QuestionComment
has text: @Alex Do you understand the benefits of vectorisation? The solution I'm testing simply involves slicing A up into small enough chunks (but not rows).
comment on: http://stackoverflow.com/q/52030945

http://stackoverflow.com/a/52020021
accepted answer of: http://stackoverflow.com/q/52019218
type: AcceptedAnswer
type: Answer
has body: Just made it work. lr.coef_ = np.array(lr.coef_) lr.classes_ = np.array(lr.classes_) lr.n_iter_ = np.array(lr.n_iter_) lr.intercept_ = np.array(lr.intercept_) lr.predict(X)
score: 1
answers question: http://stackoverflow.com/q/52019218
upvote count: 1
downvote count: 0

http://stackoverflow.com/q/52098537
tagged with: pandas
downvote count: 0
favorite count: 0
has body: I want a line plot to indicate if a piece of data is missing such as: However, the code below fills the missing data, creating a potentially misleading chart: import pandas as pd import seaborn as sns from matplotlib import pyplot as plt # load csv df=pd.read_csv('data.csv') # plot a graph g = sns.lineplot(x="Date", y="Data", data=df) plt.show() What should I change in my code to avoid filling missing values? csv looks as following: Date,Stagnation 01-07-03, 01-08-03, 01-09-03, 01-10-03, 01-11-03, 01-12-03,100 01-01-04, 01-02-04, 01-03-04, 01-04-04, 01-05-04,39 01-06-04, 01-07-04, 01-08-04,53 01-09-04, 01-10-04, 01-11-04, 01-12-04, 01-01-05,28 01-02-05, 01-03-05, 01-04-05, 01-05-05, 01-06-05,25 01-07-05,50 01-08-05,21 01-09-05, 01-10-05, 01-11-05,17 01-12-05, 01-01-06,16 01-02-06,14 01-03-06,21 01-04-06, 01-05-06,14 01-06-06,14 01-07-06, 01-08-06, 01-09-06,10 01-10-06,13 01-11-06,8 01-12-06,20 01-01-07,8 01-02-07,20 01-03-07,10 01-04-07,9 01-05-07,19 01-06-07,6 01-07-07, 01-08-07,11 01-09-07,17 01-10-07,12 01-11-07,13 01-12-07,17 01-01-08,11 01-02-08,8 01-03-08,9 01-04-08,21 01-05-08,8 01-06-08,8 01-07-08,14 01-08-08,14 01-09-08,19 01-10-08,27 01-11-08,7 01-12-08,16 01-01-09,25 01-02-09,17 01-03-09,9 01-04-09,14 01-05-09,14 01-06-09,3 01-07-09,14 01-08-09,5 01-09-09,8 01-10-09,13 01-11-09,10 01-12-09,10 01-01-10,8 01-02-10,12 01-03-10,12 01-04-10,15 01-05-10,13 01-06-10,5 01-07-10,6 01-08-10,7 01-09-10,13 01-10-10,19 01-11-10,19 01-12-10,13 01-01-11,11 01-02-11,11 01-03-11,15 01-04-11,9 01-05-11,14 01-06-11,7 01-07-11,9 01-08-11,11 01-09-11,24 01-10-11,14 01-11-11,17 01-12-11,14 01-01-12,10 01-02-12,13 01-03-12,12 01-04-12,12 01-05-12,12 01-06-12,9 01-07-12,7 01-08-12,9 01-09-12,15 01-10-12,13 01-11-12,25 01-12-12,13 01-01-13,13 01-02-13,15 01-03-13,23 01-04-13,22 01-05-13,14 01-06-13,13 01-07-13,20 01-08-13,17 01-09-13,27 01-10-13,15 01-11-13,16 01-12-13,18 01-01-14,18 01-02-14,19 01-03-14,14 01-04-14,14 01-05-14,10 01-06-14,11 01-07-14,8 01-08-14,18 01-09-14,16 01…
tagged with: seaborn
has answer: http://stackoverflow.com/a/52101576
tagged with: python
upvote count: 29
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/77172878
score: 29
has answer: http://stackoverflow.com/a/52100393
type: Question
has answer: http://stackoverflow.com/a/78232488
tagged with: line-plot
has answer: http://stackoverflow.com/a/76096233
tagged with: matplotlib
has title: Avoid plotting missing values on a line plot
has answer: http://stackoverflow.com/a/64172693
answer count: 6
possible better answer: http://stackoverflow.com/a/52100393
accepted answer: http://stackoverflow.com/a/76096233

http://stackoverflow.com/comment/91063071
type: QuestionComment
has text: Sorry, I mean't the different file formats that you can integrate into Python such as Pickle, Json
comment on: http://stackoverflow.com/q/52054899
score: 0
type: Comment

http://stackoverflow.com/a/52042879
score: 2
upvote count: 2
has body: Your keys are duplicated, so you cannot create a dictionary with them (you'll lose the first elements). So comprehensions are difficult to use (and inefficient, as stated by other comprehension answers here) because of the accumulation effect that you need. I suggest using collections.defaultdict(list) instead and a good old loop: import collections y = [1, 3, 1, 5, 1] d = collections.defaultdict(list) for i,x in enumerate(y[1:]): d[x].append(y[i]) # i is the index of the previous element in y print(d) result: defaultdict(&lt;class 'list'&gt;, {1: [3, 5], 3: [1], 5: [1]})
answers question: http://stackoverflow.com/q/52042758
downvote count: 0
type: Answer

http://stackoverflow.com/comment/90978739
score: 0
comment on: http://stackoverflow.com/q/52013628
type: Comment
has text: It has nothing to do with OS because it's about request protocol. Sometimes it depends on your geography too. Where are you from @user1888427?
type: QuestionComment

http://stackoverflow.com/a/52013281
answers question: http://stackoverflow.com/q/52013260
score: 1
has body: If you mean that you want to return the negation of the boolean resulting from the comparison you could do something like class T: def __init__(self, x): self._x = x def __lt__(self, other): return not self._x &lt; other._x t1 = T(1) t2 = T(2) print(t1 &lt; t2) #False Note that in the comparison self._x &lt; other._x you are using the __lt__ method of the int class.
upvote count: 1
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52013260
type: Answer

http://stackoverflow.com/a/52071135
accepted answer of: http://stackoverflow.com/q/52071001
has comment: http://stackoverflow.com/comment/91131773
type: AcceptedAnswer
type: Answer
score: 2
downvote count: 0
answers question: http://stackoverflow.com/q/52071001
has body: You can use an iterator to iterate through the values of binary_list instead: iter_binary_list = iter(binary_list) for truck in Trucks: for day in Days: requests[truck][day] = next(iter_binary_list)
upvote count: 2

http://stackoverflow.com/comment/90873885
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/51961782
type: Comment
has text: But it seems need check first value, so solution should be changed

http://stackoverflow.com/comment/90873756
type: QuestionComment
has text: Why is that strange? If you move the index file out of the source directory, then there *is* a module `src` for it to import from.
score: 0
comment on: http://stackoverflow.com/q/51961696
type: Comment

http://stackoverflow.com/q/52100621
favorite count: 0
tagged with: qtreewidget
has answer: http://stackoverflow.com/a/52107088
tagged with: python
has comment: http://stackoverflow.com/comment/91159229
has comment: http://stackoverflow.com/comment/91159422
has title: Save Qtreewidget item and restore it with selection
has comment: http://stackoverflow.com/comment/91152554
has comment: http://stackoverflow.com/comment/91159431
type: AnsweredQuestion
score: 1
tagged with: pyqt5
upvote count: 1
has comment: http://stackoverflow.com/comment/91156989
type: Question
has body: I need support to my little software with Qwidget and QTreeWidgets. see below figure. This is how my Qwidget looks like. I want to restore Qtreewidget items and widget when I close the window and restore it with previous selection. as Marked on the figure below.As you see in my scripts below, I have used Qsettings, I have tried to fix it with pickle but does not work. Any improvement in coding is welcoming. from PyQt5 import * from PyQt5.QtWidgets import * from PyQt5.QtCore import* from PyQt5.QtGui import * import sys import pickle iconroot = QFileInfo(__file__).absolutePath() ORGANIZATION_NAME = 'Circularcolumn App' ORGANIZATION_DOMAIN = 'Circular shape' APPLICATION_NAME = 'QSettings program' SETTINGS_TRAY = 'settings/tray' class usedcircularshape(QDialog): def __init__(self, parent=None): super().__init__(parent) self.setWindowTitle("Frequently used shape") self.setWindowIcon(QIcon(iconroot+"/images/circularcolumnnorebar.png")) #self.setStyleSheet("background-color:#f2f2f2") self.addbutton = QPushButton("Add") self.addbutton.clicked.connect(self.add) self.deletebutton = QPushButton("Delete") self.deletebutton.clicked.connect(self.delete) self.okbutton = QPushButton("Ok") self.okbutton.setCursor(Qt.PointingHandCursor) #self.okbutton.clicked.connect(self.hidethiswindow) self.okbutton.clicked.connect(self.savesetting) self.cancelbutton = QPushButton("Cancel") self.cancelbutton.setCursor(Qt.PointingHandCursor) self.cancelbutton.clicked.connect(self.loadsetting) #self.cancelbutton.clicked.connect(self.close) self.addimage() self.qlabeltodefinesection() self.treewidget() self.sectionnamecircular = QLabel('Section name: ') self.sectionnamecircularindata = QLineEdit('Define en name to section') self.sectionnamecircularindata.setObjectName("sectionnamecircularindata") self.sectionnamecircular.setBuddy(self.sectionnamecircularindata) self.sectionnamecircular.setFocus() self.grid_sectionname = QHBoxLayout() self.grid_sectionname.addWidget(self.sectionnamecircular) self.grid_…
accepted answer: http://stackoverflow.com/a/52107088
tagged with: qsettings
has comment: http://stackoverflow.com/comment/91159299
tagged with: pyqt
has comment: http://stackoverflow.com/comment/91156779
answer count: 1
has comment: http://stackoverflow.com/comment/91159591
downvote count: 0

http://stackoverflow.com/comment/91034307
has text: Possible duplicate of [Extracting text from a PDF file using Python](https://stackoverflow.com/questions/34837707/extracting-text-from-a-pdf-file-using-python)
comment on: http://stackoverflow.com/q/52041720
type: QuestionComment
type: Comment
score: 2

http://stackoverflow.com/comment/92081569
has text: @HammadKhan : The Q is closed, so there is no space for bigger coding examples. Please post a new Q and try to define more clearly what you wish.
comment on: http://stackoverflow.com/q/52001964
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/91003021
has text: @melpomene I'd rather we show _new contributors_ how to use the site. Editing their question when there's ambiguity is not helpful in the long run. They need to clarify themselves otherwise we're all guessing here.
type: Comment
comment on: http://stackoverflow.com/q/52026382
type: QuestionComment
score: 2

http://stackoverflow.com/a/52016638
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/90983538
has comment: http://stackoverflow.com/comment/90983499
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/90983438
accepted answer of: http://stackoverflow.com/q/52016577
has body: You can use the following expression: \+1 (?:\*{3}-){2}\*{2}\d{2} \+1 Matches substring +1. (?:\*{3}-){2} Non capturing group. Matches three * followed by two -. Group is repeated two times. \*{2} Matches two *. \d{2} Matches two digits. Regex demo here. In Python: import re phoneno = 'my number is +1 ***-***-**98' match = re.search(r'\+1 (?:\*{3}-){2}\*{2}\d{2}',phoneno) print(match.group(0)) Prints: +1 ***-***-**98
type: Answer
has comment: http://stackoverflow.com/comment/90983458
answers question: http://stackoverflow.com/q/52016577

jwt
tags question: http://stackoverflow.com/q/52033003
tag name: jwt
type: Tag
tags question: http://stackoverflow.com/q/52087743

http://stackoverflow.com/a/52041100
type: Answer
answers question: http://stackoverflow.com/q/52040800
has body: When you do this: X = iris[:,3] Then X is only a single column (4th feature petal.width), which is why you are getting error in est.fit() part, because the estimator think you have only a single sample (I'm assuming you are using an older version of scikit-learn. Newer versions throw a different more clear error there) Correct that to: X = iris[:,:4] to use all features. Why are you doing y = np.choose(y, [1, 2, 0]).astype(np.float)?
score: 0
has comment: http://stackoverflow.com/comment/91033996
has comment: http://stackoverflow.com/comment/91033601
has comment: http://stackoverflow.com/comment/91034029
has comment: http://stackoverflow.com/comment/91036198

http://stackoverflow.com/q/52006648
tagged with: python
tagged with: regex
favorite count: 0
accepted answer: http://stackoverflow.com/a/52007277
has title: Search string and replace value
upvote count: 1
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90963590
score: 1
type: Question
has comment: http://stackoverflow.com/comment/90963367
has answer: http://stackoverflow.com/a/52007277
answer count: 1
downvote count: 0
has body: Here is my code, import os, os.path import collections import sys import re DIR_DAT = "dat" DIR_OUTPUT = "output" filenames = [] data = [] #in case if output folder doesn't exist if not os.path.exists(DIR_OUTPUT): os.makedirs(DIR_OUTPUT) input_file = 'axcfgpasww-from-server.dat' element = sys.argv[1] output_value = sys.argv[2] with open(input_file) as infile, open('axcfgpasww-modified.dat', "w") as outfile: if element in open(input_file).read(): regex = re.findall("\s*([\S\s]+)", element) outfile.write(regex[0]) print(regex[0]) else: print('No match found') The input_file : CMD_VERS=2 CMD_TRNS=O CMD_REINIT=N CMD_ORDER=MAJECR CMD_COMM=2590552 NUM_COMM:nNN0.7=2590552 I execute my script this way : modify_file.py NUM_COMM:nNN0.7 Hello world ! So if NUM_COMM:nNN0.7 exists in the file, it writes "NUM_COMM:nNN0.7" in a new axcfgpasww-modified.dat file. But what I want to do, is execute my command as written above. And the result is the input file, with only the new value. So my output file would be : CMD_VERS=2 CMD_TRNS=O CMD_REINIT=N CMD_ORDER=MAJECR CMD_COMM=2590552 NUM_COMM:nNN0.7=Hello world ! Can anyone help me on this ? Thanks !

http://stackoverflow.com/q/52003387
answer count: 1
tagged with: scikit-learn
linked to: http://stackoverflow.com/q/952914
has body: I want to train a linear model Y = M_1*X_1 + M_2*X_2 using sklearn with multidimensional input and output samples (e.g. vectors). I tried the following code: from sklearn import linear_model from pandas import DataFrame x1 = [[1,2],[2,3],[3,4]] x2 = [[1,1],[3,2],[3,5]] y = [[1,0],[1,2],[2,3]] model = { 'vec1': x1, 'vec2': x2, 'compound_vec': y} df = DataFrame(model, columns=['vec1','vec2','compound_vec']) x = df'vec1','vec2'.astype(object) y = df['compound_vec'].astype(object) regr = linear_model.LinearRegression() regr.fit(x,y) But I get the following error: regr.fit(x,y) ... array = array.astype(np.float64) ValueError: setting an array element with a sequence. Does anyone know what is wrong with the code? and if this is a right way to train Y = M_1*X_1 + M_2*X_2?
upvote count: 5
has comment: http://stackoverflow.com/comment/90957580
has comment: http://stackoverflow.com/comment/90961711
tagged with: python
has comment: http://stackoverflow.com/comment/90959856
has comment: http://stackoverflow.com/comment/90961766
downvote count: 0
has comment: http://stackoverflow.com/comment/90957787
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/52003762
has comment: http://stackoverflow.com/comment/90963794
tagged with: linear-regression
favorite count: 0
has comment: http://stackoverflow.com/comment/90980317
type: Question
has answer: http://stackoverflow.com/a/52003762
score: 5
has title: Multivariate multiple linear regression using Sklearn

http://stackoverflow.com/q/51971477
downvote count: 0
has answer: http://stackoverflow.com/a/51971794
type: UnansweredQuestion
tagged with: homebrew
has title: Homebrew - What's the difference between `python@3` and `python3`?
type: Question
has body: I have python 2.7.14 installed via homebrew, and I'd like to install the latest version of python 3 via homebrew as well. When I search for "python3" I see the following results. $ brew search python3 ==&gt; Formulae boost-python3 python3 python@3 If you meant "python3" specifically: It was migrated from homebrew/cask to homebrew/core. Why is there both python@3 and python3? What's the difference?
has comment: http://stackoverflow.com/comment/90893807
has comment: http://stackoverflow.com/comment/90893997
upvote count: 2
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/90893816
tagged with: python-3.x
tagged with: python
tagged with: osx-elcapitan
has comment: http://stackoverflow.com/comment/90893699
score: 2

http://stackoverflow.com/comment/91153854
score: 0
type: QuestionComment
has text: The output shows `[30/Aug/2018 18:56:13] "GET / HTTP/1.1" 200 2651` *twice*. That's two requests. The print lines show the context processor was only called once per request.
type: Comment
comment on: http://stackoverflow.com/q/52099920

http://stackoverflow.com/q/52111452
type: UnansweredQuestion
score: -4
downvote count: 4
has comment: http://stackoverflow.com/comment/91173442
upvote count: 0
has comment: http://stackoverflow.com/comment/91173357
favorite count: 0
type: Question
has body: I face this problem anytime I try to update the value of the iterator variable of the python for a loop. It just does not let me update the variable. for i in range(1,10): print(i) i=i+5 print(i) The output turn out to be: 1 6 2 7 3 8 4 9 5 10 6 11 7 12 8 13 9 14 Can anyone give me the explanation of this output and solution to my problem if I want to update the iterator variable?
tagged with: python
has answer: http://stackoverflow.com/a/52111555
has title: The problem of for loop iteration updation in python
has comment: http://stackoverflow.com/comment/91514407
has comment: http://stackoverflow.com/comment/91514324
answer count: 1

http://stackoverflow.com/q/51966663
score: -1
has comment: http://stackoverflow.com/comment/90884064
has title: Solve equation with two arrays and show it as a new one
favorite count: 0
linked to: http://stackoverflow.com/q/19542801
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90884294
has comment: http://stackoverflow.com/comment/90884172
tagged with: python
has answer: http://stackoverflow.com/a/51968006
has body: edit: Proper values and equation: R=(Tpow-T)*(1-exp((x**2*alfa*t)/k**2)*(1.0-erf(x*sqrt(alfa*t)/k))) R = np.array([[24.7,46.12, 64.78, 81.12, 95.52], [ 108,119.6, 183, 183, 183], [129.7,138.77, 146.9, 154.3, 161], [167.06,172.6,177.7, 182.3, 186]]) T = np.array([[20,20,20,20,20], [20,20,20,20], [20,31,12,23,14], [15,11,37,28,19]]) I calculate x in excel but only for T=20, correct values should be around: x = np.array([[10,20,30,40,50], [60,70,80,90], [100,?,?,?,?], [?,?,?,?,?]]) let's look at random (implicit) equation: R[i,j]=T[i,j]*exp(x*B)*x*A where R,T - are 2D np.array, A,B - constant values and x is unknown value. How to write right loops to get numerical result of that equation in new array. I would like to solve my equation independently for each: R[1,1], T[1,1] = x[1,1] R[2,2], T[2,2] = x[2,2] and so on. . . It's not so easy because of operating on implicit function random values: TR = np.array([[24,46, 64, 81, 95], [167,172,177, 182, 186]]) T1 = np.array([[22,10,6,52,12], [10,10,2,3,6]]) A = 20 B = 30 X = np.array([[?,?,?,?,?], [?,?,?,?,?]]) As you suppose I'm beginner in programming so please try to explain to me as a kid.:) I got help with equation with one array and implicit equation but I cannot implement it to this kind of problem: Solve non linear equation numpy
tagged with: equation
downvote count: 1
has comment: http://stackoverflow.com/comment/90884001
linked to: http://stackoverflow.com/q/51920645
type: Question
tagged with: numpy
upvote count: 0
tagged with: implicit
tagged with: arrays
answer count: 1

http://stackoverflow.com/comment/90891092
has text: Please consider closing/deleting this question if you've already solved it. It seem trivial and not of any value to the SO community.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51969361

http://stackoverflow.com/comment/92045201
type: Comment
comment on: http://stackoverflow.com/a/52113564
score: 0
type: AnswerComment
has text: I used the Firefox Developer Network tool to watch for XHR requests during a reload of the page.

http://stackoverflow.com/comment/91119053
score: 0
type: Comment
type: QuestionComment
has text: Ok, was more like a typo. Thank you, it works!
comment on: http://stackoverflow.com/q/52083983

http://stackoverflow.com/q/52100876
has answer: http://stackoverflow.com/a/52100964
score: 0
has answer: http://stackoverflow.com/a/52100905
linked to: http://stackoverflow.com/q/9171158
type: Question
duplicate of: http://stackoverflow.com/q/9171158
accepted answer: http://stackoverflow.com/a/52101023
has title: python convert 2d array to 1d array
answer count: 6
tagged with: numpy
possible better answer: http://stackoverflow.com/a/52101040
tagged with: arrays
has comment: http://stackoverflow.com/comment/91152553
has answer: http://stackoverflow.com/a/52101040
has answer: http://stackoverflow.com/a/52101023
has body: I am new to python and need to do the following thing: I've given an 1d array of vectors (so pretty much 2d). My task is to create an 1d array that contains the length of each vector. array([[0. , 0. ], [1. , 0. ], [1. , 1. ], [1. , 0.75], [0.75, 1. ], [0.5 , 1. ] ... should be converted to array([0, 1, 1.4142, ... I could easily do this in theory but I am not familiar with the inbuild commands of python and I am very happy if someone could tell me some inbuild commands of python that can do this.
tagged with: python
has answer: http://stackoverflow.com/a/52101065
has comment: http://stackoverflow.com/comment/91152524
linked to: http://stackoverflow.com/q/327002
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52101035

http://stackoverflow.com/comment/91411736
score: 0
type: Comment
has text: I tried again but this time I didn't get any ImportError. But I cannot exclude cv2 because my script mostly relies on cv2 module. And after compiling I get error [https://ibb.co/eYZtUp].
type: AnswerComment
comment on: http://stackoverflow.com/a/52113220

http://stackoverflow.com/comment/90932374
score: 1
has text: It's before even my time, what they are talking about in that thread is no longer true.
comment on: http://stackoverflow.com/a/51991317
type: AnswerComment
type: Comment

http://stackoverflow.com/q/52030123
type: Question
score: -2
has comment: http://stackoverflow.com/comment/91010667
upvote count: 0
answer count: 1
favorite count: 0
has title: I'm getting this error but I tried everything. TypeError: can't multiply sequence by non-int of type 'float'
tagged with: python
has answer: http://stackoverflow.com/a/52030143
has comment: http://stackoverflow.com/comment/91010647
tagged with: syntax
has body: I'm having an issue with running this simple calculator. Every time I run this program, I get this error: f = a * l TypeError: can't multiply sequence by non-int of type 'float' Does anyone notice my error and how I can correct it? while True: print("///Calculator///") print("======================================") mq = float(input("Market Quote: ")) if mq==0: break a = input("Balance: ") l = input("Lev: ") if not l: l = 500 else: l = float(l) 0 p = input("Other: ") if not p: p = 70 else: p = float(p) #------------------------------------- f = a * l q = f / l mr = q * mq so = 0.40 mm = mr * so k = p * 10 b = a - mm x = b / k h = x / 8 u = round(h, 2) o = x * mq j = o / l c = round(j)
type: UnansweredQuestion
downvote count: 2
tagged with: floating-point

http://stackoverflow.com/a/51961776
has body: Create a day column by splitting on '-', and then filter using .iloc to ensure we match the first row: df['Day'] = df['Col 1'].str.split('-').str[-1] filtered = df[df['Day'] == df['Day'].iloc[0]] print(filtered) prints: Col 1 Col 2 Day 0 val1-Mon A Mon 1 val2-Mon B Mon 4 val5-Mon A Mon 5 val6-Mon B Mon 6 val7-Mon A Mon 7 val8-Mon B Mon
answers question: http://stackoverflow.com/q/51961650
downvote count: 0
type: Answer
score: 1
upvote count: 1

http://stackoverflow.com/comment/91074951
score: 1
comment on: http://stackoverflow.com/q/52062274
has text: Switching between threads can still lead to race conditions. Thread A could be in the middle of manipulating a shared resource when control is switched to Thread B, which then also wants to manipulate the shared resource. Without locking, how will Thread A even know that the resource was changed when control switches back?
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51976453
has comment: http://stackoverflow.com/comment/90903334
has comment: http://stackoverflow.com/comment/90903214
has answer: http://stackoverflow.com/a/51976521
has title: How to prevent new line caused by \\n in %WINDIR%\\system32\\netsh.exe in javascript
has body: Is there a way that I can prevent the new line caused by '\n' in: %WINDIR%\\system32\\netsh.exe I want to show this string in a html page and I use javascript to show it. However, I get: %WINDIR%\system32 etsh.exe Also, I get this string using a python template and I already tried to replace it with various combinations of '\', '/', and 'n' in python and still no luck! I appreciate if someone can provide some hint.
has comment: http://stackoverflow.com/comment/90903154
has comment: http://stackoverflow.com/comment/90903427
has comment: http://stackoverflow.com/comment/90903192
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/51976501
tagged with: javascript
has comment: http://stackoverflow.com/comment/90903357
tagged with: python
score: 0
type: UnansweredQuestion

http://stackoverflow.com/comment/91070837
has text: that works perfectly fine, thank you @Roomm
type: Comment
score: 0
comment on: http://stackoverflow.com/q/52060123
type: QuestionComment

http://stackoverflow.com/comment/90937560
has text: Possible duplicate of [Import error: No module name urllib2](https://stackoverflow.com/questions/2792650/import-error-no-module-name-urllib2)
comment on: http://stackoverflow.com/q/51992254
type: Comment
type: QuestionComment
score: 1

http://stackoverflow.com/q/52090857
favorite count: 0
score: 4
possible better answer: http://stackoverflow.com/a/52092239
has answer: http://stackoverflow.com/a/52092239
tagged with: machine-learning
tagged with: python
accepted answer: http://stackoverflow.com/a/52091200
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/55469601
has title: How to apply sigmoid function for each outputs in Keras?
type: Question
upvote count: 4
answer count: 2
downvote count: 0
tagged with: keras
tagged with: sigmoid
has body: This is part of my codes. model = Sequential() model.add(Dense(3, input_shape=(4,), activation='softmax')) model.compile(Adam(lr=0.1), loss='categorical_crossentropy', metrics=['accuracy']) with this code, it will apply softmax to all the outputs at once. So the output indicates probability among all. However, I am working on non-exclusive classifire, which means I want the outputs to have independent probability. Sorry my English is bad... But what I want to do is to apply sigmoid function to each outputs so that they will have independent probabilities.
tagged with: deep-learning
has answer: http://stackoverflow.com/a/52091200

http://stackoverflow.com/comment/90993899
comment on: http://stackoverflow.com/q/52021689
type: Comment
type: QuestionComment
score: 1
has text: It is technically possible. But it’s something obscure and very unusual. Can you explain your use-case?

http://stackoverflow.com/q/52022551
tagged with: ubuntu
accepted answer: http://stackoverflow.com/a/52023242
tagged with: postgresql
tagged with: linux
score: 1
has comment: http://stackoverflow.com/comment/90996006
has comment: http://stackoverflow.com/comment/90996503
favorite count: 0
has comment: http://stackoverflow.com/comment/90995625
has comment: http://stackoverflow.com/comment/90995597
upvote count: 1
tagged with: python
type: AnsweredQuestion
has title: Can not INSERT INTO Postgresql
has body: simplechan In other words, I installed a message board named simplechan, but I can not log in to a site dedicated to the administrator. Because you need a password to get there. I do not know the password. I entered in psql as follows simplech_db=# select * from moderator_list; username | password_md5 | session_id | expire_ts | actions_per_hour ----------+--------------+------------+-----------+------------------ (0 rows) In "simplechan/sql/create_table_query.sql" it was drawn as follows. -- tables for moderator things create extension if not exists "uuid-ossp"; -- this is only required for unique session_id. CREATE TABLE IF NOT EXISTS moderator_list ( username text PRIMARY KEY, password_md5 text NOT NULL UNIQUE, session_id uuid UNIQUE, expire_ts timestamp with time zone, actions_per_hour int NOT NULL DEFAULT 10 ); And I tried it like this, but it was useless. I accessed "IP / mod_login" and entered my password, but I could not put it in. INSERT INTO moderator_list (username,md5_password) values ('my username','mypassword'); INSERT 01 When "password" is set to "md 5 _ password", I properly INSERTed it. I accessed "IP / mod_login" and entered the password, but the password is incorrect. It was displayed. I confirmed it with "select * from moderator_list;" but it came in properly. simplech_db=# select * from moderator_list; username | password_md5 | session_id | expire_ts | actions_per_hour ----------+--------------+------------+-----------+------------------ myuser | mypassword | | | 10 (1 row)
type: Question
has answer: http://stackoverflow.com/a/52023242
downvote count: 0
answer count: 1

http://stackoverflow.com/comment/90923610
type: QuestionComment
has text: @Ross Take a look at `pandas`. Just fill a DataFrame for each with the time as timestamp index with `parse_dates=True` and then resample both to the nearest matching frequency. Then you can merge both into one DataFrame. `pandas` is exactly the tool you are looking for for things like this.
comment on: http://stackoverflow.com/q/51985853
type: Comment
score: 0

http://stackoverflow.com/a/52108045
accepted answer of: http://stackoverflow.com/q/52107775
has body: The problem is with this line in your code: recipient_list = list(str('xxxxx@gmail.com')) If you run that in your console, you will get the following output: ['x', 'x', 'x', 'x', 'x', '@', 'g', 'm', 'a', 'i', 'l', '.', 'c', 'o', 'm'] Which is not a list of valid email addresses! You need to do this instead: recipient_list = ['xxxxx@gmail.com']
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/52107775
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/91166982
type: Answer

http://stackoverflow.com/q/51972477
tagged with: python
has comment: http://stackoverflow.com/comment/90989644
answer count: 0
tagged with: orbit
has comment: http://stackoverflow.com/comment/90989162
tagged with: numeric
type: Question
has comment: http://stackoverflow.com/comment/90895717
has body: it's my first time asking a question here and since i only started some days ago with coding i may need your help defining my problem a bit more precise. I would like to simulate some keplerian orbits, but i have reoccurring problems with the required precision. For example when my point comes to close to the center of gravity it slings it out of every sensible orbit. (My theory is that the acceleration increases so drastically compared to the time-window dt, that it reaches escape velocity before gravity 'has a chance' to pull it back.) Another problem is that the orbit itself rotates around the center of gravity. I have not studied this problem in detail but i guess, this time small errors sum up thus creating this flower-like effect. First thought why these errors occur: As written in the title i use a simple Verlet integration to approximate the true solution. I know there are other possibilities like Runge-Kutta method, but i saw people doing some nice simulations with a simple Euler-Approximation. So i thought a second order Verlet-Approximation should be sufficient. Maybe this is not the case, so should i use another method of approximation? Second idea: I simply coded it badly and there are better ways to handle it, keeping numerical errors minimal. For further analysis i upload a snip of my small code here: t = t + dt i = 1 while t &lt;= T and i &lt;= n: #A_list was the idea of calculating the acceleration more efficient, i append the necessary entries, calculate the acceleration and delete the entries again to repeat the process A_list.append(x_list[i]) A_list.append(y_list[i]) r = np.sqrt(A_list[0]**2 + A_list[1]**2) A_x = -(G*M/r**2) * A_list[0] * 1/r A_y = -(G*M/r**2) * A_list[1] * 1/r x_i1 = 2*A_list[0] - x_list[i-1] + A_x * dt**2 y_i1 = 2*A_list[1] - y_list[i-1] + A_y * dt**2 del A_list[1] del A_list[0] i = i + 1 t = t + dt x_list.append(x_i1) y_list.append(y_i1) t_list.append(t) I hope this was somewhat readable and there is someone who would like to…
has comment: http://stackoverflow.com/comment/90989695
score: 0
has comment: http://stackoverflow.com/comment/90896141
has title: How to minimize occuring errors in Verlet Integration for orbital mechanics
has comment: http://stackoverflow.com/comment/90895731
type: UnansweredQuestion

http://stackoverflow.com/a/51985628
type: Answer
answers question: http://stackoverflow.com/q/51985371
has body: You can do the following instead: if all(isinstance(i, int) for i in lis): lim = lis[::-1] elif all(isinstance(i, str) for i in lis): lim = [i.upper() for i in lis]
score: 0

http://stackoverflow.com/comment/91095689
has text: please format this into your Q
comment on: http://stackoverflow.com/q/52072935
type: Comment
type: QuestionComment
score: 4

http://stackoverflow.com/q/52107825
tagged with: nltk
linked to: http://stackoverflow.com/q/31689621
has comment: http://stackoverflow.com/comment/91166481
type: Question
answer count: 1
has comment: http://stackoverflow.com/comment/91171684
has answer: http://stackoverflow.com/a/52108005
has comment: http://stackoverflow.com/comment/91166622
has comment: http://stackoverflow.com/comment/91166643
tagged with: chunking
score: 0
has comment: http://stackoverflow.com/comment/91171291
tagged with: python
tagged with: nlp
favorite count: 0
has title: Any good or better or direct way to get the chunking result from a nltk Tree?
has body: I want to chunk the string to get the groups in a certain height. The original order should be kept and it should also be completly contain all the original words. import nltk height = 2 sentence = [("the", "DT"), ("little", "JJ"), ("yellow", "JJ"), ("dog", "NN"), ("barked","VBD"), ("at", "IN"), ("the", "DT"), ("cat", "NN")] pattern = """NP: {&lt;DT&gt;?&lt;JJ&gt;*&lt;NN&gt;} VBD: {&lt;VBD&gt;} IN: {&lt;IN&gt;}""" NPChunker = nltk.RegexpParser(pattern) result = NPChunker.parse(sentence) In [29]: Tree.fromstring(str(result)).pretty_print() S _________________|_____________________________ NP VBD IN NP ________|_________________ | | _____|____ the/DT little/JJ yellow/JJ dog/NN barked/VBD at/IN the/DT cat/NN My approach is kind of brute force like below: In [30]: [list(map(lambda x: x[0], _tree.leaves())) for _tree in result.subtrees(lambda x: x.height()==height)] Out[30]: [['the', 'little', 'yellow', 'dog'], ['barked'], ['at'], ['the', 'cat']] I thought there should exist some direct API or something I can use to do chuncking. Any suggestions are highly appreciated.
accepted answer: http://stackoverflow.com/a/52108005
upvote count: 1
tagged with: depth-first-search
downvote count: 1
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91170858

http://stackoverflow.com/a/55218025
score: 1
type: AcceptedAnswer
has body: Checked with my system screen resolution options available. It had below resolution options available. The script worked fine for all the above options. Note that 1440 x 810 resolution option is not available and hence it also didn't work on my system. May be issue is related to support for the screen resolution on that system and not specific to the above code.
upvote count: 1
accepted answer of: http://stackoverflow.com/q/51987408
answers question: http://stackoverflow.com/q/51987408
type: Answer
downvote count: 0

http://stackoverflow.com/q/52096527
type: Question
has body: We are looking for Devops CD process for our python developers work, where currently they are writing and testing codes using web2py. If we use jenkins, how can we get a better option for the replacement for web2y? Or can we integrate web2py with jenkisn for completing the devops cycle?
downvote count: 0
tagged with: web2py
favorite count: 0
tagged with: web-deployment
tagged with: jenkins
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/91143913
answer count: 0
score: 1
upvote count: 1
has title: Are there any jenkins plugins available for developers work easiness (a replacement for web2py)
tagged with: jenkins-plugins

http://stackoverflow.com/q/51965561
downvote count: 1
type: Question
possible better answer: http://stackoverflow.com/a/51965774
has answer: http://stackoverflow.com/a/51965774
tagged with: web-crawler
accepted answer: http://stackoverflow.com/a/51965716
answer count: 2
favorite count: 0
tagged with: python
tagged with: selenium-webdriver
type: AnsweredQuestion
has title: TypeError: 'str' object is not callable with driver.current_url() (Python 3.6)(Selenium)
has body: My code: https://pastebin.com/WKHZwAib import selenium from selenium import webdriver as web url = 'https://www.wta.org/go-outside/hikes/hike_search? sort=&amp;rating=0&amp;mileage:float:list=0.0&amp;mileage:float:list=25.0&amp;title=&amp;region=all&amp;searchabletext=&amp;filter=Search&amp;subregion=all&amp;b_start:int=0&amp;show_incomplete=on&amp;elevationgain:int:list=0&amp;elevationgain:int:list=5000&amp;highpoint=' driver = web.Chrome('D:/Development/Projects/Test/test/chromedriver') driver.get(url) driver.current_url() I am getting TypeError: 'str' object is not callable on driver.current_url(). Any tips on how I can resolve this? I am going to be running through the pages on this site and grabbing each URL. If there is another way to do this that would avoid this, let me know. Thanks in advance.
upvote count: 2
has answer: http://stackoverflow.com/a/51965716
score: 1
tagged with: web-scraping

http://stackoverflow.com/q/51992946
answer count: 5
tagged with: python
has answer: http://stackoverflow.com/a/51993145
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51993421
accepted answer: http://stackoverflow.com/a/51992999
upvote count: 1
possible better answer: http://stackoverflow.com/a/51993075
type: Question
has comment: http://stackoverflow.com/comment/90936383
has answer: http://stackoverflow.com/a/51993075
has title: How to convert list of keyed 2-lists to list of same-keyed N-lists?
has body: How can I create a list of lists with first element as key: From: myList = [ [26, 'hello'], [26, 'hola'], [26, 'hi'], [26, 'bonjour'], [27, 'bye'],[27, 'doei'], [27, 'see you'], [27, 'tot ziens'] ] To: [ [26, 'hello', 'hola', 'hi', 'bonjour'], [27, 'bye', 'doei', 'see you', 'tot ziens'] ]
downvote count: 0
score: 1
has answer: http://stackoverflow.com/a/51992999
favorite count: 0
has answer: http://stackoverflow.com/a/51993068

http://stackoverflow.com/q/52049311
type: Question
has title: Getting null date while reading a dataframe in pyspark?
answer count: 1
has body: I have a csv file having data in below format 02/04/2018,MZE-RM00007(Kg.),29530,14.5,428185 02/04/2018,MZE-RM00007(Kg.),29160,14.5,422820 02/04/2018,MZE-RM00007(Kg.),22500,14.501,326272.5 02/04/2018,MZE-RM00007(Kg.),29490,14.5,427605 02/04/2018,MZE-RM00007(Kg.),19750,14.5,286375 02/04/2018,MZE-RM00007(Kg.),30140,14.5,437030 02/04/2018,MZE-RM00007(Kg.),24730,14.25,352402.5 02/04/2018,MZE-RM00007(Kg.),29520,14.5,428040 03/04/2018,CHOLINE CHLORIDE-MD00027(Kg.),3000,93,279000 I am trying to read it in pyspark like below spark = SparkSession.builder.\ appName("Weather_Data_Extraction_To_Delhi_Only_2017").\ master("local").\ config("spark.driver.memory", "4g").\ config("spark.executor.memory", "2g").\ getOrCreate() MySchema = StructType([ StructField("sDate", DateType(), True), StructField("Items", StringType(), True), StructField("purchasedQTY", DoubleType(), True), StructField("rate", DoubleType(), True), StructField("purchasedVolume", DoubleType(), True), ]) linesDataFrame = spark.read.format("csv").schema(MySchema).load("/home/rajnish.kumar/eclipse-workspace/ShivShakti/Data/RMPurchaseData.csv") print linesDataFrame.printSchema() and my print schema is root |-- sDate: date (nullable = true) |-- Items: string (nullable = true) |-- purchasedQTY: double (nullable = true) |-- rate: double (nullable = true) |-- purchasedVolume: double (nullable = true) None Now when I query: linesDataFrame.select("sDate","Items","purchasedQTY","rate","purchasedVolume").show() I get below results +-----+-----+------------+----+---------------+ |sDate|Items|purchasedQTY|rate|purchasedVolume| +-----+-----+------------+----+---------------+ | null| null| null|null| null| | null| null| null|null| null| | null| null| null|null| null| | null| null| null|null| null| | null| null| null|null| null| | null| null| null|null| null| | null| null| null|null| null| | null| null| null|null| null| | null| null| null|null| null| | null| null| null|null| null| | null| null| null|null| null| | null| null| null|…
favorite count: 0
score: 0
tagged with: apache-spark
tagged with: python
type: UnansweredQuestion
upvote count: 1
downvote count: 1
tagged with: pyspark
has answer: http://stackoverflow.com/a/52049432

http://stackoverflow.com/a/52007473
upvote count: 13
accepted answer of: http://stackoverflow.com/q/52007139
has body: For your example. Your data: df = pd.DataFrame(data=[['A', '2018-08-05 17:06:01'], ['A', '2018-08-05 17:06:02'], ['A', '2018-08-05 17:06:03'], ['B', '2018-08-05 17:06:07'], ['B', '2018-08-05 17:06:09'], ['B', '2018-08-05 17:06:11']], columns = ['column', 'date']) Solution: df.date = pd.to_datetime(df.date).values.astype(np.int64) df = pd.DataFrame(pd.to_datetime(df.groupby('column').mean().date)) Output: date column A 2018-08-05 17:06:02 B 2018-08-05 17:06:09 I hope it will be helpful.
score: 13
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/52007139
type: Answer

http://stackoverflow.com/comment/91018438
type: QuestionComment
has text: Why do you believe your way is inefficient? It is better than having to loop through the list, get the attribute, check its value, and then modify the button.
comment on: http://stackoverflow.com/q/52034106
score: 0
type: Comment

http://stackoverflow.com/comment/91087347
type: Comment
has text: The driving distance between the locations. I created a 73x73 matrix of distances.
comment on: http://stackoverflow.com/q/52068624
score: 0
type: QuestionComment

http://stackoverflow.com/a/52008637
type: Answer
accepted answer of: http://stackoverflow.com/q/52008298
score: 2
downvote count: 0
upvote count: 2
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/52008298
has body: TPOT will fit the final 'best' pipeline on the full training set: code It's therefore recommended that your testing data never be passed to the TPOT fit function if you plan to directly interact with the 'best' pipeline via the TPOT object. If that is an issue for you, you can retrain the pipeline directly via the tpot.fitted_pipeline_ attribute, which is simply a sklearn Pipeline object. Alternatively, you can use the export function to export the 'best' pipeline to its corresponding Python code and interact with the pipeline outside of TPOT. Additionally, is there a way to access the complete set of trained models corresponding to the set of splits for the winning/optimized pipeline? No. TPOT uses sklearn's cross_val_score when evaluating pipelines, so it throws out the set of trained pipelines from the CV process. However, you can access the scoring results of every pipeline that TPOT evaluated via the tpot.evaluated_individuals_ attribute.

http://stackoverflow.com/comment/91006605
type: AnswerComment
has text: `('100'<'35') is True`, so the first method won't work.
type: Comment
score: 2
comment on: http://stackoverflow.com/a/52028150

http://stackoverflow.com/a/52022159
score: 2
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51963116
answers question: http://stackoverflow.com/q/51963116
type: Answer
has body: This is not an API supported by elasticsearch. To create a boolean field use the put_mapping API (0) or just send a boolean value (True or False) from python and elasticsearch will create the field for you automatically (1). 0 - https://elasticsearch-py.readthedocs.io/en/master/api.html#elasticsearch.client.IndicesClient.put_mapping 1 - https://www.elastic.co/guide/en/elasticsearch/reference/6.4/dynamic-mapping.html
upvote count: 2

http://stackoverflow.com/q/52043323
upvote count: 1
has comment: http://stackoverflow.com/comment/91037558
tagged with: sqlite
has answer: http://stackoverflow.com/a/52043683
favorite count: 0
has comment: http://stackoverflow.com/comment/91037510
has comment: http://stackoverflow.com/comment/91037737
has body: Prelumination: I have the Table "baseline" in the Sqlite3-DB. Table "Baseline" has following columns: word counter Question: Any ideas how it is possible to let sqlite3 engine (if it is more efficient) do for me following operation: if table "baseline" already has an element with primary key "word", than while insertion don't replace this row but do addition between old counter and new counter. Example After following Insertions Commands: "INSERT INTO baseline(word, counter) VALUES 'bla', 1; " "INSERT INTO baseline(word, counter) VALUES 'bla', 1; " I want to get the following data from the DB: &gt;&gt;&gt; "SELECT * FROM baseline;" '("bla", 2)' Thx in advance=)
has comment: http://stackoverflow.com/comment/91038404
tagged with: python
has title: PYTHON SQLITE3 INSERTION: if exist than make addition
has comment: http://stackoverflow.com/comment/91041798
has comment: http://stackoverflow.com/comment/91041559
type: AnsweredQuestion
downvote count: 0
has comment: http://stackoverflow.com/comment/91044576
possible better answer: http://stackoverflow.com/a/52043486
score: 1
has answer: http://stackoverflow.com/a/52043486
type: Question
has comment: http://stackoverflow.com/comment/91037615
accepted answer: http://stackoverflow.com/a/52043683
answer count: 2

http://stackoverflow.com/q/52049576
has answer: http://stackoverflow.com/a/62844521
tagged with: python
tagged with: dependencies
score: 2
type: AnsweredQuestion
has body: In an Azure DataFactory pipeline, I try to make two CopyActivities run sequentially, i.e. first one copies data from blob to SQL table, THEN the second one copies the SQL table to another database. I tried below code, but the result pipeline has no dependency built upon activities (checked in Azure UI from workflow diagram and JSON). When I run the pipeline, I got error message like below: "ErrorResponseException: The template validation failed: 'The 'runAfter' property of template action 'my second activity nameScope' at line '1' and column '22521' contains non-existent action. balababla...." Once I manually add the dependency in Azure UI, I can run the pipeline successfully. I appreciate if someone could point me to example code (Python/C#/Powershell) or document. My Python code: def createDataFactoryRectStage(self, aPipelineName, aActivityStageName, aActivityAcquireName, aRectFileName, aRectDSName, aStageTableName, aStageDSName, aAcquireTableName, aAcquireDSName): adf_client = self.__getAdfClient() ds_blob = AzureBlobDataset(linked_service_name = LinkedServiceReference(AZURE_DATAFACTORY_LS_BLOB_RECT), folder_path=PRJ_AZURE_BLOB_PATH_RECT, file_name = aRectFileName, format = {"type": "TextFormat", "columnDelimiter": ",", "rowDelimiter": "", "nullValue": "\\N", "treatEmptyAsNull": "true", "firstRowAsHeader": "true", "quoteChar": "\"",}) adf_client.datasets.create_or_update(AZURE_RESOURCE_GROUP, AZURE_DATAFACTORY, aRectDSName, ds_blob) ds_stage= AzureSqlTableDataset(linked_service_name = LinkedServiceReference(AZURE_DATAFACTORY_LS_SQLDB_STAGE), table_name='[dbo].[' + aStageTableName + ']') adf_client.datasets.create_or_update(AZURE_RESOURCE_GROUP, AZURE_DATAFACTORY, aStageDSName, ds_stage) ca_blob_to_stage = CopyActivity(aActivityStageName, inputs=[DatasetReference(aRectDSName)], outputs=[DatasetReference(aStageDSName)], source= BlobSource(), sink= SqlSink(write_batch_size = AZURE_SQL_WRITE_BATCH_SIZE)) ds_acquire= AzureSqlTableDataset(linked_service_name = LinkedSe…
upvote count: 2
accepted answer: http://stackoverflow.com/a/62844521
type: Question
tagged with: azure-data-factory
answer count: 2
possible better answer: http://stackoverflow.com/a/52053112
has answer: http://stackoverflow.com/a/52053112
has title: How to create dependency between activities of Pipeline for Azure Data Factory in Python
downvote count: 0
favorite count: 0

http://stackoverflow.com/a/51974501
has comment: http://stackoverflow.com/comment/90899526
upvote count: 1
downvote count: 0
score: 1
has body: You can iterate over the byte string and get a series of bytes in python. These bytes are represented as integers. You then convert them back to hex strings and join them all together with a space between each hex string. &gt;&gt;&gt; a = b'\xff\x00\xff\xff' &gt;&gt;&gt; print( ' '.join( '%02x' % x for x in a ) ) 'ff 00 ff ff' Or using format in python3: &gt;&gt;&gt; a = b'\xff\x00\xff\xff' &gt;&gt;&gt; print( ' '.join( '{:02x}'.format(x) for x in a ) ) 'ff 00 ff ff'
answers question: http://stackoverflow.com/q/51974380
has comment: http://stackoverflow.com/comment/90899433
type: Answer

http://stackoverflow.com/q/51965650
tagged with: regex
score: 1
has answer: http://stackoverflow.com/a/51965975
has body: I have a very long string which has nested loops. I want to extract a pattern in that. String_Text: some random texts...... ........................ ........................ {{info ................. .....texts.............. ...{{ some text }}...... // nested parenthesis 1 ........................ ...{{ some text }}...... // nested parenthesis 2 ........................ }} // End of topmost parenthesis ........................ ..again some random text ........................ ........................ // can also contain {{ }} ......End of string. I want to extract all the text between the topmost parenthesis i.e. Extracted_string: info ................. .....texts.............. ...{{ some text }}...... // nested parenthesis 1 ........................ ...{{ some text }}...... // nested parenthesis 2 ........................ Pattern: 1.) starts with { and can be followed by any number of {. 2.) After that there can be any number of white space. 3.) The first word after that is surely info. 4.) Extract till this bracket is not closed. What is have tried so far: re.findall(r'\{+[^\S\r\n]*info\s*(.*(?:\r?\n.*)*)\}+') I know this is wrong as what this does is find the last instance of } in the string. Can someone help me out in extracting text between those bracket? TIA
accepted answer: http://stackoverflow.com/a/51966129
answer count: 3
upvote count: 1
has comment: http://stackoverflow.com/comment/90881182
linked to: http://stackoverflow.com/q/546433
has title: Regex to find texts between nested parenthesis
type: AnsweredQuestion
downvote count: 0
has answer: http://stackoverflow.com/a/51966129
favorite count: 0
possible better answer: http://stackoverflow.com/a/51965797
has comment: http://stackoverflow.com/comment/90881848
type: Question
has answer: http://stackoverflow.com/a/51965797
tagged with: python

http://stackoverflow.com/q/51964845
type: UnansweredQuestion
score: 6
type: Question
has body: I have tried following code but not sure what is the issue task runPython(type:Exec) { workingDir 'C:\\Users\\adityaj\\git\\Learn\\TestProject' commandLine 'python', 'main.py' } Also attached project hierarchy Below is my build.gradle file: plugins { id 'groovy' id 'com.gradle.plugin-publish' version '0.9.10' id 'eclipse' } apply plugin: 'eclipse' //apply plugin: 'py-build' repositories { jcenter() } dependencies { testCompile 'pypi:Werkzeug:0.7' testCompile 'pypi:Jinja2:2.4' testCompile 'pypi:itsdangerous:0.21' testCompile 'pypi:click:2.0' } task runPython(type:Exec) { workingDir 'C:\\Users\\adityaj\\git\\Learn\\TestProject' commandLine 'python', 'main.py' } test { testLogging { events 'skipped', 'failed', 'standard_error' exceptionFormat 'full' } }
tagged with: gradle
tagged with: python-2.7
downvote count: 0
has comment: http://stackoverflow.com/comment/105791241
favorite count: 0
tagged with: python
has title: Not able to run python script from Gradle?
upvote count: 6
tagged with: build.gradle
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/105669177
answer count: 0

http://stackoverflow.com/a/52050797
has comment: http://stackoverflow.com/comment/91052617
has comment: http://stackoverflow.com/comment/91052166
has comment: http://stackoverflow.com/comment/91052045
has comment: http://stackoverflow.com/comment/91052587
answers question: http://stackoverflow.com/q/52050755
score: 0
has comment: http://stackoverflow.com/comment/91052536
type: Answer
has body: If you're using tail: tail somelog.log | grep -E 'GET|POST' You may also be able to use egrep: tail somelog.log | egrep 'GET|POST' You could also cat the log file and pipe the same egrep or grep -E command.

http://stackoverflow.com/comment/90954648
score: 0
has text: They appear, like all `print` statements on the console log of your application. If you do not work with I/O redirection, those can not be retrieved.
type: QuestionComment
comment on: http://stackoverflow.com/q/52002793
type: Comment

http://stackoverflow.com/q/52063948
has comment: http://stackoverflow.com/comment/91078761
answer count: 0
upvote count: 2
type: UnansweredQuestion
type: Question
tagged with: sqlalchemy
downvote count: 0
favorite count: 0
tagged with: sql-server
has title: Python sqlalchemy writing data into SQL Server
has comment: http://stackoverflow.com/comment/91078579
has body: I'm trying to connect to SQL Server database using sqlalchemy (with pyodbc) on Python 3.6 in Spyder. I get no error when running: import sqlalchemy engine = create_engine('mssql+pyodbc://admin:pass@SERVERNAME/Databasename') But when I take the data and try to write data into the database: d={'col1':[1,2],'col2':[3,4]} df=pd.DataFrame(data=d) df.to_sql('TestTable',con=engine,if_exists='append',index_label='Indx') I get the following error: InterfaceError: (pyodbc.InterfaceError) ('IM002', '[IM002] [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified (0) (SQLDriverConnect)') (Background on this error at: http://sqlalche.me/e/rvf5) Thank you in advance!
tagged with: python
score: 2

http://stackoverflow.com/a/51998482
upvote count: 4
has comment: http://stackoverflow.com/comment/101773109
accepted answer of: http://stackoverflow.com/q/51959066
type: AcceptedAnswer
downvote count: 0
score: 4
has body: So i was able to fix the issue. The issues were: the space I was plotting my data on. My previous meshgrid was from the range -3 to 3 with a 0.1 increment. I changed this to use my training data range limits. (x_min, x_max, y_min, y_max) I was also normalizing my training data when plotting it for my decision boundary. I removed this and plotted the original data points. (not sure if this was causing a problem) the z values I was using were the class values. I changed this to use the probability values obtained from the sigmoid function so that I can use the levels parameter. Below is the working code: import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns sns.set(style="white") def map_features(x, degree): x_old = x.copy() x = pd.DataFrame({"intercept" : [1]*x.shape[0]}) column_index = 1 for i in range(1, degree+1): for j in range(0, i+1): x.insert(column_index, str(x_old.columns[1]) + "^" + str(i-j) + str(x_old.columns[2]) + "^" + str(j), np.multiply(x_old.iloc[:,1]**(i-j), x_old.iloc[:,2]**(j))) column_index+=1 return x def normalize_features(x): global mean_values global std_values for column_name in x.columns[1:]: mean = x[column_name].mean() std = x[column_name].std() x[column_name] = (x[column_name] - mean) / std mean_values[column_name] = mean std_values[column_name] = std return x def sigmoid(z): return 1/(1+np.exp(-z)) def cost(x, y, theta): m = x.shape[0] h_theta = pd.DataFrame(sigmoid(np.dot(x,theta))) cost = 1/m * ((-np.multiply(y,h_theta.apply(np.log)) - np.multiply(1-y, (1-h_theta).apply(np.log))).sum()) return np.asscalar(cost) def gradient_descent(x, y, theta): global cost_values m = x.shape[0] iterations = 1000 alpha = 0.03 cost_values = pd.DataFrame({'iteration' : [0], 'cost' : [cost(x,y,theta)]}) for iteration in range(0,iterations): theta_old = theta.copy() theta.iloc[0,0] = theta.iloc[0,0] - (alpha/m) * np.asscalar((sigmoid(np.dot(x,theta_old)) - y).sum()) for i in range(1,theta.shape[0]): theta.iloc[i,0] =…
type: Answer
has comment: http://stackoverflow.com/comment/101744053
answers question: http://stackoverflow.com/q/51959066
has comment: http://stackoverflow.com/comment/101807464

http://stackoverflow.com/a/52045823
accepted answer of: http://stackoverflow.com/q/52045136
has body: What the test does Django offers certain functions to generate a URL from a view name (optionally with parameters): the reverse(…) [Django-doc] function. Furthermore the opposite is done with the resolve(…) [Django-doc] function: it calculates what path will be called, from a given URL and returns a ResolverMatch object that contains the view name, as well as a reference to the function, etc. If the two functions are implemented correctly - something we as developers have no control about, since we use Django (well of course one can fix bugs and create tickets for the Django development team, but let us ignore that for now), it looks as if the two functions are "inverses" of each other. There might however be some piculiarities. Cases where the test might fail First of all, the test here implicitly checks that a view with the given name exists: in case no such view exists anymore, the reverse lookup will fail, and raise an error. The test thus ensures that one for example does not - by accident - renames the view. Another thing this checks is that the relation between views and URLs is injective: if there are two views producing the same URL, then the function is not injective. If for example there are overlapping paths in the sense that these both match a given URL, then it is possible that the resolve(..) function will point to another URL: if for example the view name generates an URL /some/url, but that one is covered by a path earlier in the list of paths as well, then the resulve will have a different name. Note however that even if the relation between views and URLs is not injective, then this still does not mean this will raise an error: it is possible that the given view name is the first path, and thus that problem is not "detected". Regardless whether this test was intended to check this, it is not a good idea to check this in an ad-hoc fashion: in case one wants to guarantee that all views have a name, etc. It is better to write a test that exhaustively…
answers question: http://stackoverflow.com/q/52045136
upvote count: 2
type: AcceptedAnswer
type: Answer
score: 2
downvote count: 0

http://stackoverflow.com/q/52080462
possible better answer: http://stackoverflow.com/a/66770346
has body: There is cluster ID property that can be retrieved with Get-Cluster | select Id in powershell command. How to get it with WMI? Looks like MSCluster_Cluster doesn't have ID field.
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/66770346
accepted answer: http://stackoverflow.com/a/52121704
tagged with: wmi
type: Question
tagged with: windows-server-2008-r2
answer count: 2
tagged with: failovercluster
has title: How to get cluster id using WMI on Windows Server 2008 R2?
has answer: http://stackoverflow.com/a/52121704
score: 0

http://stackoverflow.com/q/51989790
accepted answer: http://stackoverflow.com/a/51992164
has title: Remove Dotted Selection around QGraphicsItem
favorite count: 0
has body: I've search around online for a solution and most of them are in C++ and not complete answers. I was wondering if someone could help me find out how to remove the selection rectangle around a qgraphicsitem as seen in the image below? import sys from PySide.QtGui import * from PySide.QtCore import * import random class MyGraphicsView(QGraphicsView): def __init__(self): super(MyGraphicsView, self).__init__() self.setDragMode(QGraphicsView.RubberBandDrag) self._isPanning = False self._mousePressed = False # self.setBackgroundBrush(QImage("C:/Users/jmartini/Desktop/Temp/images/flag_0140.jpg")) self.setCacheMode(QGraphicsView.CacheBackground) self.setHorizontalScrollBarPolicy( Qt.ScrollBarAlwaysOff ) self.setVerticalScrollBarPolicy( Qt.ScrollBarAlwaysOff ) def mousePressEvent(self, event): if event.button() == Qt.LeftButton: self._mousePressed = True if self._isPanning: self.setCursor(Qt.ClosedHandCursor) self._dragPos = event.pos() event.accept() else: super(MyGraphicsView, self).mousePressEvent(event) elif event.button() == Qt.MiddleButton: self._mousePressed = True self._isPanning = True self.setCursor(Qt.ClosedHandCursor) self._dragPos = event.pos() event.accept() def mouseMoveEvent(self, event): if self._mousePressed and self._isPanning: newPos = event.pos() diff = newPos - self._dragPos self._dragPos = newPos self.horizontalScrollBar().setValue(self.horizontalScrollBar().value() - diff.x()) self.verticalScrollBar().setValue(self.verticalScrollBar().value() - diff.y()) event.accept() else: super(MyGraphicsView, self).mouseMoveEvent(event) def mouseReleaseEvent(self, event): if event.button() == Qt.LeftButton: if self._isPanning: self.setCursor(Qt.OpenHandCursor) else: self._isPanning = False self.setCursor(Qt.ArrowCursor) self._mousePressed = False elif event.button() == Qt.MiddleButton: self._isPanning = False self.setCursor(Qt.ArrowCursor) self._mousePressed = False super(MyGraphicsView, self).mouseReleaseEvent(event) def mouseDoubleClickEvent(self, event): self.f…
tagged with: python
has answer: http://stackoverflow.com/a/51992164
score: 2
downvote count: 0
tagged with: qgraphicsscene
type: Question
type: AnsweredQuestion
tagged with: pyside
upvote count: 2
tagged with: qgraphicsitem
answer count: 1

http://stackoverflow.com/comment/91162724
score: 1
has text: That `keys()` is only a list if you're on Python 2; on Python 3, it's a `dict_keys` view, and you can't call `sort` on that. Just do `keys = sorted(myDict)` and it'll work on all Python versions, as well as being simpler.
comment on: http://stackoverflow.com/a/52105819
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/91149392
score: 1
type: Comment
type: QuestionComment
has text: So you want to get such JSON blob when you POST to the view?
comment on: http://stackoverflow.com/q/52099275

http://stackoverflow.com/q/51976776
favorite count: 0
type: UnansweredQuestion
tagged with: python
tagged with: logging
score: 1
upvote count: 1
type: Question
tagged with: database
has body: I have a python package and the logging level is set as below (in app.py). logger = logging.getLogger('app') logger.handlers = [] logger.addHandler(logging.StreamHandler()) logger.setLevel(logging.ERROR) logging.getLogger("requests").setLevel(logging.WARNING) I generally import this module DbApp (from app.py) and directly run it. As this package is installed using pip, I don't want to change the logging level in the file. How can I change from my main program to set the logging level? from db.rest import DbApp app = DbApp()
has title: python application changing logging level
has answer: http://stackoverflow.com/a/51976835
downvote count: 0
answer count: 1

http://stackoverflow.com/q/52020581
type: UnansweredQuestion
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/90992329
has comment: http://stackoverflow.com/comment/90992217
has body: I'm trying access a list of related objects through the "related_set.all()" method whenever a model is saved from Django Admin. No matter what I do however the QuerySet is always empty... Here's what it looks like (I've removed a lot of (hopefully) irrelevant stuff) class Board(models.Model): group = models.OneToOneField(Group, on_delete=models.CASCADE) def clean(self): roles = self.role_set.all() # This just returns &lt;QuerySet []&gt; ... validation, etc.... class Role(models.Model): board = models.ForeignKey(Board, on_delete=models.CASCADE) members = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) Funny thing is that it used to work, but after setting the User to be the AUTH_USER_MODEL (after a lot of refactoring) it suddenly stopped returning anything in the QuerySet... For what it matters I'm using a NestedStackedInline in the Admin panel, and what I hope to achieve is that whenever the "Save"-button in the admin panel is called, it should call the clean() method on the Role-class, call the clean() method on the Board-class and upon success call the save() method on both. I've been troubleshooting this for way too long now and would really appreciate if anyone have some pointers or ideas.
tagged with: orm
has comment: http://stackoverflow.com/comment/90992048
has comment: http://stackoverflow.com/comment/90992202
has comment: http://stackoverflow.com/comment/90992119
type: Question
has comment: http://stackoverflow.com/comment/90992426
has comment: http://stackoverflow.com/comment/90992302
has comment: http://stackoverflow.com/comment/90992100
has title: Django Related Object empty queryset on clean()
has comment: http://stackoverflow.com/comment/90992035
score: 0
has comment: http://stackoverflow.com/comment/90991817
answer count: 0

http://stackoverflow.com/comment/90963257
type: Comment
has text: Try this: `Q_VEC.append(np.mean(np.array(DOC), axis=0))` . Maybe in your `numpy` version using a list of numpy arrays is what is behind this error.
score: 0
comment on: http://stackoverflow.com/q/52005471
type: QuestionComment

http://stackoverflow.com/q/52056540
score: 1
favorite count: 0
type: Question
has body: I'm having three hosts(ex-XX.XX.XX.XX:P1,YY.YY.YY.YY:P2, ZZ.ZZ.ZZ.ZZ:P3)and i'm connecting these hosts with pymongo.MongoClient(). So can anyone guide me, how to find which host is primary using pymongo-3.7.1 with python-3.6?
tagged with: python
answer count: 1
has title: How to check which host is primary in multiple URI using pymongo?
has comment: http://stackoverflow.com/comment/91138785
tagged with: pymongo
upvote count: 1
has comment: http://stackoverflow.com/comment/91180216
tagged with: mongodb
downvote count: 0
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/52094292

http://stackoverflow.com/a/52241520
score: 1
answers question: http://stackoverflow.com/q/52094973
has body: Since it's been over a week, I'm going to assume that this homework came due already and it's safe to provide a complete answer. Let's do it without ugly numeric indexes by using Python 3 unpacking: def countpairs(string): if string: first, *second_on = string if second_on: second, *third_on = second_on if first == second: return 1 + countpairs(third_on) return countpairs(second_on) # outdent a level and still works! Work out why. return 0 for word in ['', 'I', 'oo', 'aaa', 'zzzz', 'bookkeeper']: print(word, ":", countpairs(word)) OUTPUT &gt; python3 test.py : 0 I : 0 oo : 1 aaa : 1 zzzz : 2 bookkeeper : 3 &gt;
upvote count: 1
type: Answer
downvote count: 0

http://stackoverflow.com/comment/91170146
comment on: http://stackoverflow.com/a/52103722
type: Comment
score: 0
has text: Nicely done, @rahlf23; thank-you. My upvote does not count yet, as i am still a n00b here, but it is nonetheless recorded, apparently.
type: AnswerComment

http://stackoverflow.com/q/52009943
type: Question
has body: Can the following be coded more compactly using list comprehension? labels=[] for i in range(10): labels=labels+[i]+9*[''] labels=labels+[10]
has answer: http://stackoverflow.com/a/52013292
downvote count: 0
has answer: http://stackoverflow.com/a/52013325
possible better answer: http://stackoverflow.com/a/52013292
accepted answer: http://stackoverflow.com/a/52013476
answer count: 4
favorite count: 0
upvote count: 2
tagged with: python
linked to: http://stackoverflow.com/q/952914
score: 2
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52013722
has title: List comprehension to create a list
tagged with: list-comprehension
has answer: http://stackoverflow.com/a/52013476

http://stackoverflow.com/comment/91100340
type: Comment
score: 0
comment on: http://stackoverflow.com/q/52017297
has text: @CrisLuengo since the background of both the `plt.show` and the border margin is white, it's pretty hard to tell whether a border is there or not.
type: QuestionComment

http://stackoverflow.com/comment/90977290
type: Comment
has text: You can't just write SQL into Python code.
comment on: http://stackoverflow.com/q/52013248
score: 0
type: QuestionComment

http://stackoverflow.com/a/52042456
type: Answer
score: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/52024026
answers question: http://stackoverflow.com/q/52024026
has body: A sess.run(train_step) after inputting data fixed my code

http://stackoverflow.com/a/52047651
upvote count: 2
answers question: http://stackoverflow.com/q/52045496
type: Answer
score: 2
downvote count: 0
has body: The solution requires a bit of gymnastics, in that you have to import the current script as if it were an external module. So for instance. The contents of schedule_twitter_jobs.py would be: from redis import Redis from rq_scheduler import Scheduler import schedule_twitter_jobs # we are importing the very module we are executing def schedule_fetch_tweets(args, queue_name): ''' This is the child process to schedule''' concurrent_queue = Scheduler(queue_name=queue_name+'_concurrent', connection=Redis()) # this scheduler is created based on a queue_name that will be passed in for task in range(args.n_tasks): scheduler_concurrent.schedule( scheduled_time=datetime.utcnow(), func=app.controller.fetch_twitter_tweets, args=[args.statuses_backfill, fill_start_time]) serial_queue = Scheduler(queue_name='myqueue', connection=Redis()) serial_queue.schedule( '''This is the first schedule.''' scheduled_time=datetime.utcnow(), func=schedule_twitter_jobs.schedule_fetch_tweets, #now we have a fully-qualified reference to the function we need to schedule. args=(args, ttl, timeout, queue_name) #pass through the args to the child schedule )

http://stackoverflow.com/q/52009353
has body: class AbstractBaseField(models.Model): choices = models.CharField(_("Choices"), max_length=1000, blank=True) class Meta: abstract = True class TicketField(AbstractBaseField): pass TicketField._meta.get_field("choices").max_length = 5000 I'm trying to modify the max_length attribute on a field on TicketField, which inherits from an abstract model. As you see, I've monkey-patched the field on model definition and the migration is generated as expected. The field has the max_length applied correctly and I can set the value just fine via the shell, but admin validation fails as if the old max_length is still present, showing the error Ensure this value has at most 1000 characters (it has XXXX). I've inspected the max_length on the ModelForm and the Validator values at runtime, and they all use the new max_length, but somehow a validation error is still being raised. (Pdb) self.fields["choices"].max_length 5000 (Pdb) self.fields["choices"].validators[0]._constructor_args ((5000,), {}) (Pdb) self.fields["choices"].widget.attrs {u'class': u'vTextField', u'maxlength': '5000'}
type: UnansweredQuestion
tagged with: django
tagged with: python
answer count: 0
downvote count: 0
score: 1
type: Question
has title: Modify max_length for a field in an abstract model
upvote count: 1
favorite count: 0

http://stackoverflow.com/q/52102025
has comment: http://stackoverflow.com/comment/91158067
has comment: http://stackoverflow.com/comment/91159842
has answer: http://stackoverflow.com/a/52104373
has comment: http://stackoverflow.com/comment/91158727
has title: Using a imported module in python result in permission denied error
score: 0
answer count: 1
tagged with: permissions
has comment: http://stackoverflow.com/comment/91157854
has comment: http://stackoverflow.com/comment/91158142
accepted answer: http://stackoverflow.com/a/52104373
has comment: http://stackoverflow.com/comment/91158027
tagged with: pip
tagged with: python
type: AnsweredQuestion
has body: I'm trying to use a imported module (pylightning) in a python script that runs using apache under user www-data. The script gives a permission error when run via apache as user www-data: File "/usr/local/lib/python3.4/dist-packages/lightning/lightning.py", line 69, in call sock.connect(self.socket_path) PermissionError: [Errno 13] Permission denied To fix this I have intensively searched and found i needed to reinstall the module as www-data user: sudo pip3 uninstall pylightning sudo -H -u www-data pip3 install pylightning The script still runs smoothly from the CLI as regular user: $python3 index.py Content-Type: text/html etc... But from apache (through a browser or from the command line as user www-data) still gives the same error: $sudo -u www-data python3 /var/www/html/index.py Content-Type: text/html Traceback (most recent call last): File "/var/www/html/index.py", line 29, in <module> print(rpc_interface.listpeers()) File "/usr/local/lib/python3.4/dist-packages/lightning/lightning.py", line 345, in listpeers return self.call("listpeers", payload) File "/usr/local/lib/python3.4/dist-packages/lightning/lightning.py", line 69, in call sock.connect(self.socket_path) PermissionError: [Errno 13] Permission denied Anyone has any idea here? Script source: #!/usr/bin/env python3 import hashlib from lightning.lightning import LightningRpc rpc_interface = LightningRpc("/home/pi/.lightning/lightning-rpc") print ("Content-Type: text/html\n\n"); print (" asd"); print(rpc_interface.listpeers()) the error triggers on this line: print(rpc_interface.listpeers())
has comment: http://stackoverflow.com/comment/91155759
has comment: http://stackoverflow.com/comment/91156485
tagged with: import
type: Question

http://stackoverflow.com/q/52102805
has comment: http://stackoverflow.com/comment/91157596
has comment: http://stackoverflow.com/comment/91156515
has comment: http://stackoverflow.com/comment/91157337
tagged with: python
has body: I want to plot 5 different subplots, one for each year of data. For each year, I want to show the DEMs and REPs for each county. I have written the following code so far: fig = plt.figure(figsize=(13,10)) plt.subplot(3, 2, 1) plt.bar(data=districts_2018'DEM', 'REP', x=districts_2018.index, height=(districts_2018'DEM', 'REP')) plt.subplot(3, 2, 2) plt.bar(data=districts_2017'DEM', 'REP', x=districts_2017.index, height=districts_2017['DEM']) plt.subplot(3, 2, 3) plt.bar(data=districts_2016'DEM', 'REP', x=districts_2016.index, height=districts_2016['DEM']) plt.subplot(3, 2, 4) plt.bar(data=districts_2015'DEM', 'REP', x=districts_2015.index, height=districts_2015['DEM']) plt.subplot(3, 2, 5) plt.bar(data=districts_2014'DEM', 'REP', x=districts_2014.index, height=districts_2014['DEM']) plt.tight_layout(); However, as in the case of the first subplot (3,2,1) I get the error: ValueError: shape mismatch: objects cannot be broadcast to a single shape. This code works if I only set the height to districts_2018['DEM'] but then that only shows the DEMs and not the REPs.
type: AnsweredQuestion
has title: Two dataframes broadcast together in multiple subplots
accepted answer: http://stackoverflow.com/a/52104959
has comment: http://stackoverflow.com/comment/91159809
tagged with: plot
has comment: http://stackoverflow.com/comment/91158482
type: Question
has answer: http://stackoverflow.com/a/52104959
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/91160307
score: 0
tagged with: pandas
answer count: 1
has comment: http://stackoverflow.com/comment/91158278

http://stackoverflow.com/comment/91148407
type: QuestionComment
comment on: http://stackoverflow.com/q/52097392
score: 0
has text: @VivekKumar, just confirming, it's not possible to do this with random forest and my only solution is to use 4 separate binary classifiers?
type: Comment

http://stackoverflow.com/a/53533757
score: 1
has body: Even though, the given input image links are not working &amp; so I obviously doesn't know the following is what you have asked for, I learnt something from your question, when I was working on, removing table structure lines from given image, I like to share what I have learnt, for the future readers. I followed the steps provided in opencv documentation to remove the lines. But that only removed the horizontal lines. When I tried to remove vertical lines, the result image only had the vertical lines. The text in the table was not there. Then I came across your question &amp; saw final_img = cv2.subtract(img1, img) in the question. Tried that &amp; it worked great. Here are the steps that I followed: # Load the image src = cv.imread(argv[0], cv.IMREAD_COLOR) # Check if image is loaded fine if src is None: print ('Error opening image: ' + argv[0]) return -1 # Show source image cv.imshow("src", src) # [load_image] # [gray] # Transform source image to gray if it is not already if len(src.shape) != 2: gray = cv.cvtColor(src, cv.COLOR_BGR2GRAY) else: gray = src # Show gray image # show_wait_destroy("gray", gray) # [gray] # [bin] # Apply adaptiveThreshold at the bitwise_not of gray, notice the ~ symbol gray = cv.bitwise_not(gray) bw = cv.adaptiveThreshold(gray, 255, cv.ADAPTIVE_THRESH_MEAN_C, \ cv.THRESH_BINARY, 15, -2) # Show binary image # show_wait_destroy("binary", bw) # [bin] # [init] # Create the images that will use to extract the horizontal and vertical lines horizontal = np.copy(bw) vertical = np.copy(bw) # [horiz] # [vert] # Specify size on vertical axis rows = vertical.shape[0] verticalsize = rows / 10 # Create structure element for extracting vertical lines through morphology operations verticalStructure = cv.getStructuringElement(cv.MORPH_RECT, (1, verticalsize)) # Apply morphology operations vertical = cv.erode(vertical, verticalStructure) vertical = cv.dilate(vertical, verticalStructure) # [init] # [horiz] # Specify size on horizontal axis cols = horizonta…
downvote count: 0
answers question: http://stackoverflow.com/q/52052884
type: Answer
upvote count: 1

http://stackoverflow.com/a/52073894
type: AcceptedAnswer
downvote count: 0
type: Answer
score: 1
answers question: http://stackoverflow.com/q/52073784
upvote count: 1
accepted answer of: http://stackoverflow.com/q/52073784
has body: you can use values In [1]: header_dict = {0: "id", ...: 1: "PR_DISPLAY_NAME", ...: 2: "PR_HOME_ADDRESS_STREET", ...: 3: "PR_ZIP", ...: 29: "PR_SURNAME", ...: } ...: In [2]: s = '{} ' * len(header_dict) In [3]: s.format(*header_dict.values()) Out[3]: 'id PR_DISPLAY_NAME PR_HOME_ADDRESS_STREET PR_ZIP PR_SURNAME ' and your code will: Person = namedtuple('Person',s.format(*header_dict.values()))

http://stackoverflow.com/q/51999007
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion
downvote count: 2
has answer: http://stackoverflow.com/a/51999679
tagged with: python
tagged with: dictionary
has title: Am I doing something wrong
has comment: http://stackoverflow.com/comment/90947165
has body: The website I learn python on doesn't explain the dictionaries well so I resort to this.What I'm supposed to do is find the average of the 3 of these room's temperatures over how many days the user types(maximum is 3). Each day has 4 temperatures over 1 day. When I run this code, it doesn't produce any temperatures for the 3 rooms. hi={} days=int(input('How many days of data do you have? ')) print('Average Temperatures:') f = open('temps1.txt') g= open('temps1.txt') and open('temps2.txt') o=open('temps1.txt') and open('temps2.txt') and open('temps3.txt') if days=='1': for line in f: parts = line.strip().split(",") if parts[0] not in hi: hi[parts[0]] = [] hi[parts[0]].append(int(val[1])) elif days=='2': for line in g: parts = line.strip().split(",") if parts[0] not in hi: hi[parts[0]] = [] hi[parts[0]].append(int(val[1])) elif days=='3': for line in o: parts = line.strip().split(",") if parts[0] not in hi: hi[parts[0]] = [] hi[parts[0]].append(int(val[1])) for k, v in hi.items(): print("Room: {}, Avg: {}".format(k, sum(v)/days*4)) temps1.txt activates only when 1 is typed by the user in the input question: Living Room,23 Bedroom,24 Kitchen,22 Living Room,24 Bedroom,26 Kitchen,22 Living Room,25 Bedroom,26 Kitchen,23 Living Room,24 Bedroom,26 Kitchen,23 temps2.txt only activates when the user enters 2 in the first question(this is used alongside temps1.txt): Living Room,26 Bedroom,24 Kitchen,23 Living Room,27 Bedroom,24 Kitchen,24 Living Room,28 Bedroom,25 Kitchen,26 Living Room,29 Bedroom,26 Kitchen,28 temps3.txt only activates when the user enters 3 in the first question(this is used alongside temps1.txt and temps2.txt): Living Room,28 Bedroom,29 Kitchen,28 Living Room,28 Bedroom,30 Kitchen,29 Living Room,29 Bedroom,29 Kitchen,31 Living Room,21 Bedroom,23 Kitchen,21 Am I able to produce a code to do this but with no imports of the sort? Also one more thing, am I able to assign variables to 'for in' statements and 'if' statements?
tagged with: file
type: Question
upvote count: 0
score: -2
has comment: http://stackoverflow.com/comment/90947157
answer count: 1

http://stackoverflow.com/a/52075956
downvote count: 0
upvote count: 5
type: Answer
has comment: http://stackoverflow.com/comment/91106747
has comment: http://stackoverflow.com/comment/91106305
answers question: http://stackoverflow.com/q/52049865
has body: As you seem a little unsure/inconsistent about the details of your question, I would like to suggest a very simple, alternative solution, not in Python but too big for a comment, that helps you and others explore whether you really want this and what you actually want - before anyone spends hours coding Python. I suggest you use ImageMagick which is installed on most Linux distros and is available for macOS and Windows. So, just in Terminal, you can make a sample image which is black with a white square in the middle, like this: convert -size 100x100 xc:black -fill white -draw "rectangle 10,10 90,90" test.png Now try your filter and you can see the corners are rounded: convert test.png -statistic mode 10x10 result.png Now try again with a bigger "radius": convert test.png -statistic mode 20x20 result.png Maybe you can experiment with that and see if it does what you want before anyone wastes too much time coding anything.
score: 5

http://stackoverflow.com/q/51973640
score: 1
tagged with: django-rest-framework
favorite count: 0
tagged with: python-3.x
linked to: http://stackoverflow.com/q/51970130
type: UnansweredQuestion
tagged with: django
tagged with: python
has answer: http://stackoverflow.com/a/51973753
has body: I have tried to put details to server but getting 403 error below is my code. export const updateAppTypeData = (appData) =&gt; async dispatch =&gt; { const token = localStorage.getItem('token') const response = await axios({ method : 'put', url: ('http://localhost:8000/api/posts/appType/'+appData.id+'/'), data: appData, headers: {'Content-Type': 'application/json', 'Authorization': 'Token '+token}, json: true }).then(function (response) { console.log(response); }); //dispatch({ type : FETCH_APP_TYPE , payload: response.data }); }; Any help will be a big plus. Thanks.
has title: How to send axios put request with jwt token in reactjs
upvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/90897911
has comment: http://stackoverflow.com/comment/90898731
tagged with: reactjs
downvote count: 0
answer count: 1

http://stackoverflow.com/q/52024005
type: UnansweredQuestion
upvote count: 1
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/90998660
has comment: http://stackoverflow.com/comment/90998945
has comment: http://stackoverflow.com/comment/90998915
score: 1
has title: Transferring Django from windows to ubuntu
tagged with: configparser
type: Question
has comment: http://stackoverflow.com/comment/90998317
downvote count: 0
has comment: http://stackoverflow.com/comment/90998425
has comment: http://stackoverflow.com/comment/90998855
tagged with: virtualenv
tagged with: ini
has answer: http://stackoverflow.com/a/52024399
has comment: http://stackoverflow.com/comment/90998848
has comment: http://stackoverflow.com/comment/90998889
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/90998714
has body: I have written a project in windows with Django, It works well in windows, I wanted to transfer it to Ubuntu, first I installed the python3 and then made a virtualenv, activated it and installed django and required packages, I got some errors but the main irritating one is that, I have a INI file, I use the configobj to read it, it works well in windows but in Ubuntu it give 'Key error' here is my code: from configobj import ConfigObj ConfigPath = os.path.join(settings.MEDIA_ROOT, 'Vars.ini') ConfigParser = ConfigObj(ConfigPath) print(ConfigParser['FileNames']['MotionName']) and here is the file: [FileNames] MotionName = test1 I also tried to use only lowercase words but still no chance.

http://stackoverflow.com/comment/90993881
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52015508
score: 1
has text: If you're using java 10, it's OK to define the map as `var signs = Map.of("+", add, "-", sub);`

http://stackoverflow.com/q/52100801
upvote count: 3
has comment: http://stackoverflow.com/comment/91152546
tagged with: z3py
type: Question
tagged with: z3
accepted answer: http://stackoverflow.com/a/52101306
answer count: 2
downvote count: 0
has answer: http://stackoverflow.com/a/60790255
favorite count: 0
has title: How to print z3 solver results print(s.model()) in order?
score: 3
possible better answer: http://stackoverflow.com/a/60790255
tagged with: python
has answer: http://stackoverflow.com/a/52101306
has body: Suppose I have a list of 10 variables v = [Real('v_%s' % (i+1)) for i in range(10)] and I want to add a simple constraint like this s = Solver() for i in range(10): s.add(v[i] == i) if s.check() == sat: print(s.model()) So a satisfying model is v_1 = 0, v_2 = 1 .... v_10 = 9. However the output of print(s.model()) is totoally unordered which makes me confused when I have lots of variables in a bigger model. For this example, the output of my computer is v_5, v_7, v_4, v_2, v_1, v_3, v_6, v_8, v_9, v_10, but I want to ouput the variables of this model in order like v_1, v_2, ..., v_10. Can anyone tell me does z3Py have this kind of function or not? Thanks!
type: AnsweredQuestion
tagged with: python-3.x

http://stackoverflow.com/comment/90961828
type: Comment
comment on: http://stackoverflow.com/a/52005796
type: AnswerComment
score: 0
has text: I think it is probably worth to add this to the answer :)

http://stackoverflow.com/comment/90914819
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51981089
has text: @Giacomo Alzetta - Thanks! I wondered about the import/exception approach, and maybe I'll end up doing that. But I have a gripe that it treats the (eventually) normal case of using Python3 as an exception, which feels not-so-future-proof to me. (E.g. suppose a new module "StringIO" comes available in the future?). And I can't construct it the other way round because Python2 has io.StringIO. I think using `six.StringIO` is a better option, but so far I've been able to avoid this kind of external library dependency.

http://stackoverflow.com/a/51995371
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/51995287
answers question: http://stackoverflow.com/q/51995287
type: Answer
score: 2
downvote count: 0
upvote count: 2
has body: Very close! Everything is correct except for the way you are trying to count the number of percent changes greater than 0. Here is one way of doing it def countIncrease(df,column): print sum(df[column].pct_change().fillna(0) &gt; 0)

http://stackoverflow.com/a/52031003
has comment: http://stackoverflow.com/comment/91012618
has body: You are missing the name argument for the path function: Change the following line path('login/', auth_views.LoginView.as_view(template_name='login.html')), to path('login/', auth_views.LoginView.as_view(template_name='login.html'), name='login'),
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/52030913
has comment: http://stackoverflow.com/comment/91012596
answers question: http://stackoverflow.com/q/52030913
upvote count: 5
has comment: http://stackoverflow.com/comment/91012678
type: Answer
downvote count: 0
score: 5

http://stackoverflow.com/q/52046064
answer count: 0
type: Question
tagged with: opencv
tagged with: alpha
has comment: http://stackoverflow.com/comment/91047046
has body: I am loading in an image with alpha and am confused at the data I am see to represent each pixel. I am splitting the pixel to get each b,g,r,a band respectively and am confused with my output when loaded into a data set as seen below: Pixel ---------------------B-band---------G-band----------R-band---------------A-band Why are my white pixels in the r band (4th column) 254 and not 255? Why are the alpha values ranging from 0 to 255 and not 0 to 1? Another interesting note is that where the alpha is set to 0 (transparent) I am confused as to why the pixels being given a color and alternately why opaque pixels are displayed as white and not transparent? Code: img = cv2.imread('/Volumes/EXTERNAL/ClassifierImageSets/Origional_2.png',-1) b,g,r,a = cv2.split(img) test = pd.DataFrame({'bBnad':b.flat[:],'gBnad':g.flat[:],'rBnad':r.flat[:],'Alpha':a.flat[:]}) with pd.option_context('display.max_rows', None, 'display.max_columns', 4): print(test)
score: 0
tagged with: pandas
has title: Pixel data incorrect with alpha
tagged with: scikit-learn
has comment: http://stackoverflow.com/comment/91043454
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91047086
tagged with: python
has comment: http://stackoverflow.com/comment/91043233

http://stackoverflow.com/comment/91110369
type: Comment
comment on: http://stackoverflow.com/q/52077984
score: 0
type: QuestionComment
has text: @duhaime acutally, setting public ip is excellent choice. can you guide me how to do that.

http://stackoverflow.com/comment/91814246
type: Comment
comment on: http://stackoverflow.com/q/52107447
has text: @mfitzp ill check it tomorrow AM. I am away from my Lc. Thanks for the reply!
score: 0
type: QuestionComment

http://stackoverflow.com/comment/91062320
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52055984
score: 0
has text: @NilsWerner the `group-0[number]` are keys autocreated because in that page is it possible to create textboxes clicking on the button add, so that `group-0[number]` are just the name for each textbox, what I really need is to sort are the `M01`, `M02`..

http://stackoverflow.com/q/52052946
upvote count: 1
has answer: http://stackoverflow.com/a/52145431
has answer: http://stackoverflow.com/a/68176018
tagged with: ubuntu-16.04
type: AnsweredQuestion
downvote count: 0
tagged with: amazon-ec2
score: 1
has body: I am trying to install dlib on EC2 ubuntu 16.04, I tried many options suggested on google like this, But getting above error, I install on my local machine which was quite simple and installed easily. Also I tried by changing my environment since I was thinking, may be some python version compatibility issue, but with python3 also getting same error. Output here: Collecting dlib Using cached https://files.pythonhosted.org/packages/df/aa/6a9bb2a763107bb2606d6ee1aa65fcd3b51375a9ef6436e9c9280b0dd63c/dlib-19.15.0.tar.gz Installing collected packages: dlib Running setup.py install for dlib ... error Complete output from command /home/ubuntu/newEnv/bin/python3 -u -c "import setuptools, tokenize;__file__='/tmp/pip-install-xqrlt_6v/dlib/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-c_7ykc12/install-record.txt --single-version-externally-managed --compile --install-headers /home/ubuntu/newEnv/include/site/python3.5/dlib: running install running build running build_py package init file 'dlib/__init__.py' not found (or not a regular file) running build_ext Building extension for Python 3.5.2 (default, Nov 23 2017, 16:37:01) Invoking CMake setup: 'cmake /tmp/pip-install-xqrlt_6v/dlib/tools/python -DCMAKE_LIBRARY_OUTPUT_DIRECTORY=/tmp/pip-install-xqrlt_6v/dlib/build/lib.linux-x86_64-3.5 -DPYTHON_EXECUTABLE=/home/ubuntu/newEnv/bin/python3 -DCMAKE_BUILD_TYPE=Release' -- The C compiler identification is GNU 5.4.0 -- The CXX compiler identification is GNU 5.4.0 -- Check for working C compiler: /usr/bin/cc -- Check for working C compiler: /usr/bin/cc -- works -- Detecting C compiler ABI info -- Detecting C compiler ABI info - done -- Detecting C compile features -- Detecting C compile features - done -- Check for working CXX compiler: /usr/bin/c++ -- Check for working CXX compiler: /usr/bin/c++ -- works -- Detecting CXX compiler ABI info -- Detecting CXX compi…
accepted answer: http://stackoverflow.com/a/52145431
favorite count: 0
type: Question
possible better answer: http://stackoverflow.com/a/52064938
has comment: http://stackoverflow.com/comment/110417337
tagged with: python
has title: Error in dlib installation AWS EC2 instance Ubuntu 16.04
has answer: http://stackoverflow.com/a/52064938
tagged with: dlib
answer count: 3

http://stackoverflow.com/comment/114846052
comment on: http://stackoverflow.com/q/51958667
score: 0
has text: Relatd: https://stackoverflow.com/questions/32445375/pyo-server-boot-returns-error-on-ubuntu-14-04
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51969836
has comment: http://stackoverflow.com/comment/90890337
answer count: 0
score: 1
has comment: http://stackoverflow.com/comment/90891010
has comment: http://stackoverflow.com/comment/90890281
type: Question
has comment: http://stackoverflow.com/comment/90890392
has comment: http://stackoverflow.com/comment/90890839
has comment: http://stackoverflow.com/comment/90890349
has comment: http://stackoverflow.com/comment/90890375
has comment: http://stackoverflow.com/comment/90890197
has comment: http://stackoverflow.com/comment/90890298
has body: For a piece of coursework, I have been asked to create some functions to input a lecturer's details and then store them in a tuple which I have done below. def lect_input() payroll = input("Enter your Payroll. ") department = input("Enter your department. ") salary = input("Enter your Salary. ") forename = input("Enter your Forename. ") surname = input("Enter your Surname. ") list_lect = (payroll, department, salary, forename, surname) def lect_details() str_lect = '{0:&gt;15},{1:&lt;25}{2:&gt;15} {3:&lt;10}£{4:&lt;5}'.format(list_lect[3], list_lect[4], list_lect[0], list_lect[1], list_lect[2]) print(str_lect) My next task reads as follows... In the main body of the program, write code which prompts the user for a filename and attempts to open the file whose name is supplied. If the file cannot be opened an error message should be output and the program should terminate; otherwise, the program should read each line from the file and supply it to the lecturer-creation function, storing the tuples returned by this function in a list. so far I have managed to find a small snippet of code which can help me but I'm not sure where to go from this and am stuck trying 'read each line from the file'. As well as this I am not fully sure that what I have is entirely correct and would make my job easier later on in the exercise (I am still new to programming). Any help would be much appreciated. f = raw_input("\n Hello, user. " "\n \n Please type in the path to your file and press 'Enter': ") myfile = open(f, 'r') ^I have tried this but I'm not sure that's what I'm being asked to do.
has title: Python - storing tuples returned by a function into a list
upvote count: 1
has comment: http://stackoverflow.com/comment/90890234
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/90890238
tagged with: python-3.x
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90890496
tagged with: python

http://stackoverflow.com/comment/90958216
comment on: http://stackoverflow.com/q/52004427
has text: In addition to @DanielRoseman, if you have to do those, `threading.Lock` the threads when writing.
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/91159545
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52104007
has text: @MattW. which version of `pandas` are you using? And what command is causing the deprecation warning?
score: 0

http://stackoverflow.com/a/52075272
has body: Thanks for the answers! I also found this: pos=np.ones((xsize,ysize)) xx,yy=np.mgrid[:xsize,:ysize] for element in lis: circle=(xx-element[0])**2+(yy-element[1])**2 pos=np.logical_and(pos,(circle&lt;(lis[element]**2))) #pos&amp;circle&lt;(lis[element]**2 doesn't work(I read somewhere it does) I needed this array for marking when I reached my destination or not. if pos[dest[0]][dest[1]]==1 #Reached
type: Answer
answers question: http://stackoverflow.com/q/52072784
score: 0

http://stackoverflow.com/q/52049714
upvote count: 2
tagged with: python
tagged with: regex
has title: Regular Expression Mismatch
score: 2
type: AnsweredQuestion
has body: I am trying to match values that come in this format: , ####-####-####-#### , ####-########-##### , ##-###-#-###-##-#-#### For example: 2018-03-10, 2018-02-10-2019, 10-20-2016 should only capture , 2018-02-10-2019 but it's capturing all of the line. The , at the start is optional. I'm basically trying to find values that have 3 or more hyphens in them. Here is what I am using: (, )?([\/-]?)(\d+[\/-]?){4,} This is not only capturing the values I want, but it's also capturing values like this: 30/05/2018 Can someone help me troubleshoot this? Edit #1: This is not a duplicate question, one is matching via hyphens and another is matching digits. They are in different locations and represent different things.
has comment: http://stackoverflow.com/comment/91052260
accepted answer: http://stackoverflow.com/a/52049814
type: Question
linked to: http://stackoverflow.com/q/52050018
has comment: http://stackoverflow.com/comment/91052355
tagged with: pandas
answer count: 1
downvote count: 0
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/52049814

http://stackoverflow.com/comment/91101479
type: QuestionComment
comment on: http://stackoverflow.com/q/52075814
score: 0
type: Comment
has text: print one of the data as well. which you tried decoding.

http://stackoverflow.com/comment/91170328
type: AnswerComment
comment on: http://stackoverflow.com/a/52109851
type: Comment
has text: Thanks. I did try the 'SK\.' in first place but didn't get the idea. And now I noticed that default parameter was ** regex=True **. It works now. Thx.
score: 1

http://stackoverflow.com/comment/91121298
score: 0
comment on: http://stackoverflow.com/q/52083998
type: Comment
has text: I did not. Can you put that in an answer and I can mark it solved?
type: QuestionComment

http://stackoverflow.com/a/52030534
has comment: http://stackoverflow.com/comment/91012711
has comment: http://stackoverflow.com/comment/91012348
type: AcceptedAnswer
has body: There's eucl_dist package (disclaimer: I am its author) that basically contains two methods to solve the problem of computing squared euclidean distances that are more efficient than SciPy's cdist, especially for large arrays ( with decent to large number of columns). We will use some of the codes from its source code to adapt to our problem here to give us two approaches. Approach #1 Following the wiki contents, we could leverage matrix-multiplication and some NumPy specific implementations for our first approach, like so - def pdist_squareformed_numpy(a): a_sumrows = np.einsum('ij,ij-&gt;i',a,a) dist = a_sumrows[:,None] + a_sumrows -2*np.dot(a,a.T) np.fill_diagonal(dist,0) return dist Approach #2 One more method would be to create "extended" versions of input arrays, again discussed in detail in that github source code link to have our second approach, which is better for lesser columns, as is the case here, like so - def ext_arrs(A,B, precision="float64"): nA,dim = A.shape A_ext = np.ones((nA,dim*3),dtype=precision) A_ext[:,dim:2*dim] = A A_ext[:,2*dim:] = A**2 nB = B.shape[0] B_ext = np.ones((dim*3,nB),dtype=precision) B_ext[:dim] = (B**2).T B_ext[dim:2*dim] = -2.0*B.T return A_ext, B_ext def pdist_squareformed_numpy_v2(a): A_ext, B_ext = ext_arrs(a,a) dist = A_ext.dot(B_ext) np.fill_diagonal(dist,0) return dist Note that these give us squared eucludean distances. So, for the actual distances, we want to use np.sqrt() if that's the final output needed. Sample runs - In [380]: np.random.seed(0) ...: a = np.random.rand(5,3) In [381]: from scipy.spatial.distance import cdist In [382]: cdist(a,a) Out[382]: array([[0. , 0.29, 0.42, 0.2 , 0.57], [0.29, 0. , 0.58, 0.42, 0.76], [0.42, 0.58, 0. , 0.45, 0.9 ], [0.2 , 0.42, 0.45, 0. , 0.51], [0.57, 0.76, 0.9 , 0.51, 0. ]]) In [383]: np.sqrt(pdist_squareformed_numpy(a)) Out[383]: array([[0. , 0.29, 0.42, 0.2 , 0.57], [0.29, 0. , 0.58, 0.42, 0.76], [0.42, 0.58, 0. , 0.45, 0.9 ], [0.2 , 0.42, 0.45, 0. , 0.51], [0.57, 0.76, 0.…
downvote count: 0
has comment: http://stackoverflow.com/comment/91012187
has comment: http://stackoverflow.com/comment/91012104
upvote count: 8
has comment: http://stackoverflow.com/comment/91012733
type: Answer
has comment: http://stackoverflow.com/comment/91012138
has comment: http://stackoverflow.com/comment/91012607
accepted answer of: http://stackoverflow.com/q/52030458
has comment: http://stackoverflow.com/comment/91012894
score: 8
has comment: http://stackoverflow.com/comment/91012704
has comment: http://stackoverflow.com/comment/91012224
has comment: http://stackoverflow.com/comment/91012159
has comment: http://stackoverflow.com/comment/91012378
answers question: http://stackoverflow.com/q/52030458
has comment: http://stackoverflow.com/comment/91012442

http://stackoverflow.com/q/52107184
tagged with: amazon-web-services
downvote count: 0
answer count: 1
favorite count: 0
tagged with: static
tagged with: django
tagged with: python
has title: SuspiciousOperation when loading image in django
type: AnsweredQuestion
score: 3
tagged with: amazon-s3
upvote count: 3
type: Question
has body: I'm deploying a web application in django and there is one page that loads some images from my static files that is returning the following error: SuspiciousOperation at /wallet Attempted access to '/coins/' denied. I've been reading that it is because the media file but I don't understand it because all the other static files load correctly. I'm using s3 from aws. This is my s3 configuration file: import datetime import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) AWS_ACCESS_KEY_ID = "whatever" AWS_SECRET_ACCESS_KEY = "whatever" AWS_STORAGE_BUCKET_NAME = 'xxx' AWS_S3_CUSTOM_DOMAIN = '%s.s3.us-east-2.amazonaws.com' % AWS_STORAGE_BUCKET_NAME AWS_S3_OBJECT_PARAMETERS = { 'CacheControl': 'max-age=86400', } AWS_LOCATION = 'static' STATICFILES_DIRS = [ os.path.join(BASE_DIR, '../static'), ] STATIC_URL = 'https://%s/%s/' % (AWS_S3_CUSTOM_DOMAIN, AWS_LOCATION) STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' MEDIA_URL = '' MEDIA_ROOT = '' and the whole error in debug mode is the following one: Environment: Request Method: GET Request URL: http://ip/wallet Django Version: 2.0.5 Python Version: 3.6.6 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'profiles', 'portfolios', 'django_extensions', 'rest_framework', 'corsheaders', 'storages'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware'] Template error: In template /home/ubuntu/chimpy/templates/base.html, error at line 54 Atte…
has answer: http://stackoverflow.com/a/52107217
accepted answer: http://stackoverflow.com/a/52107217

http://stackoverflow.com/q/52095109
type: AnsweredQuestion
upvote count: 1
type: Question
accepted answer: http://stackoverflow.com/a/52095313
has title: Python regular expression; brackets within brackets
has comment: http://stackoverflow.com/comment/91141873
answer count: 1
downvote count: 0
score: 1
favorite count: 0
tagged with: parsing
has body: I know that there are SO MANY python regular expression questions here, I just cannot figure out my specific question, even with examples. I have tried using regex101 but it's just not clicking. I have these sentences: [Hi]-THISISALOADOFTEXT-[text] I-X-(blah[THIS2CAN2Have-SymbolsAndNumbers0])-ABCD-{x}A-AB A-[This can 4 have any X1 rubbish in it]-ABCDDS-OH A-F{a}R-(textnumber1)-AB-[ThisIsText123]-P-{d}C-(ThisCanHaveNumbers1)-W-[ThisIsSymbolsText123] I just want to pull out what is between the square brackets, EXCEPT when the square brackets are enclosed by parentheses (rounded brackets). So in the above example, it would return: [Hi], [text] ...nothing returned for line 2... [This can 4 have any X1 rubbish in it] [ThisIsText123], [ThisIsSymbolsText123] It almost works with this code: import re pattern = re.compile(r'(\[.*?\])') regex = re.findall(pattern,text) I was trying to incorporate the 'not' like this: ?!A-Za-z0-9(\[.*?\]) that I got from the python manual, but various attempts at this not working. The only problem is that the above code also returns [THIS2CAN2Have-SymbolsAndNumbers0], I do not want this, as it is enclosed by parentheses. Importantly, and where I am getting stuck, is that there can be text and numbers in between the square brackets and the rounded brackets, as in this example: (blah[THIS2CAN2Have-SymbolsAndNumbers0]) Can someone help? As a side note, just FYI, the ultimate goal once I figure out the regex is to incorporate into a loop that says: For each sentence, find text in square brackets If square brackets not enclosed by parentheses (rounded brackets), do one routine. elif square brackets enclosed by parentheses, do a different routine. Edit 1: How could I extend this, so that for the sequences that have square brackets in parentheses, the full phrase in the parenthesis are returned. So for example, the input sequences: [Hi]-THISISALOADOFTEXT-[text] I-X-(blah[THIS2CAN2Have-SymbolsAndNumbers0])-ABCD-{x}A-AB A-[This can 4 have any X1 rubbis…
tagged with: python
tagged with: regex
has answer: http://stackoverflow.com/a/52095313

http://stackoverflow.com/comment/91120911
has text: @PatrickArtner I intended to remove all the minimum elements off the list, that's the reason for it.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52085276

http://stackoverflow.com/comment/91012894
comment on: http://stackoverflow.com/a/52030534
score: 0
type: AnswerComment
has text: i'll use the `pdist_squareformed_numpy()`. it's only 2 times slower than scipy. `pdist_squareformed_numpy_v2()` is relatively fast, but slower than my `vert_dist_matrix()` with vectorized inner loop. see the update in original post.
type: Comment

http://stackoverflow.com/comment/90968823
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/52008774
has text: It should have an option of `.all()` which will return all the rows.
score: 0

http://stackoverflow.com/comment/91094506
type: QuestionComment
has text: Isn't the function for minimize in the form `f(x, *args)` instead of `f(*args, x)`? I actually don't quite understand, what your code is supposed to achieve (input, restrictions, output). It might be helpful to post a simple input dataset with the expected output, so people can test their code. See [ How to create a Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve).
score: 1
comment on: http://stackoverflow.com/q/52068810
type: Comment

http://stackoverflow.com/comment/90884186
type: QuestionComment
has text: i want the output of "print(str(df.dtypes))" which gives something like: Concept ID uint16 Model ID category Cell category Fuse category .... ..... to be able to print the non-unicode column names if any
type: Comment
comment on: http://stackoverflow.com/q/51966532
score: 0

http://stackoverflow.com/q/52063354
has body: I am trying to get data from the website but I want to select first 1000 link open one by one and get data from there. I have tried: list_links = driver.find_elements_by_tag_name('a') for i in list_links: print (i.get_attribute('href')) through this getting extra links which are not required. for example: https://www.magicbricks.com/property-for-sale/residential-real-estate?bedroom=1,2,3,4,5,%3E5&amp;proptype=Multistorey-Apartment,Builder-Floor-Apartment,Penthouse,Studio-Apartment,Residential-House,Villa,Residential-Plot&amp;cityName=Mumbai we will get more than 50k link. How to open only first 1000 link has in below with properties photos. Edit I have tried this also: driver.find_elements_by_xpath("//div[@class='.l-srp__results.flex__item']") driver.find_element_by_css_selector('a').get_attribute('href') for matches in driver: print('Liking') print (matches) #matches.click() time.sleep(5) But getting error: TypeError: 'WebDriver' object is not iterable Why I am not getting link by using this line: driver.find_element_by_css_selector('a').get_attribute('href') Edit 1 I am trying to sort links as per below but getting error result = re.findall(r'https://www.magicbricks.com/propertyDetails/', my_list) print (result) Error: TypeError: expected string or bytes-like object or Tried a = ['https://www.magicbricks.com/propertyDetails/'] output_names = [name for name in a if (name[:45] in my_list)] print (output_names) Not getting anything. All links are in list. Please suggest Thank you in advance. Please suggest
has answer: http://stackoverflow.com/a/52065417
has comment: http://stackoverflow.com/comment/91077404
score: 0
tagged with: python-3.x
type: UnansweredQuestion
tagged with: web-scraping
tagged with: python
has comment: http://stackoverflow.com/comment/91077240
tagged with: selenium
tagged with: web-crawler
type: Question
has answer: http://stackoverflow.com/a/52073317
has title: How to click one by one to get data from website by using selenium python
answer count: 2

http://stackoverflow.com/comment/90904055
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51976677
has text: You need to answer all of the questions, not just some of them. Do you have multiple copies of Python installed? What is the actual output of those `--version` commands?
score: 0

http://stackoverflow.com/a/54363424
has body: You need to send the Assertion Control along with your modify operation (see RFC 4528). Basically the control contains a filter which has to be matched. I'm using this control in my web2ldap to prevent concurrent writes to do anything bad. I have some doubts that ldap3 module supports it out-of-the-box though. Further notes: Not all LDAP servers support this control. There are subtle bugs in LDAP server implementations supporting this control.
downvote count: 0
score: 1
upvote count: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/51982547
answers question: http://stackoverflow.com/q/51982547
type: Answer

http://stackoverflow.com/comment/91003590
comment on: http://stackoverflow.com/a/52026626
has text: Thank you very much, I was looking for every mistake but didn't see this one!
type: AnswerComment
score: 0
type: Comment

keras
tags question: http://stackoverflow.com/q/52078836
tags question: http://stackoverflow.com/q/52065812
tags question: http://stackoverflow.com/q/52069367
tags question: http://stackoverflow.com/q/51979677
tags question: http://stackoverflow.com/q/52063286
tags question: http://stackoverflow.com/q/52034983
tags question: http://stackoverflow.com/q/52058848
tags question: http://stackoverflow.com/q/51993599
tags question: http://stackoverflow.com/q/52095862
tags question: http://stackoverflow.com/q/52090857
tags question: http://stackoverflow.com/q/51997384
tags question: http://stackoverflow.com/q/52093062
tags question: http://stackoverflow.com/q/51970426
tags question: http://stackoverflow.com/q/52014004
tags question: http://stackoverflow.com/q/51960343
tags question: http://stackoverflow.com/q/52071751
tags question: http://stackoverflow.com/q/51983391
tags question: http://stackoverflow.com/q/52001543
tags question: http://stackoverflow.com/q/52020748
tags question: http://stackoverflow.com/q/52012667
tags question: http://stackoverflow.com/q/52045585
tags question: http://stackoverflow.com/q/52043511
tags question: http://stackoverflow.com/q/52032296
tags question: http://stackoverflow.com/q/52009468
tags question: http://stackoverflow.com/q/52004148
tags question: http://stackoverflow.com/q/52106360
tags question: http://stackoverflow.com/q/52023702
tags question: http://stackoverflow.com/q/52024350
tags question: http://stackoverflow.com/q/52067481
tags question: http://stackoverflow.com/q/52004350
tags question: http://stackoverflow.com/q/52089601
tags question: http://stackoverflow.com/q/51972909
tags question: http://stackoverflow.com/q/52092999
tags question: http://stackoverflow.com/q/52058487
tags question: http://stackoverflow.com/q/51960471
tags question: http://stackoverflow.com/q/52104406
tags question: http://stackoverflow.com/q/52095790
tags question: http://stackoverflow.com/q/52042199
tags question: http://stackoverflow.com/q/51969472
tags question: http://stackoverflow.com/q/52004548
tags question: http://stackoverflow.com/q/52024342
tags question: http://stackoverflow.com/q/51972552
tags question: http://stackoverflow.com/q/52109710
tags question: http://stackoverflow.com/q/51980730
tags question: http://stackoverflow.com/q/51992336
tags question: http://stackoverflow.com/q/51975951
tags question: http://stackoverflow.com/q/52085468
tags question: http://stackoverflow.com/q/52019658
tags question: http://stackoverflow.com/q/51962106
tags question: http://stackoverflow.com/q/52006745
tags question: http://stackoverflow.com/q/52000103
tags question: http://stackoverflow.com/q/52082538
tags question: http://stackoverflow.com/q/52096523
tags question: http://stackoverflow.com/q/52026823
tags question: http://stackoverflow.com/q/52018226
tags question: http://stackoverflow.com/q/52047126
tags question: http://stackoverflow.com/q/51989867
tags question: http://stackoverflow.com/q/52059580
tags question: http://stackoverflow.com/q/52103972
tags question: http://stackoverflow.com/q/52067100
tags question: http://stackoverflow.com/q/51962659
tags question: http://stackoverflow.com/q/52023609
tags question: http://stackoverflow.com/q/52015499
tags question: http://stackoverflow.com/q/51958745
tags question: http://stackoverflow.com/q/51982179
tags question: http://stackoverflow.com/q/52084911
tags question: http://stackoverflow.com/q/52032280
tags question: http://stackoverflow.com/q/52108685
tags question: http://stackoverflow.com/q/52018645
tags question: http://stackoverflow.com/q/51985357
tags question: http://stackoverflow.com/q/52097698
tags question: http://stackoverflow.com/q/52087578
tags question: http://stackoverflow.com/q/52019226
tags question: http://stackoverflow.com/q/52001272
tags question: http://stackoverflow.com/q/52075519
tags question: http://stackoverflow.com/q/52010073
tags question: http://stackoverflow.com/q/52060555
tags question: http://stackoverflow.com/q/52056382
tags question: http://stackoverflow.com/q/51963377
tags question: http://stackoverflow.com/q/52092259

http://stackoverflow.com/a/52052051
has body: b = [[i, j] for i in a for j in a[i]] for nested for loops in list comprehension the first loop will be the one whose variable you will be using in the second one, like here for example i is used in the second loop, nested for loops in list comprehensions are hard to read therefore you should better avoid it.
answers question: http://stackoverflow.com/q/52052003
has comment: http://stackoverflow.com/comment/91054826
has comment: http://stackoverflow.com/comment/91054916
downvote count: 0
score: 8
has comment: http://stackoverflow.com/comment/91054696
upvote count: 8
type: Answer
has comment: http://stackoverflow.com/comment/91054507
has comment: http://stackoverflow.com/comment/91054626

http://stackoverflow.com/a/52048161
answers question: http://stackoverflow.com/q/52048071
type: Answer
score: 1
upvote count: 1
accepted answer of: http://stackoverflow.com/q/52048071
type: AcceptedAnswer
downvote count: 0
has body: I took the time to copy your code and run it. I debugged it with an if check on the input length. The major issue is your for loop was incorrectly placed and running for each iteration of your while loop. I would write this down on paper if you do not understand the iteration process. Amped up code: Guess_1 = input() Number_2 = input() Set_dead_1 = set() def teste_dead_1(): index_1 = 0 Guess1Length = len(Guess_1) Number2Length = len(Guess_1) if Guess1Length &lt; 3 or Number2Length &lt; 3: print('Input must be more than 3 characters') return False while index_1 &lt;= 3: if Guess_1[index_1] == Number_2[index_1]: Set_dead_1.add(Number_2[index_1]) index_1 += 1 for i in Set_dead_1: print(i, "is dead.") return True teste_dead_1()

http://stackoverflow.com/a/51974980
type: AcceptedAnswer
downvote count: 0
score: 1
type: Answer
accepted answer of: http://stackoverflow.com/q/51974807
upvote count: 1
answers question: http://stackoverflow.com/q/51974807
has body: It looks like the problem is in the order of the astype and fillna calls. &gt;&gt;&gt; df.astype(str).fillna('') user_index movie_index genre_index cast_index 0 3590 1514 10|12|17|35 46|534 1 63 563 4|2|1|8 None 2 15 9 None 9|27 If you switch the order of the two methods you get something that works: &gt;&gt;&gt; df.fillna('').astype(str).apply(lambda x: [ [int(z) + offset_dct.get(x.name, 0) for z in y.split('|') if z] for y in x]) user_index movie_index genre_index cast_index 0 [3592] [1514] [15, 17, 22, 40] [46, 534] 1 [65] [563] [9, 7, 6, 13] [] 2 [17] [9] [] [9, 27] Also there was an error in your original list comprehension. You can't put an else clause in the if condition of a list comprehension. The if condition is purely there to tell the comprehension which values to keep. If you wanted to do something differently depending on the value of each item, you'd need to put that logic in the function part of the comprehension (probably using a lambda expression). But for this particular problem you didn't need anything else than what I wrote above.

http://stackoverflow.com/comment/90952128
has text: @kevinkayaks, yes there was slight mixing of dimension, I had earlier assumed (3, h, w). Corrected.
comment on: http://stackoverflow.com/a/51997339
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/91098361
score: 3
type: AnswerComment
type: Comment
has text: Your iterator isn't a valid iterator (or at least breaks conventions and could lead to confusing errors) since iterators must also be iterable as discussed in my answer. You either need to inherit from `collections.abc.Iterator` or define `def __iter__(self): return self`.
comment on: http://stackoverflow.com/a/52058739

http://stackoverflow.com/comment/90970415
type: Comment
type: QuestionComment
score: 0
has text: What is the batch size? It seems it has been set to a very high value!
comment on: http://stackoverflow.com/q/52009816

http://stackoverflow.com/a/52032888
accepted answer of: http://stackoverflow.com/q/52024954
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/91021751
has comment: http://stackoverflow.com/comment/91023824
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/91020033
answers question: http://stackoverflow.com/q/52024954
has body: As far as I understood you, your data is 44 dimensional and not a time series. An RNN is computing operations on a sequence of data, i.e. a 2D and not a 1D tensor. But you can still use a RNN for 1D vectors, by interpreting them not as one n-dimensional vector but as a time series of n steps, each containing a 1D vector. model = Sequential() model.add(Reshape((-1, 1) model.add(LSTM(44, input_shape=(6900, 44), )) model.add(Dense(1)) model.compile(loss='mape', optimizer='adam', metrics=['mse', 'mae', 'mape']) model.fit(X_train, y_train, epochs=100, batch_size=10, verbose=1)
type: Answer

http://stackoverflow.com/comment/91097854
has text: so, you dont need to create the file5.xlsx , you are putting the df into file5.xlsx, instead you create a sheet named file5 write the df directly into foo.xlsx. If making the file5.xlsx is absolutely mandatory, you can write the df into file5.xlsx and read it back again using read_excel, then use that dfnew = pd.read_excel('file5.xlsx') in my code, replace dfnew with df in that case.
type: Comment
comment on: http://stackoverflow.com/a/52073775
type: AnswerComment
score: 0

http://stackoverflow.com/q/51982189
has comment: http://stackoverflow.com/comment/90916125
answer count: 3
linked to: http://stackoverflow.com/q/33549854
linked to: http://stackoverflow.com/q/20669375
tagged with: python
has comment: http://stackoverflow.com/comment/90914212
favorite count: 0
score: 2
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/90914280
downvote count: 1
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/63694808
has answer: http://stackoverflow.com/a/51983326
has answer: http://stackoverflow.com/a/51983525
upvote count: 3
has comment: http://stackoverflow.com/comment/90914249
has comment: http://stackoverflow.com/comment/90915810
has title: Equivalent of R's ls() function in Python to remove all created objects
possible better answer: http://stackoverflow.com/a/63694808
accepted answer: http://stackoverflow.com/a/51983525
has comment: http://stackoverflow.com/comment/90914264
type: Question
has comment: http://stackoverflow.com/comment/90914603
has body: I am new in Python. There is a function in R called ls(). I can easily remove any created objects using ls() and rm() functions as bellow. R Code # Create x and y x = 1 y = "a" # remove all created objects ls() # [1] "x" "y" rm(list = ls()) # Try to print x x # Error: object 'x' not found In this post someone suggested an equivalent of ls() in python. So, I have tried to do the same operation in python. Python Code # Create x and y x = 1 y = "a" # remove all created objects for v in dir(): del globals()[v] # Try to print x x # NameError: name 'x' is not defined But the problem is when x is recreated and printed it is throwing error: # Recreate x x = 1 # Try to print x x Traceback (most recent call last): File "", line 1, in x File "C:\SomePath\Anaconda\lib\site-packages\IPython\core\displayhook.py", line 258, in call self.update_user_ns(result) File "C:\SomePath\Anaconda\lib\site-packages\IPython\core\displayhook.py", line 196, in update_user_ns if result is not self.shell.user_ns['_oh']: KeyError: '_oh' I have noticed dir() give some extra objects other than my objects. Is there any function which will give the same output like R's ls()?
has comment: http://stackoverflow.com/comment/90914362
has comment: http://stackoverflow.com/comment/90914197

http://stackoverflow.com/a/52024844
accepted answer of: http://stackoverflow.com/q/52024311
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/91001584
has comment: http://stackoverflow.com/comment/91001498
type: Answer
has comment: http://stackoverflow.com/comment/91001378
score: 13
downvote count: 0
upvote count: 13
answers question: http://stackoverflow.com/q/52024311
has body: The problem is that getter didn't even start executing, which you can confirm by adding a print at its beginning. Since the try block was never entered, the except didn't run either. This happens because, in contrast to await, ensure_future doesn't start executing the coroutine right away, it just schedules it to run at the next event loop iteration, like call_soon does for ordinary functions. Since you cancel the task immediately, it gets removed from the runnable set and its coroutine gets closed without ever having started. Add an await asyncio.sleep(0) before task.cancel() and you should observe the behavior you expect. I suspect you don't need to make such change in your actual code - in the unlikely case that the task gets cancelled before it ran, as in the example, it won't get a chance to acquire the resources that try/except cleans up in the first place. Two tangential remarks: You probably want to re-raise asyncio.CancelledError after handling it, otherwise it will be suppressed. That's not a problem in getter as shown in the question, but it could be an issue if the code were buried in a function call. Even better, consider using finally or with, which propagate the exception and ensure that the resources are released regardless of exception type. When you need to create a task and run a coroutine, loop.create_task is preferred to asyncio.ensure_future. In short, although both do the same thing for coroutines, create_task makes the intention clearer; ensure_future is designed to accept a wider range of objects and procure a future of an unspecified type.

http://stackoverflow.com/q/52050108
tagged with: python-3.x
has answer: http://stackoverflow.com/a/73448710
tagged with: python
has answer: http://stackoverflow.com/a/52050137
accepted answer: http://stackoverflow.com/a/52050137
answer count: 4
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/63185314
score: 7
tagged with: http://stackoverflow.com/tag/json
linked to: http://stackoverflow.com/q/9170288
has comment: http://stackoverflow.com/comment/129707312
type: Question
has answer: http://stackoverflow.com/a/63185314
linked to: http://stackoverflow.com/q/27129681
has comment: http://stackoverflow.com/comment/91050776
has comment: http://stackoverflow.com/comment/91050785
downvote count: 0
has body: I want to create a json file like this: {"946705035":4,"946706692":4 ...} I am taking a column that only contains Unix Timestamp and group them. result = data['Last_Modified_Date_unixtimestamp_no_time'].value_counts() In [21]: result.head() Out[21]: 1508284800 131 1508716800 106 1508371200 101 1508457600 99 1508630400 96 Name: Last_Modified_Date_unixtimestamp_no_time, dtype: int64 transform to a dict result = result.to_dict() result ''' {1507161600: 1, 1507852800: 1, 1508198400: 64, 1508284800: 131, ... 1535155200: 1, 1535241600: 1} ''' import json result = json.dumps(result) with open('result.json', 'w') as fp: json.dump(result, fp, indent=4) result this is the data structure that I expected {"946705035":4,"946706692":4}
upvote count: 7
has title: how to remove a back slash from a JSON file
has answer: http://stackoverflow.com/a/54746319
favorite count: 0

http://stackoverflow.com/a/52065406
has comment: http://stackoverflow.com/comment/91081385
has body: You don't need to do a nested loop over the keys. Instead you can just check if the key_new is in the dict_old and if it is, compare the values and make the update. for key_new in dict_new.keys(): if (dict_old.get(key_new) and dict_old[key_new] == dict_new[key_new]): dict_update[key_new] = dict_old[key_new]
score: 0
has comment: http://stackoverflow.com/comment/91081418
has comment: http://stackoverflow.com/comment/91081544
answers question: http://stackoverflow.com/q/52065292
type: Answer
has comment: http://stackoverflow.com/comment/91081495
has comment: http://stackoverflow.com/comment/91081354

http://stackoverflow.com/comment/91037557
type: Comment
comment on: http://stackoverflow.com/a/52042449
has text: Oh I see. Yeah, just exclude 'USN' as a column then and see my edit above.
score: 0
type: AnswerComment

http://stackoverflow.com/q/52047986
duplicate of: http://stackoverflow.com/q/41602162
upvote count: 1
type: Question
downvote count: 0
score: 1
favorite count: 0
has body: I am trying to map a relationship between a gym model and its offer and events model. The idea is 1 gym can have many offers and many events. But 1 offer cannot belong to many gyms and 1 event cannot belong to many gyms. So, with the look of things, it is a one to Many relation. So far so good. This is my first time working with the Django ORM, so my approach might be a bit naive. I would like to essentially have tables in my db such as a table for gym, table for events and a table for offers. The offer and event table is connected to the gym through the gym id.How can i achieve that ? Because so far i see some pretty strange things in my Django admin page.This is what i tried so far class Program(models.Model): id = models.AutoField(primary_key=True) created = models.DateTimeField(auto_now_add=True, editable=False) last_updated = models.DateTimeField(auto_now=True, editable=False) name = models.CharField(max_length=100) price = models.DecimalField(max_digits=6, decimal_places=2) class Meta: ordering = ('last_updated',) def __str__(self): return "%s %s" % (self.id, self.price) class Offer(models.Model): id = models.AutoField(primary_key=True) created = models.DateTimeField(auto_now_add=True, editable=False) last_updated = models.DateTimeField(auto_now=True, editable=False) name = models.CharField(max_length=100) numberofsessions = models.CharField(max_length=100) price = models.DecimalField(max_digits=6, decimal_places=2) expireddate = models.DateTimeField(auto_now_add=True, editable=False) class Meta: ordering = ('last_updated',) def __str__(self): return "%s %s" % (self.id, self.expireddate) class Event(models.Model): id = models.AutoField(primary_key=True) created = models.DateTimeField(auto_now_add=True, editable=False) last_updated = models.DateTimeField(auto_now=True, editable=False) name = models.CharField(max_length=100) location = models.CharField(max_length=100) price = models.DecimalField(max_digits=6, decimal_places=2) eventdate = models.DateTimeField(au…
type: UnansweredQuestion
tagged with: django
tagged with: python
linked to: http://stackoverflow.com/q/41602162
has title: multiple foreign key in a model (One to Many mapping) django python?
has comment: http://stackoverflow.com/comment/91046808
answer count: 0

http://stackoverflow.com/a/52077862
has comment: http://stackoverflow.com/comment/91105863
type: Answer
answers question: http://stackoverflow.com/q/52077771
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/91105565
upvote count: 1
has comment: http://stackoverflow.com/comment/91105528
has body: A very basic option. See here for an explanation. [^.]\s([A-Z]\w+) import re s = 'This is a Test sentence. The sentence is Supposed to Ignore the Words at the beginning of the Sentence, And others.' re.findall(r'[^.]\s([A-Z]\w+)', s) output ['Test', 'Supposed', 'Ignore', 'Words', 'Sentence', 'And']

http://stackoverflow.com/q/52065009
tagged with: web-scraping
score: 11
has answer: http://stackoverflow.com/a/52169632
type: Question
has comment: http://stackoverflow.com/comment/91208264
has body: I've written a script in python to reach the target page where each category has their avaiable item names in a website. My below script can get the product names from most of the links (generated through roving category links and then subcategory links). The script can parse sub-category links revealed upon clicking + sign located right next to each category which are visible in the below image and then parse all the product names from the target page. This is one of such target pages. However, few of the links do not have the same depth as other links. For example this link and this one are different from usual links like this one. How can I get all the product names from all the links irrespective of their different depth? This is what I've tried so far: import requests from urllib.parse import urljoin from bs4 import BeautifulSoup link = "https://www.courts.com.sg/" res = requests.get(link) soup = BeautifulSoup(res.text,"lxml") for item in soup.select(".nav-dropdown li a"): if "#" in item.get("href"):continue #kick out invalid links newlink = urljoin(link,item.get("href")) req = requests.get(newlink) sauce = BeautifulSoup(req.text,"lxml") for elem in sauce.select(".product-item-info .product-item-link"): print(elem.get_text(strip=True)) How to find trget links:
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91207462
has answer: http://stackoverflow.com/a/52130032
has answer: http://stackoverflow.com/a/52142848
has comment: http://stackoverflow.com/comment/91208698
downvote count: 0
accepted answer: http://stackoverflow.com/a/52169632
has comment: http://stackoverflow.com/comment/91189157
favorite count: 0
tagged with: beautifulsoup
possible better answer: http://stackoverflow.com/a/52104264
has answer: http://stackoverflow.com/a/52104264
tagged with: python
answer count: 4
upvote count: 11
has title: Trouble parsing product names out of some links with different depth
tagged with: python-3.x

http://stackoverflow.com/comment/90905127
type: Comment
has text: @Bunny Your list would start off is empty, correct. Again, I just pre-set the list as an example.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51976607

http://stackoverflow.com/comment/90955034
has text: there you got your bug then, have you tried running the test with an arbitrary input? If that works, then all you have to do is generate that input format from your data.
comment on: http://stackoverflow.com/q/52002342
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/51974378
downvote count: 0
has body: template is a sequence of characters, not the word stream on which your code depends. word takes on the values W, h, o, , ... A quick fix could be: to nest loops for each thing you want to replace: question_list = [] for name in dictionary["Name"]: for job in dictionary["Job"]: for month in dictionary["Month"]: new_sent = template[:] # copy of template for old, new in [("Name", name), ("Job", job), ("Month", month)]: template.replace(old, new) question_list.append(new) This is still very brute-force, but is at the programming level you're using. The triple-loop can be replaced with itertools.product, if you want to learn to use that package. You can also automate the words you're replacing with a regex for words in angle brackets. In fact, you can cram this entire process into a single-statement list comprehension, which you assign to question_list.
type: Answer
upvote count: 1
answers question: http://stackoverflow.com/q/51974207
score: 1

http://stackoverflow.com/a/52041147
answers question: http://stackoverflow.com/q/52040800
upvote count: 2
has comment: http://stackoverflow.com/comment/91032957
score: 2
downvote count: 0
has body: you should also encode the labels, else it won't work. I've dowload it too, and changing just the code as below allow me to run perfectly. (apart from the missing closing ')' at the end of the code but i think is copy paste mistake) from sklearn import preprocessing le = preprocessing.LabelEncoder() np.random.seed(5) iris = read_csv('iris.csv') iris = iris.values X = iris[:,:4] # features y = le.fit_transform(iris[:,4]) # target
type: Answer

http://stackoverflow.com/a/52096683
has comment: http://stackoverflow.com/comment/91151332
answers question: http://stackoverflow.com/q/52096279
upvote count: 1
score: 1
has body: I believe using iterkeys() is much efficient. for k in d.iterkeys(): d[k] = [1.0] You can also do the same without any loops and in a single line using fromkeys(): d = d.fromkeys(d, [1.0]) Hope it helps!!
downvote count: 0
type: Answer

http://stackoverflow.com/comment/90983050
comment on: http://stackoverflow.com/a/52012161
has text: That works, but you don't need to do this. There is an `auto_paging_iterator` in stripe-python that handles it all for you(scroll down a little on [this](https://stripe.com/docs/api/python#pagination) page : `for coupon in stripe.Coupon.list().auto_paging_iter():`
score: 1
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/90962083
type: QuestionComment
type: Comment
has text: However if you require specific formatting for each of the list elements this requires an additional mapping to the formatted elements before joining. You could also generate the format string dynamically by using `len(sample_list)`.
score: 1
comment on: http://stackoverflow.com/q/52006062

http://stackoverflow.com/a/56130636
score: 0
has body: You can also do this, but the other answer is better code: i = 0 sum = 100 while i &lt; 7: sum = sum * 1.1 i += i
type: Answer
answers question: http://stackoverflow.com/q/52107758

http://stackoverflow.com/q/52081556
favorite count: 0
has answer: http://stackoverflow.com/a/52081650
type: Question
has title: pytest verbose output explanation
upvote count: 1
tagged with: python
answer count: 1
accepted answer: http://stackoverflow.com/a/52081650
tagged with: pytest
tagged with: pytest-django
has body: I am using pytest-django to run unit tests I made. When I use the -v flag I get an output like: dashboard/apps/excel_import/tests.py::ExcelImportTestCase::test_multiple_excel PASSED [ 50%] dashboard/apps/excel_import/tests.py::ExcelImportTestCase::test_specific_excel PASSED [100%] I can't find in the pytest docs, or anywhere else on google, what the PASSED [ 50%] means. I have 4 asserts in that specific test, does it mean I passed 2 and failed 2? if so then why doesn't it tell me I failed some tests? I don't know if this is relevant but I am also using python-cov for code coverage. The code coverage results claim 100% of that file is being run, so it doesn't seem like only half the tests were run or something of the sort. If anyone know what the PASSED [ 50%] means I will be very grateful for the insight. Thanks in advance for any help available!
type: AnsweredQuestion
downvote count: 0
score: 1

import
type: Tag
tags question: http://stackoverflow.com/q/51962662
tag name: import
tags question: http://stackoverflow.com/q/52047314
tags question: http://stackoverflow.com/q/51959579
tags question: http://stackoverflow.com/q/52106962
tags question: http://stackoverflow.com/q/52048701
tags question: http://stackoverflow.com/q/51996163
tags question: http://stackoverflow.com/q/52025036
tags question: http://stackoverflow.com/q/52102025
tags question: http://stackoverflow.com/q/52009543
tags question: http://stackoverflow.com/q/52009234
tags question: http://stackoverflow.com/q/52011425
tags question: http://stackoverflow.com/q/52029201
tags question: http://stackoverflow.com/q/52101013
tags question: http://stackoverflow.com/q/52054135
tags question: http://stackoverflow.com/q/52047387

http://stackoverflow.com/q/51976675
linked to: http://stackoverflow.com/q/43554124
answer count: 1
has comment: http://stackoverflow.com/comment/90903739
has comment: http://stackoverflow.com/comment/90903706
tagged with: python
type: AnsweredQuestion
has body: So imagine two computers that I have full control on both, I will call them computer A and computer B. On computer A there is a python script that is running in the background and has multiple functions, one of them being able to create and show a message box: (this is just an example) def msg_box(text,title): MessageBox = ctypes.windll.user32.MessageBoxW MessageBox(None, text, title, 0) What I want to do, is to access the functions of the script running on computer A from computer B, in the case of the msg_box function, I want to be able to call it on the computer B with any parameters that I want, and it will get executed on computer A. I am a beginner and I don't know how to do this link between the computers, I remind you that I have full control over both of them and they are connected to my local network. Some have suggested me using a ssh server, can someone give me some ideas ?
has comment: http://stackoverflow.com/comment/90903733
score: 0
has answer: http://stackoverflow.com/a/51981230
has comment: http://stackoverflow.com/comment/90903720
linked to: http://stackoverflow.com/q/14659789
type: Question
has title: Remote control functions of a python script running on another computer
accepted answer: http://stackoverflow.com/a/51981230

http://stackoverflow.com/q/52104648
downvote count: 0
type: Question
has body: I have a question to the AUTH_USER_MODEL in Django: https://docs.djangoproject.com/en/dev/ref/settings/#auth-user-model The default value is auth.User. However, the actual model is in auth.models.User. How does Django find the correct class? I am asking because when I usually use models in Django, I have to write from myapp.models import MyModel. So, why do I not need models in auth.User for AUTH_USER_MODEL? Can some explain me that or show the code that uses it?
upvote count: 3
answer count: 1
has title: Django: How does it find the User model?
favorite count: 0
has answer: http://stackoverflow.com/a/52104694
tagged with: django
accepted answer: http://stackoverflow.com/a/52104694
tagged with: python
type: AnsweredQuestion
score: 3

http://stackoverflow.com/q/52048125
has answer: http://stackoverflow.com/a/52048139
accepted answer: http://stackoverflow.com/a/52048139
tagged with: python-3.x
linked to: http://stackoverflow.com/q/3277503
tagged with: python
possible better answer: http://stackoverflow.com/a/52048138
has title: How to read a specific range of lines in an external file in python?
type: AnsweredQuestion
score: 3
has answer: http://stackoverflow.com/a/52048138
downvote count: 0
type: Question
has answer: http://stackoverflow.com/a/52048179
favorite count: 0
has body: Lets say you have a python file with 50 lines of code in it, and you want to read a specific range lines into a list. If you want to read ALL the lines in the file, you can just use the code from this answer: with open('yourfile.py') as f: content = f.readlines() print(content) But what if you want to read a specific range of lines, like reading line 23-27? I tried this, but it doesn't work: f.readlines(23:27)
upvote count: 3
answer count: 3

wsgi
type: Tag
tags question: http://stackoverflow.com/q/51995926
tag name: wsgi

http://stackoverflow.com/comment/90979082
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51998266
has text: Hi Nihal, I would like to use the .xlsx format
score: 0

http://stackoverflow.com/q/52022570
has comment: http://stackoverflow.com/comment/91002406
tagged with: pandas
has answer: http://stackoverflow.com/a/52026145
answer count: 1
has title: Adding a column to dataframe that calculates the mean across rows-getting all 'NaNs' returned
favorite count: 0
has comment: http://stackoverflow.com/comment/90998221
tagged with: python
score: 2
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/52026145
upvote count: 3
has body: I am trying to add a column to my data frame that calculates the average across rows of a subset of my data frame columns. I am trying this (Min1-Min5 are the names of the subset of columns I want the average for): df_temps['MinAvg'] = df_temps'Min1', 'Min2', 'Min3', 'Min4', 'Min5'.mean(axis=1) but it returns a column called MinAvg with all NaN values. There are no NA or missing data points in my data frame. Updated: All Min Variables were string type pulled from an API. Therefore, I needed to change it from a string to a float with the (.astype(float)) per the feedback below! Thanks for the help!
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/91002374
tagged with: mean
tagged with: dataframe
has comment: http://stackoverflow.com/comment/90995488

http://stackoverflow.com/comment/91094215
type: Comment
has text: @MarkK Well, I just wanted to show how it can be done with a single `re.findall` call, and someone disliked my idea. Anyway, I was going to add the second solution, just some people tend to complain about non-regex answers for regex questions. And vice versa :) We cannot please everyone on SO.
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/52072046

http://stackoverflow.com/comment/91152554
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/52100621
has text: In SO you should ask a question by POST, so Ask Question says, do not say Ask Questions, please edit your question and remove the questions, those questions you should do in other POST.
score: 0

http://stackoverflow.com/comment/91110787
has text: https://stackoverflow.com/questions/11984386/expand-and-flatten-a-ragged-nested-list
type: AnswerComment
comment on: http://stackoverflow.com/a/52080368
score: 0
type: Comment

http://stackoverflow.com/comment/91172981
score: 0
type: Comment
type: QuestionComment
has text: Tried it, different result from browser and scraping.
comment on: http://stackoverflow.com/q/52109321

http://stackoverflow.com/a/51981230
type: Answer
has comment: http://stackoverflow.com/comment/91264145
answers question: http://stackoverflow.com/q/51976675
has comment: http://stackoverflow.com/comment/91298420
accepted answer of: http://stackoverflow.com/q/51976675
has comment: http://stackoverflow.com/comment/91263454
score: 0
has body: This sounds like a job for the Pyro4 package. Here's an example based on their "Simple Example", with some extra code to start the nameserver automatically and listen over a network. First use this command on each machine to install Pyro4: pip install pyro4 On the server, save this script as server.py and then run it in a terminal window via python server.py: # saved as server.py import Pyro4, Pyro4.naming import socket, threading # Define an object that will be accessible over the network. # This is where all your code should go... @Pyro4.expose class MessageServer(object): def show_message(self, msg): print("Message received: {}".format(msg)) # Start a Pyro nameserver and daemon (server process) that are accessible # over the network. This has security risks; see # https://pyro4.readthedocs.io/en/stable/security.html hostname = socket.gethostname() ns_thread = threading.Thread( target=Pyro4.naming.startNSloop, kwargs={'host': hostname} ) ns_thread.daemon = True # automatically exit when main program finishes ns_thread.start() main_daemon = Pyro4.Daemon(host=hostname) # find the name server ns = Pyro4.locateNS() # register the message server as a Pyro object main_daemon_uri = main_daemon.register(MessageServer) # register a name for the object in the name server ns.register("example.message", main_daemon_uri) # start the event loop of the main_daemon to wait for calls print("Message server ready.") main_daemon.requestLoop() On the client, save this as client.py and run it with python client.py: # saved as client.py import Pyro4 import sys print("What is your message?") msg = sys.stdin.readline().strip() # lookup object uri on name server and create a proxy for it message_server = Pyro4.Proxy("PYRONAME:example.message") # call method on remote object message_server.show_message(msg) Note that setting up Pyro to listen over your network is a security risk. So you should read their section on security before you go ahead with this. But this should be enough to get you…
type: AcceptedAnswer

cryptography
tag name: cryptography
type: Tag
tags question: http://stackoverflow.com/q/51978463
tags question: http://stackoverflow.com/q/52028845
tags question: http://stackoverflow.com/q/52030155
tags question: http://stackoverflow.com/q/52106332

http://stackoverflow.com/comment/90892951
comment on: http://stackoverflow.com/q/51970145
type: Comment
has text: A common idea when inserting multiple items in a list is to start with the largest index and work back. That way you don't have adjust the indexing for growth. But adjusting for growth isn't hard; it's a simple arithmetic step.
type: QuestionComment
score: 0

http://stackoverflow.com/comment/91077163
has text: @NaN yes it has to be a odd block.
score: 0
comment on: http://stackoverflow.com/q/52049865
type: QuestionComment
type: Comment

google-translation-api
tags question: http://stackoverflow.com/q/51976180
type: Tag
tag name: google-translation-api

http://stackoverflow.com/a/52064059
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/91123764
has comment: http://stackoverflow.com/comment/91079010
type: Answer
has comment: http://stackoverflow.com/comment/91079640
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/91078617
has comment: http://stackoverflow.com/comment/91083393
accepted answer of: http://stackoverflow.com/q/52063733
has body: Here's a solution that can handle text-input with words of arbitrary length: from collections import Counter your_text = input('input characters') with open('P:/words.txt', 'r') as infile: file_text = infile.read() old_words = { str(sorted(Counter(w).items())): w for w in file_text.split() } for w in your_text.split(): i = str(sorted(Counter(w).items())) if i in old_words: print(old_words[i]) It doesn't need to check each permutation of input characters; it matches when the count of letters in an input word is the same as one from your input file. This was my 1st solution and works, but do not input a string with a word longer than 10 chars or it will crash your computer: from itertools import permutations perms_list = [] perms = [] matches = [] your_chars = input("input characters") your_words = your_chars.split() for word in your_words: perms_list.append([i for i in permutations(word)]) for word in perms_list: for perm in word: perms.append(''.join(list(perm))) with open('P:/words.txt', 'r') as comparefile: file_contents = comparefile.read().split() for permutation in perms: if permutation in file_contents: matches.append(permutation) print(matches)
answers question: http://stackoverflow.com/q/52063733
upvote count: 1

http://stackoverflow.com/comment/90873708
type: Comment
comment on: http://stackoverflow.com/q/51961652
score: 0
type: QuestionComment
has text: Hi Val! Here is the elasticsearch error log in the link. https://pastebin.com/iT2de2rc

http://stackoverflow.com/a/75910621
score: 0
answers question: http://stackoverflow.com/q/52009351
has comment: http://stackoverflow.com/comment/133967684
has body: from selenium import webdriver from selenium.webdriver.chrome.options import Options o = Options() o.add_argument('--no-sandbox') driver = webdriver.Chrome(executable_path=r"chromedriver.exe",chrome_options=o) It worked for me.
type: Answer

http://stackoverflow.com/comment/90939094
has text: are you looking for a way to run pylint in the browser, or on the server, ace doesn't have builtin support for any of this?
comment on: http://stackoverflow.com/q/51986039
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/90990424
type: Comment
has text: Possible duplicate: https://stackoverflow.com/questions/42287579/how-to-define-basic-python-structures/42287634#42287634 although it didn't include 3.7 data classes...
comment on: http://stackoverflow.com/q/52019921
score: 0
type: QuestionComment

http://stackoverflow.com/q/52082406
answer count: 1
has comment: http://stackoverflow.com/comment/91115540
favorite count: 0
accepted answer: http://stackoverflow.com/a/52082960
has body: I'm trying to port some Python code to C# and in the code there is a part where it encrypts a string with AES with the following key: '\xd7\xdf\xca2\xd0Vhu\xeb\x06\xa0\xba\n\xa2\x07O\xc1\x8b\xcf\x8f2&amp;t\xc0\x92\xc4\xa5\x0b>\xb4\xe7\xbc' This key is 32 bytes in Python, but the problem is that in C# it is 30 bytes when I convert that string (Encoding.Default.GetBytes), so I can't generate the AES key. Why is the length of the key 32 in Python and the byte array length is 30 in C#? Converting the key to bytes array: byte[] key = Encoding.Default.GetBytes("\xd7\xdf\xca2\xd0Vhu\xeb\x06\xa0\xba\n\xa2\x07O\xc1\x8b\xcf\x8f2&amp;t\xc0\x92\xc4\xa5\x0b&gt;\xb4\xe7\xbc"); Getting invalid key size for algorithm exception (because it's 30 bytes and not 32): byte[] encrypted; byte[] iv; using (Aes aesAlg = Aes.Create()) { aesAlg.Key = key; aesAlg.GenerateIV(); iv = aesAlg.IV; aesAlg.Mode = CipherMode.CBC; var encryptor = aesAlg.CreateEncryptor(aesAlg.Key, iv); using (var msEncrypt = new MemoryStream()) { using (var csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write)) { using (var swEncrypt = new StreamWriter(csEncrypt)) { swEncrypt.Write("test"); } encrypted = msEncrypt.ToArray(); } } }
tagged with: byte
tagged with: python
has title: C# byte array length inferior to python
has answer: http://stackoverflow.com/a/52082960
has comment: http://stackoverflow.com/comment/91115450
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91115190
type: Question
tagged with: c#
score: -2
has comment: http://stackoverflow.com/comment/91115711
downvote count: 3
upvote count: 1

http://stackoverflow.com/q/52102843
has title: Selenium: Why does initializing the Firefox webdriver from Python trigger a Windows Firewall alert?
has answer: http://stackoverflow.com/a/52107370
score: 1
tagged with: selenium
upvote count: 1
type: Question
has body: Python: 2.7.9 Selenium 2.53.6 We drive Selenium from Python, and it works great. Issue is that when we hit this line: driver = webdrive.Firefox() The Windows Firewall pops up, asking us to give permission to python.exe We notice that we can ignore the firewall prompt, and everything seems to work OK. Can anyone tell us: Why something in python land (selenium specifically) is opening a port The port open that triggers the firewall prompt is clearly NOT required, (since we can ignore the prompt, and web drier still works). What is the explanation for this? How we can , in code, suppress the firewall prompt? (e.g. by perhaps only allowing the engine to bind to 127.0.0.1 rather than the device IP?)
answer count: 1
downvote count: 0
favorite count: 0
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/comment/91288949
comment on: http://stackoverflow.com/a/52168991
type: AnswerComment
score: 0
type: Comment
has text: I will give a look into it, might prove to be useful once the tasks get harder. Thank you.

http://stackoverflow.com/comment/90879673
score: 0
type: Comment
type: QuestionComment
has text: @sers Only the one coming from 2017 year
comment on: http://stackoverflow.com/q/51964400

http://stackoverflow.com/q/52048296
answer count: 1
has title: to use instance attributes in another python class
downvote count: 0
has body: class User: def __init__(self, name, age, country, title, ph): self.name = name self.age = age self.country = country self.title = title self.ph = ph class Programmer(User): def __init__(self, address): self.address=address def do_something(self): print self.name print self.age print self.title print self.country + " " + self.ph brian = User("brian", "28", "US", "Mr", "123556") diana = Programmer("newark", brian) diana.do_something() Error: Traceback (most recent call last): File "C:/Users/esurega/Desktop/NPI_TA/enm2enm/test/test.py", line 24, in &lt;module&gt; diana = Programmer("newark", brian) TypeError: __init__() takes exactly 2 arguments (3 given)
favorite count: 0
has comment: http://stackoverflow.com/comment/91047515
has comment: http://stackoverflow.com/comment/91047391
tagged with: python
has answer: http://stackoverflow.com/a/52049120
has comment: http://stackoverflow.com/comment/91048053
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91050667
has comment: http://stackoverflow.com/comment/91047439
accepted answer: http://stackoverflow.com/a/52049120
upvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/91047479
score: 1
has comment: http://stackoverflow.com/comment/91049215
has comment: http://stackoverflow.com/comment/91047437

http://stackoverflow.com/q/52011259
tagged with: privoxy
has comment: http://stackoverflow.com/comment/90976538
type: UnansweredQuestion
type: Question
tagged with: tor
has comment: http://stackoverflow.com/comment/91011468
has title: Requesting API Content on Localhost while using Tor + Privoxy
answer count: 1
has answer: http://stackoverflow.com/a/52045702
has comment: http://stackoverflow.com/comment/91011942
tagged with: proxy
score: 0
has body: I'm using Tor, Privoxy, and Python to anonymously crawl sources on the web. Tor is configured with ControlPort 9051, while Privoxy is configured with forward-socks5 / localhost:9050 . My scripts are working flawlessly, except when I request an API resource that I have running on 8000 on the same machine. If I hit the API via urllib2 setup with the proxy, I get an empty string response. If I hit the API using a new, non-proxy instance of urllib2, I get a HTTP Error 503: Forwarding failure. I'm sure that if I open 8000 to the world I'll be able to access the port through the proxy. However, there must be a better way to access the resource on localhost. Curious how people deal with this.
tagged with: python

http://stackoverflow.com/q/52064450
upvote count: 6
favorite count: 0
tagged with: tensorflow-layers
possible better answer: http://stackoverflow.com/a/52505044
has body: I'm struggling to use Tensorflow's pruning library and haven't found many helpful examples so I'm looking for help to prune a simple model trained on the MNIST dataset. If anyone can either help fix my attempt or provide an example of how to use the library on MNIST I would be very grateful. The first half of my code is pretty standard except my model has 2 hidden layers 300 units wide using layers.masked_fully_connected for pruning. import tensorflow as tf from tensorflow.contrib.model_pruning.python import pruning from tensorflow.contrib.model_pruning.python.layers import layers from tensorflow.examples.tutorials.mnist import input_data # Import dataset mnist = input_data.read_data_sets('MNIST_data', one_hot=True) # Define Placeholders image = tf.placeholder(tf.float32, [None, 784]) label = tf.placeholder(tf.float32, [None, 10]) # Define the model layer1 = layers.masked_fully_connected(image, 300) layer2 = layers.masked_fully_connected(layer1, 300) logits = tf.contrib.layers.fully_connected(layer2, 10, tf.nn.relu) # Loss function loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits_v2(logits=logits, labels=label)) # Training op train_op = tf.train.AdamOptimizer(learning_rate=1e-4).minimize(loss) # Accuracy ops correct_prediction = tf.equal(tf.argmax(logits, 1), tf.argmax(label, 1)) accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) Then I attempt to define the necessary pruning operations but I get an error. ############ Pruning Operations ############## # Create global step variable global_step = tf.contrib.framework.get_or_create_global_step() # Create a pruning object using the pruning specification pruning_hparams = pruning.get_pruning_hparams() p = pruning.Pruning(pruning_hparams, global_step=global_step) # Mask Update op mask_update_op = p.conditional_mask_update_op() # Set up the specification for model pruning prune_train = tf.contrib.model_pruning.train(train_op=train_op, logdir=None, mask_update_op=mask_update_op) Error on this l…
has answer: http://stackoverflow.com/a/52414196
accepted answer: http://stackoverflow.com/a/52414196
score: 6
tagged with: python
type: AnsweredQuestion
downvote count: 0
has answer: http://stackoverflow.com/a/52505044
tagged with: tensorflow
type: Question
answer count: 2
has title: How to use tf.contrib.model_pruning on MNIST?

http://stackoverflow.com/comment/90938733
type: Comment
has text: Thank you for your answer. Unfortunately I think there is a syntax error, since trying your solution, I get the error.
comment on: http://stackoverflow.com/a/51994202
type: AnswerComment
score: 0

http://stackoverflow.com/q/52036014
has comment: http://stackoverflow.com/comment/91022250
has comment: http://stackoverflow.com/comment/91022381
has comment: http://stackoverflow.com/comment/91022200
has body: I'm trying to run a function called password() with argument "t" on pressing a button in Tkinter. Problem is that this gives me a TypeError even though the code seems alright. self.Button5.configure(command=lambda t='restart': password(t)) Error: TypeError: 'str' object is not callable (here is a link to whole code if necessary, error is on line 372: https://codeshare.io/G8VW6A)
has title: Tkinter button linked to function with argument gives TypeError
tagged with: typeerror
downvote count: 2
answer count: 1
has comment: http://stackoverflow.com/comment/91022353
has comment: http://stackoverflow.com/comment/91022166
tagged with: string
favorite count: 0
upvote count: 0
tagged with: python
tagged with: lambda
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91022113
has answer: http://stackoverflow.com/a/52036095
accepted answer: http://stackoverflow.com/a/52036095
type: Question
score: -2

http://stackoverflow.com/comment/90952008
score: 1
comment on: http://stackoverflow.com/q/52001241
has text: @jezrael, I think I got it. I was kind of experimenting and have passed a list to `pd.MultiIndex.levels`. Do it, you will start encountering the error.
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52009624
favorite count: 0
has comment: http://stackoverflow.com/comment/90970049
has answer: http://stackoverflow.com/a/52009670
tagged with: python
upvote count: 4
type: AnsweredQuestion
downvote count: 0
has comment: http://stackoverflow.com/comment/90970062
has title: Doubley unpacking an iterable in Python 3 removes the iterable?
type: Question
linked to: http://stackoverflow.com/q/25336726
score: 4
possible better answer: http://stackoverflow.com/a/52009654
has answer: http://stackoverflow.com/a/52009654
has answer: http://stackoverflow.com/a/52009659
accepted answer: http://stackoverflow.com/a/52009659
answer count: 3
has body: lst = iter([1, 2, 3]) print([*lst]) # &gt;&gt;&gt; [1, 2, 3] print([*lst]) # &gt;&gt;&gt; [] Is this expected behaviour for unpacking? I would've assumed the original data wouldn't be modified on unpacking and a copy is simply made? EDIT: If so, what is the reasoning behind it?

http://stackoverflow.com/a/52115297
has comment: http://stackoverflow.com/comment/91279333
has body: When you are creating your project you can add the command to upload and reload the python container under build->execute shell script.
type: Answer
answers question: http://stackoverflow.com/q/52096438
score: 0

http://stackoverflow.com/q/52030839
has answer: http://stackoverflow.com/a/52033475
has body: I have had it up to here with Python's import system... thought I'd finally got something reliable and then the inexplicable happens! This is the directory structure of my application: / - my-application/ - subpackage/ - __init__.py - my_module.py - __init__.py - tests/ - subpackage/ - __init__.py - test_my_module.py - __init__.py - conftest.py - run.py - spark.py I run all my tests through tests/run.py, which looks like the following (in an attempt to resolve all the import problems): import os import pytest import sys rootdir = os.path.abspath(os.path.join(os.path.dirname(__file__), "..")) sys.path.insert(0, os.path.abspath(os.path.join(rootdir, "my-application"))) sys.exit(pytest.main([os.path.join(rootdir, "tests")])) This worked like an absolute charm, until I made one modification to the file /my-application/subpackage/my-module.py - I added a local function call. So e.g. my_module.py: def foo(): pass def run_my_module(): def bar(): foo() &lt;---- Added this line bar() print("Ran") UPDATE: THIS works fine: def foo(): pass def run_my_module(): def bar(): pass foo() bar() print("Ran") As soon as I added that local function call, the tests stop working, with the error No module named "subpackage". The test_my_module.py looks like this (basically): from subpackage.my_module import run_my_module def basic_test(): run_my_module() Note that in test_my_module.py I am using subpackage as the first part of my import statement, because I am using the run.py file that sets my-application as a system path. If I change the import to start with my_application I get the same error referring to my_application.py. I am still learning python, so suggest any change to my application structure you like. I can't believe the hassle of this import system - I do feel like I'm missing something basic here... Thank you in advance!
downvote count: 0
answer count: 1
favorite count: 0
tagged with: python
has comment: http://stackoverflow.com/comment/91016733
score: 2
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/91016366
has comment: http://stackoverflow.com/comment/91013556
upvote count: 2
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91016401
has comment: http://stackoverflow.com/comment/91166058
type: Question
has title: Python calling local function in main code breaks imports in tests?
has comment: http://stackoverflow.com/comment/91016417
tagged with: pytest

http://stackoverflow.com/comment/91135427
type: QuestionComment
score: 0
has text: @JosephSh Becuase you should also delete the `if` condition like I showed
comment on: http://stackoverflow.com/q/52092566
type: Comment

http://stackoverflow.com/comment/90960102
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/52005234
has text: Ah, I totally forgot about that site. My tea hasn't kicked in yet :) Should I close this question and move it?
type: Comment

http://stackoverflow.com/comment/90931949
type: Comment
score: 0
comment on: http://stackoverflow.com/q/51991114
has text: @klanmiko not a duplicate, need to pass in a list of URLs not just one
type: QuestionComment

http://stackoverflow.com/comment/91162040
type: Comment
type: QuestionComment
has text: What version of pandas do you have, and what is the value you are trying to fill the missing values with?
comment on: http://stackoverflow.com/q/52105455
score: 0

http://stackoverflow.com/q/52067847
tagged with: unit-testing
type: Question
tagged with: mocking
tagged with: python-2.7
answer count: 1
downvote count: 0
has title: Mock method in test file from different directory python
favorite count: 0
has answer: http://stackoverflow.com/a/52068243
upvote count: 2
type: UnansweredQuestion
has body: I am attempting to mock a method and running into issues with mock actually overwriting it. app/tests/test_file.py &lt;- contains the the unit test, currently using: @mock.patch('app.method', return_value='foo') def test(self, thing): ... do some stuff with app/main/server.py and get its response, assert a few values ... assert 'foo' is in return value of some stuff The method being mocked is being called by another file that server.py is calling. app/main/server.py &lt;- what the unit test is actually interacting with app/main/route.py &lt;- where method being mocked is called app/main/thing.py &lt;- contains method to be mocked This is with python 2.7 and each package has an init file. The parent folder (app) contains imports for every class and method. I've tried app.method which doesn't give problems, but doesnt work. I've tried thing.method, throws an error. I've tried app.main.thing.method which does nothing. I've had success in this same test suite mocking an object and one of its methods, but that object is created and used directly in the server.py file. I'm wondering if it's because the method being called is so far down the chain. Mocking is pretty magical to me, especially in Python.
tagged with: python
score: 2
has comment: http://stackoverflow.com/comment/91086150

http://stackoverflow.com/comment/91150970
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52085054
score: 0
has text: Where does it say so?

http://stackoverflow.com/comment/91105644
has text: Welcome to Stack! As a general rule when asking questions is to provide as much detail as possible. Including any code that you may have written and any other information such as the html for this particular problem. Also! you should try searching stack overflow for similar questions that have already been answered such as here https://stackoverflow.com/questions/42184367/parse-html-table-data-with-beautifulsoup-into-a-dict
type: Comment
comment on: http://stackoverflow.com/q/52077888
score: 3
type: QuestionComment

http://stackoverflow.com/q/52098163
favorite count: 0
type: UnansweredQuestion
upvote count: 1
tagged with: python
score: 1
tagged with: copytree
type: Question
has body: I need to copy the files from a directory with patterns. Since I did as below, from fnmatch import fnmatch, filter from os.path import isdir, join from shutil import copytree, ignore_patterns def include_patterns(*patterns): def _ignore_patterns(path, names): keep = set(name for pattern in patterns for name in filter(names, pattern)) ignore = set(name for name in names if name not in keep and not isdir(join(path, name))) return ignore return _ignore_patterns src_directory = r'SOURCH_PATH' dst_directory = r'DST_PATH' ignored_directory = r'DST_PATH2' copytree(src_directory, ignored_directory,ignore=ignore_patterns('*.bat')) copytree(src_directory, dst_directory,ignore=include_patterns('*.xls')) Copytree will raise error if the destination directory already exist. So I need to perform copy something like this copytree(src_directory, ignored_directory,ignore=ignore_patterns('*.bat'), ignore=include_patterns('*.xls')) or is there any params to perform the copy operation with both include pattern &amp; exclude pattern? How to achieve this?
downvote count: 0
answer count: 1
has answer: http://stackoverflow.com/a/52098307
has comment: http://stackoverflow.com/comment/132242666
has title: Is it possible copy the files with include and exclude pattern using python?

http://stackoverflow.com/comment/90887907
has text: Note actually. How can I apply shift?
score: 0
comment on: http://stackoverflow.com/q/51968722
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91087884
type: QuestionComment
comment on: http://stackoverflow.com/q/52055072
has text: I have add the line information already.
score: 0
type: Comment

http://stackoverflow.com/q/51966863
tagged with: view
downvote count: 0
score: 1
favorite count: 0
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/90883657
has body: I've read through several other questions, yet what I was looking for wasn't there. I want to count how many times the user has gone through the ToPost/to_post.html section. Delayed redirecting works, but incrementing number of visits doesn't: post.visit_num += 1 I have a view whose template redirects after a second: def ToPost(request, pk): post = Post.objects.get(pk=pk) post.visit_num += 1 args = {'post': post} return render(request, 'posts/to_post.html', args) The pk is in the URL: url(r'^(?P&lt;pk&gt;\d+)/to-post/$', views.ToPost, name='to_post'), Template to_post.html: {% extends 'base.html' %} {% block head %} &lt;meta http-equiv="refresh" content="1;url={% url 'home_space:view_post' pk=post.pk %}"&gt; {% endblock %} {% block body %} &lt;div class="container"&gt; &lt;h2&gt; To post {{ post.pk }}... &lt;/h2&gt; &lt;/div&gt; {% endblock %} The model of Post: class Post(models.Model): title = models.CharField(max_length=128, verbose_name='Title') body = models.CharField(max_length=500, verbose_name='Description') user = models.ForeignKey(User, on_delete=models.CASCADE) visit_num = models.PositiveIntegerField(default=0) def __str__(self): return self.title
has answer: http://stackoverflow.com/a/51967025
accepted answer: http://stackoverflow.com/a/51967025
upvote count: 1
possible better answer: http://stackoverflow.com/a/51966957
has answer: http://stackoverflow.com/a/51966957
tagged with: http-redirect
tagged with: django
tagged with: count
has title: How do I count visits of page in Django? (through redirecting)
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/a/52025610
downvote count: 0
type: Answer
has body: Convert them to lists: &gt;&gt;&gt; list(zip(a,b)) [(0, 0), (1, 1), (2, 2)] The reason you need to do this is because zip() returns an iterator (something you can call next() on) and range() returns an iterable (something you can call iter() on). Both of which are not evaluated before they are needed to be (they are "lazy" in this sense) so they do not display all their contents when assigned to variables. However, when you convert them into lists, they are iterated over and evaluated so you can see their contents. The same is true when you create your own iterable or iterator: class my_iterator(): def __init__(self): self.x = 0 def __iter__(self): return self def __next__(self): self.x += 1 if self.x &lt; 10: return self.x raise StopIteration which then performs in a very similar fashion to zip instances: &gt;&gt;&gt; i &lt;__main__.my_iterator object at 0x7f219d303518&gt; &gt;&gt;&gt; list(i) [1, 2, 3, 4, 5, 6, 7, 8, 9]
has comment: http://stackoverflow.com/comment/91011849
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/52025596
has comment: http://stackoverflow.com/comment/91011506

http://stackoverflow.com/q/52024350
type: Question
has body: I'm trying to write my own layer in Keras where I need to multiply an input tensor by a weight tensor with exponential decay of a trainable value. I was planning on creating the value as a weight then "somehow" expand it. In python, I will just do this: d = 0.9 window = 6 w = np.array([pow(d, window-j) for j in range(window)]) w = w / w.sum() Output: In [63]: w Out[63]: array([0.12602255, 0.14002506, 0.1555834 , 0.17287044, 0.19207827, 0.21342029]) I can see there is tf.while_loop which might help, but how do I call tensorflow from Keras?
tagged with: keras
score: 0
answer count: 1
has answer: http://stackoverflow.com/a/52026015
type: UnansweredQuestion
tagged with: python
has title: Exponential weight tensor in Keras
tagged with: tensorflow

python-itertools
tags question: http://stackoverflow.com/q/52024670
tags question: http://stackoverflow.com/q/51991188
tags question: http://stackoverflow.com/q/52101264
tag name: python-itertools
type: Tag
tags question: http://stackoverflow.com/q/52034239
tags question: http://stackoverflow.com/q/51978080
tags question: http://stackoverflow.com/q/52086142
tags question: http://stackoverflow.com/q/52017524
tags question: http://stackoverflow.com/q/52007861

http://stackoverflow.com/comment/91080650
type: AnswerComment
type: Comment
score: 0
comment on: http://stackoverflow.com/a/52065018
has text: I know, but how to get this `n`?

http://stackoverflow.com/a/52000293
score: 2
answers question: http://stackoverflow.com/q/52000252
upvote count: 2
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52000252
type: Answer
has body: You can use isinstance Ex: a = {"foo":1} b = [{"foo":2}] c = [{"foo":3}, {"foo":4}] l = [a, b, c] for i in l: if isinstance(i, dict): #Check if dict object print(i["foo"]) elif isinstance(i, list): #Check if list object for j in i: print(j["foo"]) Output: 1 2 3 4

http://stackoverflow.com/q/52001131
answer count: 2
tagged with: python
score: -1
has answer: http://stackoverflow.com/a/52001395
has answer: http://stackoverflow.com/a/52001303
downvote count: 1
type: UnansweredQuestion
upvote count: 0
has title: Alternates to using a Config File for holding server connection details
tagged with: config
favorite count: 0
has body: I am currently creating a test framework for the Automated testing of a number of backend components. I am writing the framework in Python. Up until now I have been holding the connection details (IP Address, Port, username, password etc) in a config file and retrieving the details from here these details are fluid and can change depending from test run to test run dependant on what is being tested and where. However this config file is now becoming large and difficult to manage. Before I start splitting the config file into smaller more manageable files which are easier to maintain I wanted to know if there is an alternative to storing this kind of information that I could try.
type: Question

http://stackoverflow.com/comment/91076929
score: 1
type: AnswerComment
has text: @blhsing +1, very nice as you removed an entire loop from my solution!
comment on: http://stackoverflow.com/a/52061896
type: Comment

http://stackoverflow.com/comment/90865585
score: 0
type: AnswerComment
has text: Got it. Thanks!
type: Comment
comment on: http://stackoverflow.com/a/51957464

http://stackoverflow.com/comment/91015116
score: 0
type: Comment
has text: Did you mean `a = map(set, a)` because currently `s = map(set, a)` is not being used, you are redefining `s` in the comprehension and still using `a`. Note: it works because `issubset()` will take any iterable (this doesn't happen with `<=` set operator).
comment on: http://stackoverflow.com/a/52032414
type: AnswerComment

http://stackoverflow.com/a/52034198
has comment: http://stackoverflow.com/comment/91019094
has comment: http://stackoverflow.com/comment/91019020
has body: from datetime import datetime date_as_dt_object = datetime.strptime(dt, '%a %b %d %H:%M:%S %z %Y') You can use date_as_dt_object in a raw query or an ORM. If used in a raw query pass it as a string like: query = "select * from table where date &gt;" + str(date_as_dt_object) Check out this list for Python's strftime directives. http://strftime.org/
has comment: http://stackoverflow.com/comment/91018660
answers question: http://stackoverflow.com/q/52033958
has comment: http://stackoverflow.com/comment/91018523
score: 0
type: Answer

http://stackoverflow.com/comment/91175768
type: QuestionComment
comment on: http://stackoverflow.com/q/52112414
has text: provide complete error message
score: 0
type: Comment

recaptcha
tag name: recaptcha
tags question: http://stackoverflow.com/q/51970555
type: Tag

http://stackoverflow.com/comment/91155407
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/52099923
has text: sorry i think i haven't make my question clear, already edited

http://stackoverflow.com/comment/90905554
type: AnswerComment
comment on: http://stackoverflow.com/a/51976722
type: Comment
has text: why 'suspiciously' ?
score: 0

axes
tag name: axes
type: Tag
tags question: http://stackoverflow.com/q/51985557

http://stackoverflow.com/comment/91016366
type: QuestionComment
comment on: http://stackoverflow.com/q/52030839
score: 0
has text: That made it fail quicker, now with the error "No module named tests.subpackage.subpackage".
type: Comment

http://stackoverflow.com/comment/90900501
score: 0
type: AnswerComment
has text: `multi_dot` isn't going to provide any advantage in this case, though. It still calls `dot` repeatedly at Python level. It tries to pick an optimal order in which to do so, but all arrays involved have identical shape in this case, so there is no advantage to be gained.
type: Comment
comment on: http://stackoverflow.com/a/51974896

http://stackoverflow.com/comment/91086661
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52055442
has text: Have you read this https://stackoverflow.com/questions/47769818/why-is-my-nltk-function-slow-when-processing-the-dataframe ?

http://stackoverflow.com/comment/128640978
type: Comment
has text: its 'Shift+F10' now for running the code
type: AnswerComment
comment on: http://stackoverflow.com/a/52931131
score: 0

http://stackoverflow.com/comment/91152721
type: QuestionComment
comment on: http://stackoverflow.com/q/52100914
score: 0
has text: How are you planning on passing the username? And they would be creating a password not retrieving a password correct?
type: Comment

http://stackoverflow.com/a/70018619
score: 1
has body: This question has been answered here : Image ignored in PDF rendering with jinja2 and weasyprint, you need to add base_url='.' here : HTML(string=html_out, base_url='.').write_pdf(outfile)
answers question: http://stackoverflow.com/q/52106531
accepted answer of: http://stackoverflow.com/q/52106531
upvote count: 1
type: AcceptedAnswer
type: Answer
downvote count: 0

http://stackoverflow.com/comment/90968585
comment on: http://stackoverflow.com/a/52008198
type: Comment
score: 0
type: AnswerComment
has text: Unfortunately, it run for the the first 17403 records then stopped: `raise UnexpectedSymbol(symbol, pos) ijson.backends.python.UnexpectedSymbol: Unexpected symbol 'S' at 56649111`. Do you have any clue how to solve the issue? or can you provide an edited answer with another library that can help me read array of json objects stored in a file. The file size is around 3 GB.

http://stackoverflow.com/comment/91087506
has text: Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/178982/discussion-between-machetazo-and-jaime-lopez).
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52060332

http://stackoverflow.com/comment/91072351
comment on: http://stackoverflow.com/q/52060925
score: 0
type: Comment
type: QuestionComment
has text: Your question doesn't include enough detail. Usually we request that you create a [mcve] so that we can see what you've tried. Otherwise, the way your question is written it is simply too broad.

http://stackoverflow.com/a/51988499
upvote count: 1
has comment: http://stackoverflow.com/comment/90927058
answers question: http://stackoverflow.com/q/51988458
type: Answer
has comment: http://stackoverflow.com/comment/90927409
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/90927550
has comment: http://stackoverflow.com/comment/90927286
has body: Basically what you are doing here shall be done via the __new__ which serve as constructor. class testclass: def __init__(self, x): self.x = x def __new__(cls, *args, **kwargs): instance = super(testclass, cls).__new__(cls, *args, **kwargs) instance.outer_adjust(args[0]) return instance def outer_adjust(self, x): return self.inner_adjust(x) def inner_adjust(self, x): self.x = x + 1 test_instance = testclass(4)

http://stackoverflow.com/q/52106580
tagged with: python
has title: Extract value in dict
tagged with: dictionary
has answer: http://stackoverflow.com/a/52106606
tagged with: python-3.x
upvote count: 2
answer count: 2
has body: I have this dict: data = {'name':['Andrea', 'Luca'], 'age':['14', '15']} I write: for key, value in data.items(): print (key, value) here in this my results in (print(key, value)) are: name ['Andrea', 'Luca'] age ['14', '15'] I would like to extract this: name = Andrea name = Luca age = 14 age = 15 How can I do?
has answer: http://stackoverflow.com/a/52106612
score: 2
type: AnsweredQuestion
downvote count: 0
accepted answer: http://stackoverflow.com/a/52106612
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/52104143
possible better answer: http://stackoverflow.com/a/52106606

http://stackoverflow.com/comment/91131188
has text: What if you do `uptime 2>&1`?
comment on: http://stackoverflow.com/q/52089541
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/91106098
has text: Since dataframe is already sorted (assuming sorted by `ID`), I think only the first scenario is applicable.
type: Comment
comment on: http://stackoverflow.com/a/52078087
score: 1
type: AnswerComment

http://stackoverflow.com/q/52008765
score: 0
answer count: 2
accepted answer: http://stackoverflow.com/a/52008844
tagged with: web
has title: How to host a application made in Python plus Java
tagged with: python
tagged with: hosting
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52009260
type: Question
possible better answer: http://stackoverflow.com/a/52009260
tagged with: java
has body: I have a application built in python and java with front end html. In this there is a file upload field available where the user has to upload the text document. That document gets uploaded, processed using Java and python. So my query is where we can host this application which has java and python dependency?
has answer: http://stackoverflow.com/a/52008844

http://stackoverflow.com/a/52060584
has comment: http://stackoverflow.com/comment/91095265
has comment: http://stackoverflow.com/comment/91073020
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52060519
has body: You recieve a 301 because site is redirecting to https site. I don't know if using sockets is mandatory, but if not you can use requests, it's a easy-to-use lib for doing http requests: import requests req = requests.get("http://www.ncbi.nlm.nih.gov") html = req.text With this, the 301 is performed anyway but it's transparent. If you want to do it with sockets, you should add the "ssl layer" manually: import socket import ssl searcher = socket.socket(socket.AF_INET, socket.SOCK_STREAM) searcher.connect(("www.ncbi.nlm.nih.gov", 443)) searcher = ssl.wrap_socket(searcher, keyfile=None, certfile=None, server_side=False, cert_reqs=ssl.CERT_NONE, ssl_version=ssl.PROTOCOL_SSLv23) cmd = "GET https://www.ncbi.nlm.nih.gov/ HTTP/1.0\r\n\r\n".encode() searcher.send(cmd) while True: data = searcher.recv(512) if len(data) &lt; 1: break print(data.decode()) searcher.close()
has comment: http://stackoverflow.com/comment/91073437
type: Answer
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/52060519

http://stackoverflow.com/a/52014750
upvote count: 0
type: Answer
has body: When you use multiprocessing to open a second process, an entirely new instance of Python, with its own global state, is created. That global state is not shared, so changes made by child processes to global variables will be invisible to the parent process Use Multi-Threading instead of multi-Processing, if you wanna share variable between different processes. from threading import Thread import time varcol = {"list": []} def addelement(varcol): varcol["list"].append(1) addelement(varcol) print(len(varcol["list"])) def addelement_mp(varcol): varcol["list"].append(2) print(len(varcol["list"])) p = Thread(target=addelement_mp, args=(varcol,)) p.start() time.sleep(1) print(len(varcol["list"])) Or You can try using callback function from multiprocessing import Pool varcol = {"list": []} def addelement(varcol): varcol["list"].append(1) addelement(varcol) print(len(varcol["list"])) # Always print 1 def addelement_mp(varcol): varcol["list"].append(2) print(len(varcol["list"])) return varcol def confirm_len(varcol): print(len(varcol[0]["list"])) pool=Pool() # Will First Call addelement_mp and then call confirm_len with addelement_mp return value as its argv. r = pool.map_async(addelement_mp, (varcol,), callback=confirm_len) r.wait() if you don't wanna create a new callback function then you can do multiprocessing using multiprocessing.Pool.map print len(pool.map(addelement_mp, [varcol])[0]["list"])
has comment: http://stackoverflow.com/comment/90980082
downvote count: 1
has comment: http://stackoverflow.com/comment/90980204
answers question: http://stackoverflow.com/q/52014546
score: -1

http://stackoverflow.com/q/52105311
type: Question
has comment: http://stackoverflow.com/comment/91161758
tagged with: dataframe
score: 0
has comment: http://stackoverflow.com/comment/91193206
tagged with: pandas
answer count: 1
has title: Mark last set of items dataframe
has answer: http://stackoverflow.com/a/52136441
has body: Have a dataset of sales orders that are divided into product lots. Want to apply a flag to all the lots of the last order within a given year in Pandas / Python. Any advice? Currently have: masterDF['FLAG'] = masterDF.groupby(by=['id','year'],as_index=False)['ordernumber'].nth(-1) masterDF['LAST_ORDER_OF_QUARTER'] = np.where(masterDF['FLAG'].isnull(),0,1) But that only puts a 1 on the last row of the dataframe, not on all rows within that given order if that ordernumber appears on more than one row. To illustrate: ordernumber | lot | Last Order of Quarter ------------------------------------------------------ orderA | lot1 | 0 orderB | lot1 | 1 orderB | lot2 | 1 Any advice?
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/q/51960857
answer count: 7
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/90872394
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90872950
has comment: http://stackoverflow.com/comment/130333809
has body: a1=[1,2,3,4,5,6] b1=[[1,2,3], [4,5,6]] If using np.shape list a1 will return (6,) and b1 will return (2, 3). If Numpy is forbidden, how can I get the shape of list a1? I am mainly confused about how can I let the python program know a1 is only one dimension. Is there any good method?
tagged with: python
has answer: http://stackoverflow.com/a/67479754
has answer: http://stackoverflow.com/a/75279062
linked to: http://stackoverflow.com/q/10713004
has answer: http://stackoverflow.com/a/65860053
has answer: http://stackoverflow.com/a/51961584
has answer: http://stackoverflow.com/a/63650101
type: Question
has comment: http://stackoverflow.com/comment/90872093
has answer: http://stackoverflow.com/a/51961249
has comment: http://stackoverflow.com/comment/90872513
linked to: http://stackoverflow.com/q/17531796
has title: How can I get a list shape without using numpy?
upvote count: 29
score: 27
has comment: http://stackoverflow.com/comment/90872692
linked to: http://stackoverflow.com/q/3844801
has comment: http://stackoverflow.com/comment/90872130
downvote count: 2
has comment: http://stackoverflow.com/comment/90872727
has answer: http://stackoverflow.com/a/51961589

http://stackoverflow.com/q/52090587
has comment: http://stackoverflow.com/comment/91131106
favorite count: 0
tagged with: python
downvote count: 7
linked to: http://stackoverflow.com/q/2589479
has comment: http://stackoverflow.com/comment/91131425
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91131336
has comment: http://stackoverflow.com/comment/91131454
has title: Sorting a python list based on date?
has comment: http://stackoverflow.com/comment/91130955
has answer: http://stackoverflow.com/a/52090668
has comment: http://stackoverflow.com/comment/91131361
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/91131089
has body: I have a list of lists where each sub-list contains date values. How can I sort this based on Date? tList=[['xX0001', '10006', '102', '', '2018-02-02', 3233.9, 0.0, 36816.18, ''], ['xX0001', '10006', '102', '', '2018-02-01', 4142.45, 0.0, 40146.55, ''], ['xX0001', '10006', '200', '', '2018-02-02', 14367.539999999999, 0.0, 41496.42999999999, ''], ['xX0001', '10006', '200', '', '2018-02-01', 12663.27, 0.0, 56043.94, '']]
upvote count: 0
has comment: http://stackoverflow.com/comment/91131093
score: -7
linked to: http://stackoverflow.com/q/3121979
possible better answer: http://stackoverflow.com/a/52090705
accepted answer: http://stackoverflow.com/a/52090668
has answer: http://stackoverflow.com/a/52090705

http://stackoverflow.com/q/51956951
accepted answer: http://stackoverflow.com/a/51957539
favorite count: 0
score: 8
upvote count: 8
tagged with: python
has body: I was wondering how to generate a random weibull distribution with 2-parameter (lambda, k) in python. I know that numpy has a numpy.random.weibull, but it only accepts the a parameter as the shape of the distribution.
has title: How to random sample a 2-parameter weibull distribution in python
type: AnsweredQuestion
tagged with: weibull
tagged with: scipy
type: Question
tagged with: numpy
has answer: http://stackoverflow.com/a/51957539
answer count: 2
possible better answer: http://stackoverflow.com/a/51957169
has answer: http://stackoverflow.com/a/51957169
downvote count: 0
tagged with: random

http://stackoverflow.com/comment/91056540
score: 0
has text: I knew this way, is there any other ways to only get full URLs?
type: Comment
comment on: http://stackoverflow.com/a/52052293
type: AnswerComment

http://stackoverflow.com/comment/91073550
type: Comment
comment on: http://stackoverflow.com/q/52060720
type: QuestionComment
score: 2
has text: You should be using `json.dumps()` rather than `str()` to make a proper JSON version of your object.

http://stackoverflow.com/comment/90929199
type: Comment
comment on: http://stackoverflow.com/q/51989301
type: QuestionComment
has text: I only have two scenarios in my matrix column (either 'status': 'ZERO_RESULTS' or reported results in a standard format). what I want is to skip the operation to rows contains 'status': 'ZERO_RESULTS'. Even I narrow down to 1st row it will report error so I guess this is something to do with "if "status" not in x "
score: 0

http://stackoverflow.com/a/52086965
accepted answer of: http://stackoverflow.com/q/52048757
upvote count: 1
answers question: http://stackoverflow.com/q/52048757
score: 1
type: AcceptedAnswer
downvote count: 0
type: Answer
has body: I have the impression the sentiment polarity only works on TextBlob type. So my idea here is to split the text blob into words (with the split function -- see doc here) and convert them to TextBlob objects. This is done in the list comprehension: [TextBlob(x).sentiment.polarity for x in a.split()] So the whole thing looks like this: import statistics as s from textblob import TextBlob import pandas as pd a = TextBlob("""Thanks, I'll have a read!""") def compute_mean(a): return s.mean([TextBlob(x).sentiment.polarity for x in a.split()]) print(compute_mean("Thanks, I'll have a read!")) df = pd.DataFrame({'text':["Thanks, I'll have a read!", "Second sentence", "a bag of apples"]}) df['score'] = df['text'].map(compute_mean) print(df)

http://stackoverflow.com/a/52084146
type: Answer
answers question: http://stackoverflow.com/q/52084123
score: 2
has comment: http://stackoverflow.com/comment/91118596
has body: You can use the keyword argument end in print. Like this: for number in number_list: print(number, end=' ') Which, for number_list = [0,1,2,3,4,5], will give you the output: 0 1 2 3 4 5 The default for end is '\n' which is why each number is printed on a separate line.
downvote count: 0
upvote count: 2

http://stackoverflow.com/a/52082020
answers question: http://stackoverflow.com/q/52080991
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/52080991
upvote count: 39
type: Answer
downvote count: 1
score: 38
has body: Try adding the following for loop to your code: ax = result.plot(kind='bar', figsize=(15,4), width=0.8, color=colors_list, edgecolor=None) for p in ax.patches: width = p.get_width() height = p.get_height() x, y = p.get_xy() ax.annotate(f'{height}', (x + width/2, y + height*1.02), ha='center') Explanation In general, you use Axes.annotate to add annotations to your plots. This method takes the text value of the annotation and the xy coords on which to place the annotation. In a barplot, each "bar" is represented by a patch.Rectangle and each of these rectangles has the attributes width, height and the xy coords of the lower left corner of the rectangle, all of which can be obtained with the methods patch.get_width, patch.get_height and patch.get_xy respectively. Putting this all together, the solution is to loop through each patch in your Axes, and set the annotation text to be the height of that patch, with an appropriate xy position that's just above the centre of the patch - calculated from it's height, width and xy coords. For your specific need to annotate with the percentages, I would first normalize your DataFrame and plot that instead. colors_list = ['#5cb85c','#5bc0de','#d9534f'] # Normalize result result_pct = result.div(result.sum(1), axis=0) ax = result_pct.plot(kind='bar',figsize=(15,4),width = 0.8,color = colors_list,edgecolor=None) plt.legend(labels=result.columns,fontsize= 14) plt.title("Percentage of Respondents' Interest in Data Science Areas",fontsize= 16) plt.xticks(fontsize=14) for spine in plt.gca().spines.values(): spine.set_visible(False) plt.yticks([]) # Add this loop to add the annotations for p in ax.patches: width = p.get_width() height = p.get_height() x, y = p.get_xy() ax.annotate(f'{height:.0%}', (x + width/2, y + height*1.02), ha='center')

http://stackoverflow.com/q/51976179
tagged with: stretch
has body: I tried to follow this document, but I have this result: root@debian:~# apt-get install python-certbot-nginx -t stretch-backports Reading package lists... Done Building dependency tree Reading state information... Done Some packages could not be installed. This may mean that you have requested an impossible situation or if you are using the unstable distribution that some required packages have not yet been created or been moved out of Incoming. The following information may help to resolve the situation: The following packages have unmet dependencies: python-certbot-nginx : Depends: python3-certbot-nginx but it is not going to be installed E: Unable to correct problems, you have held broken packages. And when I try to install python3-certbox-nginx: Some packages could not be installed. This may mean that you have requested an impossible situation or if you are using the unstable distribution that some required packages have not yet been created or been moved out of Incoming. The following information may help to resolve the situation: The following packages have unmet dependencies: python3-certbot-nginx : Depends: certbot (>= 0.25.0~) but it is not going to be installed Depends: python3-acme but it is not going to be installed Depends: python3-certbot but it is not going to be installed Depends: python3-mock but it is not installable Depends: python3-openssl (>= 0.13) but it is not installable Depends: python3-pyparsing (>= 1.5.5) but it is not installable Depends: python3-zope.interface but it is not installable E: Unable to correct problems, you have held broken packages. I added the backports dep in my sources.list and ran apt-get update. Here is my sources.list. python -V says Python 2.7.13, but Python 3 is also installed.
has answer: http://stackoverflow.com/a/52897787
answer count: 3
has answer: http://stackoverflow.com/a/56894211
tagged with: nginx
upvote count: 5
type: UnansweredQuestion
downvote count: 0
tagged with: debian
tagged with: certbot
has title: Install Let's encrypt/Certbot on Debian9 with Nginx
favorite count: 0
has answer: http://stackoverflow.com/a/52900108
type: Question
score: 5
tagged with: python

http://stackoverflow.com/comment/91016932
comment on: http://stackoverflow.com/q/52033359
score: 0
has text: [Please don't post images of code (or links to them)](http://meta.stackoverflow.com/questions/285551/why-may-i-not-upload-images-of-code-on-so-when-asking-a-question)
type: Comment
type: QuestionComment

http://stackoverflow.com/a/52022682
score: 1
has comment: http://stackoverflow.com/comment/91003404
has body: What do you mean by changing the 1 to 2 in the y_pred? For multi-label y_pred, you should use one hot encoding where each column denotes a class, and each entry only takes 0/1. The error stems from mixing up binary encoding with class labels.
has comment: http://stackoverflow.com/comment/90995688
upvote count: 1
answers question: http://stackoverflow.com/q/52022597
type: Answer
downvote count: 0

http://stackoverflow.com/comment/91090298
has text: Which tutorials on text processing and excel handling in python did you follow? How far did you get? Please consider splitting this in two questions, one on reading multiple text files, one on writing to an excel file. Please demonstrate how far you got yourself, some own effort is expected before a question on StackOveflow. Please take the [tour] and read [ask].
type: Comment
type: QuestionComment
score: 3
comment on: http://stackoverflow.com/q/52070222

http://stackoverflow.com/q/52095303
has comment: http://stackoverflow.com/comment/91140772
downvote count: 0
tagged with: timedelta
favorite count: 0
possible better answer: http://stackoverflow.com/a/52095552
answer count: 3
tagged with: pandas
tagged with: datetime
has title: Length of a datetimeindex in python
has comment: http://stackoverflow.com/comment/91140694
has answer: http://stackoverflow.com/a/52095441
upvote count: 2
tagged with: python
score: 2
type: AnsweredQuestion
tagged with: datetimeindex
has body: I just cant find the answer and I know pandas eats problems like this for desert. I have a datetime index and want to know its length, in years: idx=pd.date_range('2011-07-03', '2015-07-10') expected output: 4.0191 years (4 years and 7 days) If I do: idx[0]-idx[-1] I get an output in days, but id like it in years Sorry: couldn't locate on panads docs
has answer: http://stackoverflow.com/a/52095664
accepted answer: http://stackoverflow.com/a/52095441
type: Question
has answer: http://stackoverflow.com/a/52095552

http://stackoverflow.com/comment/91005170
has text: Can you plz share some data for ease of reproducibility?
score: 1
type: Comment
comment on: http://stackoverflow.com/q/52027297
type: QuestionComment

http://stackoverflow.com/a/52089619
accepted answer of: http://stackoverflow.com/q/52089571
answers question: http://stackoverflow.com/q/52089571
upvote count: 1
score: 1
type: AcceptedAnswer
downvote count: 0
has body: Yes, It will. Might I suggest checking the list for the current movie and then if said movie is found, removing it from the list and then appending the new dictionary.
type: Answer

http://stackoverflow.com/q/52044434
type: Question
tagged with: python
has answer: http://stackoverflow.com/a/52044638
score: 0
has comment: http://stackoverflow.com/comment/91039866
answer count: 1
tagged with: plot
has body: I have some panda data with columns containing x, y data and id's so basically representing each point of a graph with its id as pointer to which graph the points belongs. I am plotting the data with mathplotlib. for i in df_path.id.unique(): x = df_path[df_path.id==i]['x'] y = df_path[df_path.id==i]['y'] if(df_path['id'].value_counts()==1): point=pd.DataFrame({'x': [x], 'y': [y]}) point.plot(x='x', y='y', ax=ax, style='bx', label='point') else: plt.plot(x-1, y-1) Now it happens that single points can not be displayed and I am trying to handle this with the if clause to separate lines from points in order to be able to plot them both. I want to do that by counting wether the id only occurs once in the panda table. this implements it is a single point not a line. Somehow the value_count() method does not work how i want it to work. Anyone having an idea how to fix it? Data looks like: "x" "y" "id" 3 4 0 1 2 1 1 3 1 1 4 1 In this case I would like to get the row with 0 id as a point to plot it and the 1 id as a line.
tagged with: matplotlib
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91040088
has title: Plotting both points and lines separately from pandas data that contains x, y, id columns
has comment: http://stackoverflow.com/comment/91039842
tagged with: pandas
has comment: http://stackoverflow.com/comment/91039937

http://stackoverflow.com/a/52047695
type: Answer
has body: Your code works. You need to ask for the picture to be shown plt.show() or to be saved plt.savefig(). Just add plt.show() and you will obtain:
score: 0
answers question: http://stackoverflow.com/q/52047646
has comment: http://stackoverflow.com/comment/91047140

http://stackoverflow.com/a/52042269
has comment: http://stackoverflow.com/comment/125741426
answers question: http://stackoverflow.com/q/52041893
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/111936028
has comment: http://stackoverflow.com/comment/125714196
type: Answer
score: 2
accepted answer of: http://stackoverflow.com/q/52041893
upvote count: 2
has body: There was an issue with the start time. Once I set StartTime = datetime.utcnow() - timedelta(seconds = 600), to 600 seconds instead of 2 days I was able to get datapoints. Also make sure the region is correct.

http://stackoverflow.com/comment/91193753
score: 0
type: QuestionComment
has text: What's this `str2date` converter?
type: Comment
comment on: http://stackoverflow.com/q/52110869

http://stackoverflow.com/q/52032112
has answer: http://stackoverflow.com/a/52032157
possible better answer: http://stackoverflow.com/a/52032282
type: Question
has answer: http://stackoverflow.com/a/52032282
has title: Pandas Using an If Statement to go row by row
answer count: 2
tagged with: pandas
downvote count: 0
accepted answer: http://stackoverflow.com/a/52032157
favorite count: 0
tagged with: python-3.x
tagged with: python
type: AnsweredQuestion
has body: I wasn't sure if that was the best title for this if someone else has a better idea for a title, I'm up for suggestions. Let's say I have a dataframe that looks like this: df2 A section 0 1 apple 2 orange 3 pear 4 watermelon 5 6 7 chair 8 sofa 9 table 10 desk 11 What I want is a dataframe that looks like this: A section 0 fruit 1 apple fruit 2 orange fruit 3 pear fruit 4 watermelon fruit 5 fruit 6 furniture 7 chair furniture 8 sofa furniture 9 table furniture 10 desk furniture 11 furniture Is there a way to do this? I thought about using an if statement to go row by row, but I had problems with boolean logic when I did this. Edit #1: This solution, posted below, solves my problem. Solution: df['section']=pd.Series(np.where(df.A.str.contains('<'),df.A.str.replace('<|>|/',''),np.nan)).ffill() What if I have data that looks like this? I would want the same result. A section 0 1 <fruit_1>apple</fruit_1> 2 <fruit_2>orange</fruit_2> 3 <fruit_3>pear</fruit_3> 4 <fruit_4>watermelon</fruit_4> 5 6 7 <furniture_1>chair</furniture_1> 8 <furniture_2>sofa</furniture_2> 9 <furniture_3>table</furniture_3> 10 <furniture_4>desk</furniture_4> 11
score: 1
upvote count: 1

http://stackoverflow.com/comment/91154857
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52101779
has text: It seems that `TruncatedSVD` computes the variance explained in each column of the `X_proj` not the variance explained in the singular matrix. See how to compute variance on this page: https://stats.stackexchange.com/questions/171539/percentage-of-variation-in-each-column-explained-by-each-svd-mode. And here is how `TruncatedSVD` computes variance https://github.com/scikit-learn/scikit-learn/blob/a7e17117bb15eb3f51ebccc1bd53e42fcb4e6cd8/sklearn/decomposition/truncated_svd.py#L183-L192

http://stackoverflow.com/q/52041448
type: AnsweredQuestion
tagged with: list
has comment: http://stackoverflow.com/comment/91033901
tagged with: loops
has answer: http://stackoverflow.com/a/52041768
possible better answer: http://stackoverflow.com/a/52041676
has comment: http://stackoverflow.com/comment/91033597
has comment: http://stackoverflow.com/comment/91033668
type: Question
has comment: http://stackoverflow.com/comment/91033732
score: 0
has body: I have these lists which are correct the scenario needed correction is in the explanation part at the end of the question. ps ['C:\\Users\\user\\Desktop\\sa\\43001\\PST\\PST.shp', 'C:\\Users\\user\\Desktop\\sa\\43003\\PST\\PST.shp'] and db ['C:\\Users\\user\\Desktop\\sa\\43001\\DBOUND\\DBOUND.shp', 'C:\\Users\\user\\Desktop\\sa\\43003\\DBOUND\\DBOUND.shp'] I want to compare these lists and if one of them has an item that is unique by means that the [-3] position where is a number as 43001 is unique then that item should be removed. In the end only pairs with same number items should remain. How do I do that? my code: for i,v in list(zip(ps,db)): if i.split("\\")[-3] not in v.split("\\")[-3]: ps.remove(i) Explanation if the lists are like that: ps ['C:\\Users\\user\\Desktop\\sa\\43001\\PST\\PST.shp', 'C:\\Users\\user\\Desktop\\sa\\43003\\PST\\PST.shp'] and db ['C:\\Users\\user\\Desktop\\sa\\43001\\DBOUND\\DBOUND.shp', 'C:\\Users\\user\\Desktop\\sa\\43003\\DBOUND\\DBOUND.shp', 'C:\\Users\\user\\Desktop\\sa\\43009\\DBOUND\\DBOUND.shp'] the item with 43009 should be removed because it doesn't exist in the ps list, and eventually the lists will look like this: ps ['C:\\Users\\user\\Desktop\\sa\\43001\\PST\\PST.shp', 'C:\\Users\\user\\Desktop\\sa\\43003\\PST\\PST.shp'] and db ['C:\\Users\\user\\Desktop\\sa\\43001\\DBOUND\\DBOUND.shp', 'C:\\Users\\user\\Desktop\\sa\\43003\\DBOUND\\DBOUND.shp']
tagged with: python
has answer: http://stackoverflow.com/a/52041676
answer count: 4
has comment: http://stackoverflow.com/comment/91033806
has comment: http://stackoverflow.com/comment/91033872
has answer: http://stackoverflow.com/a/52041668
accepted answer: http://stackoverflow.com/a/52041668
has answer: http://stackoverflow.com/a/52041670
has title: Remove unique items of a list among many lists

http://stackoverflow.com/comment/90963446
comment on: http://stackoverflow.com/a/52005031
type: Comment
has text: may be tomorrow or you can ask new question for that
type: AnswerComment
score: 0

auto-increment
type: Tag
tags question: http://stackoverflow.com/q/52020450
tag name: auto-increment

http://stackoverflow.com/comment/98108592
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/53405720
has text: an alternative is to do: cv2.VideoCapture(camera_index, cv2.CAP_DSHOW)
score: 1

http://stackoverflow.com/q/52089716
answer count: 1
downvote count: 1
has title: Comparing two excel files using openpyxl
has comment: http://stackoverflow.com/comment/91133364
has comment: http://stackoverflow.com/comment/91129745
favorite count: 0
has comment: http://stackoverflow.com/comment/91132731
has comment: http://stackoverflow.com/comment/91140484
has comment: http://stackoverflow.com/comment/91129757
has body: I am comparing two excel files that have a different number of columns and rows. I need to search for a particular value in a column but I am unable to do it as I am new to python. This is my code: import openpyxl from openpyxl import Workbook wk1= openpyxl.load_workbook("Condition.xlsx") wk2= openpyxl.load_workbook("Database.xlsx") sh1 = wk1['Sheet1'] sh2 =wk2['Sheet1'] rows1 = sh1.max_row columns1 = sh1.max_column rows2 = sh2.max_row columns2 = sh2.max_column for i in range(2,rows2): c = sh1.cell(2,1).value if sh2.cell(i,2).value==c: if sh2.cell(i,3).value== 'Credit' and sh1.cell(i,3).value=='UWCC_A': print(sh2.cell(i,3).value) else: print(1) Excel1 : C1 C2 C3 mike U_11 Baseball john U_12 cricket sam U_12 Handball Excel 2 C1 C2 C4 mike U_11 ABC mike U_11 XYZ mike U_11 EUE mike U_11 PIJ
has answer: http://stackoverflow.com/a/52095233
has comment: http://stackoverflow.com/comment/91133727
has comment: http://stackoverflow.com/comment/91137716
has comment: http://stackoverflow.com/comment/91129927
tagged with: python
has comment: http://stackoverflow.com/comment/91132277
has comment: http://stackoverflow.com/comment/91137384
type: UnansweredQuestion
tagged with: openpyxl
has comment: http://stackoverflow.com/comment/91129467
has comment: http://stackoverflow.com/comment/91129849
has comment: http://stackoverflow.com/comment/91129486
tagged with: excel
has comment: http://stackoverflow.com/comment/91129995
has comment: http://stackoverflow.com/comment/91132862
score: 1
has comment: http://stackoverflow.com/comment/91168152
type: Question
upvote count: 2
has comment: http://stackoverflow.com/comment/91134755
has comment: http://stackoverflow.com/comment/91138233
has comment: http://stackoverflow.com/comment/91129844
has comment: http://stackoverflow.com/comment/91129538
has comment: http://stackoverflow.com/comment/91138614

pyqt4
tags question: http://stackoverflow.com/q/51966124
tags question: http://stackoverflow.com/q/51969763
tags question: http://stackoverflow.com/q/52100089
type: Tag
tags question: http://stackoverflow.com/q/52020982
tags question: http://stackoverflow.com/q/52102318
tags question: http://stackoverflow.com/q/52109153
tags question: http://stackoverflow.com/q/52043492
tags question: http://stackoverflow.com/q/52089202
tag name: pyqt4

http://stackoverflow.com/a/52026721
answers question: http://stackoverflow.com/q/52026654
upvote count: 21
score: 21
type: AcceptedAnswer
downvote count: 0
has body: For code implemented in Python (as opposed to C extensions), if you're using ipython, an easy way to see the source code is to use the ?? operator. For example, on my 3.6 install: In [1]: import asyncio In [2]: asyncio.sleep?? Signature: asyncio.sleep(delay, result=None, *, loop=None) Source: @coroutine def sleep(delay, result=None, *, loop=None): """Coroutine that completes after a given time (in seconds).""" if delay == 0: yield return result if loop is None: loop = events.get_event_loop() future = loop.create_future() h = future._loop.call_later(delay, futures._set_result_unless_cancelled, future, result) try: return (yield from future) finally: h.cancel() File: c:\program files\python36\lib\asyncio\tasks.py Type: function You can also just look at the CPython GitHub repo, but depending on the code organization it may not be obvious where to look (e.g. in this case the code actually exists in asyncio.tasks, and is auto-imported into asyncio), while ipython magic finds it for you directly.
type: Answer
has comment: http://stackoverflow.com/comment/91003811
accepted answer of: http://stackoverflow.com/q/52026654

http://stackoverflow.com/q/52044389
has body: I have a pretty long Python 3 code that oversamples many images, then fits them to 2D Gaussians to find the relevant parameters of the sources in the images (centroid coordinates, amplitude, etc), shifts it to the center, normalizes, and then stacks all of them at the end by a median. I am trying to do this with data from about 50,000 images. I already extracted the data and have it saved from a previous code, which gave me a binary file of all the image data (numpy arrays) in a file called initial_data.data, and I also used an astropy wcs package to find good guesses for the centroid coordinates, so those are also saved (in the same order) in centroid_coords.data. When I first tried running my code on all the images, it said Killed during the oversampling part of the code. I then decided I'd try to break up all my images into subsections and run the code on one subsection at a time. This is okay if it's only a few subsections, but would become too tedious and impractical if I'd have to operate on say only 5,000 images at a time! Below is the rest of my code, where I attempted subsections of thirds, and tried just operating on the first one (so I entered in 1 after the first user input line). import pickle import numpy as np import re from scipy import optimize, interpolate from astropy.io import fits from astropy.nddata import Cutout2D frac = int(input('Subset 1, 2, or 3? ')) # select which subset of images to operate on oversampled_file = 'oversampled_images_frac%d.data' % (frac) params_file = 'gparams_2D_frac%d.data' % (frac) final_images_file = 'images_b4stacking_2D_frac%d.data' % (frac) FWHM_file = 'FWHM_2D_frac%d.data' % (frac) fitsfilename = 'stacked_images_frac%d.fits' % (frac) # Define subsets of total image data based on chosen fraction if frac==1: start, end = 0, 50000//3 print('Will operate on 1st subsection: %d elements' % (end-start)) elif frac==2: start, end = 50000//3, 2*50000//3 print('Will operate on 2nd subsection: %d elements' % (end-start)) elif…
downvote count: 0
favorite count: 0
tagged with: python-3.x
has title: How to prevent Python from killing code
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/91040196
has comment: http://stackoverflow.com/comment/91039831
tagged with: generator
answer count: 0
tagged with: memory
type: Question
score: 5
tagged with: kill
upvote count: 5
has comment: http://stackoverflow.com/comment/91040026

http://stackoverflow.com/a/51992564
answers question: http://stackoverflow.com/q/51991569
accepted answer of: http://stackoverflow.com/q/51991569
score: 3
downvote count: 0
type: AcceptedAnswer
has body: With some randomly generated data and a few changes in your code, i think here is what you want (each data point in a particular cluster has the same color): import numpy as np import pandas as pd from sklearn.decomposition import PCA from sklearn.cluster import KMeans import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D # randomly generate some data with 4 distinct clusters, use your own data here Demo_df_Processed = pd.DataFrame(np.random.randint(-2100,-2000,size=(100, 4)), columns=list('ABCD')) Demo_df_Processed = Demo_df_Processed.append(pd.DataFrame(np.random.randint(-600,-500,size=(100, 4)), columns=list('ABCD'))) Demo_df_Processed = Demo_df_Processed.append(pd.DataFrame(np.random.randint(500,600,size=(100, 4)), columns=list('ABCD'))) Demo_df_Processed = Demo_df_Processed.append(pd.DataFrame(np.random.randint(2000,2100,size=(100, 4)), columns=list('ABCD'))) pca_ = PCA(n_components=3) X_Demo_fit_pca = pca_.fit_transform(Demo_df_Processed) kmeans_PCA = KMeans(n_clusters=4, init='k-means++', max_iter= 300, n_init= 10, random_state= 3) y_kmeans_PCA = kmeans_PCA.fit_predict(X_Demo_fit_pca) y_kmeans_PCA fig = plt.figure(figsize=(20,10)) ax = fig.add_subplot(111, projection='3d') ax.scatter(X_Demo_fit_pca[:,0],X_Demo_fit_pca[:,1],X_Demo_fit_pca[:,2], c=y_kmeans_PCA, cmap='viridis', edgecolor='k', s=40, alpha = 0.5) ax.set_title("First three PCA directions") ax.set_xlabel("Educational_Degree") ax.set_ylabel("Gross_Monthly_Salary") ax.set_zlabel("Claim_Rate") ax.dist = 10 ax.scatter(kmeans_PCA.cluster_centers_[:,0], kmeans_PCA.cluster_centers_[:,1], kmeans_PCA.cluster_centers_[:,2], s = 300, c = 'r', marker='*', label = 'Centroid') plt.autoscale(enable=True, axis='x', tight=True) plt.show()
upvote count: 3
type: Answer

http://stackoverflow.com/comment/90982153
comment on: http://stackoverflow.com/q/52010551
score: 0
type: Comment
type: QuestionComment
has text: What do you mean by "difference"?

http://stackoverflow.com/comment/90922753
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51984225
score: 0
has text: I would make a separate view for the Ajax request.

http://stackoverflow.com/a/52100584
has comment: http://stackoverflow.com/comment/91153204
score: 1
answers question: http://stackoverflow.com/q/52100251
has body: One solution that comes into mind is writing a function that finds outliers based on upper and lower bounds and then slices the data frames based on outliers index e.g. df1 = pd.DataFrame({'wave': [1, 2, 3, 4, 5]}) df2 = pd.DataFrame({'stlines': [0.1, 0.2, 0.3, 0.4, 0.5]}) def outlier(value, upper, lower): """ Find outliers based on upper and lower bound """ # Check if input value is within bounds in_bounds = (value &lt;= upper) and (value &gt;= lower) return in_bounds # Function finds outliers in wave column of DF1 outlier_index = df1.wave.apply(lambda x: outlier(x, 4, 1)) # Return DF2 without values at outlier index df2[outlier_index] # Return DF1 without values at outlier index df1[outlier_index]
downvote count: 0
has comment: http://stackoverflow.com/comment/91152464
has comment: http://stackoverflow.com/comment/91152828
type: Answer
upvote count: 1

http://stackoverflow.com/comment/91139839
comment on: http://stackoverflow.com/q/52094797
score: 0
type: Comment
type: QuestionComment
has text: your `HelloWorld` resource is not returning a JSON object. You are instead returning a `str` type. It should instead be `return {'hello': 'Hello, World War 3'}`

http://stackoverflow.com/comment/99269769
type: Comment
comment on: http://stackoverflow.com/a/52151980
score: 0
type: AnswerComment
has text: Comments [archived in chat](https://chat.stackoverflow.com/rooms/194020/discussion-on-answer-by-asynts-segmentation-fault-core-dumped-when-trying-to-u).

http://stackoverflow.com/comment/90998962
comment on: http://stackoverflow.com/a/52019318
has text: @KrystianGrzelak No worries. But if you have further questions about this game, please ask a fresh question. You can link to it in a comment here if you want.
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/a/52082324
upvote count: 6
has comment: http://stackoverflow.com/comment/91196410
accepted answer of: http://stackoverflow.com/q/52082226
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/52082226
has comment: http://stackoverflow.com/comment/91196393
score: 6
type: Answer
has body: You can use the function union from set: OTHER_INGREDIENTS = set().union(*(salad.others for salad in SALADS.values())) Output {'chili', 'cheese', 'chicken', 'nachos'}

http://stackoverflow.com/q/52043671
downvote count: 0
has comment: http://stackoverflow.com/comment/91061863
has comment: http://stackoverflow.com/comment/91105488
favorite count: 0
has comment: http://stackoverflow.com/comment/91113206
has answer: http://stackoverflow.com/a/53405720
has answer: http://stackoverflow.com/a/56750151
score: 6
tagged with: python
has comment: http://stackoverflow.com/comment/91067286
upvote count: 6
answer count: 4
has answer: http://stackoverflow.com/a/52076409
possible better answer: http://stackoverflow.com/a/53405720
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91060023
type: Question
tagged with: opencv
accepted answer: http://stackoverflow.com/a/56750151
has title: OpenCV capturing image with black side bars
has body: I'm trying to capture photos and videos using cv2.VideoCapture and cameras with an aspect ratio of 16:9. All image is returned by OpenCV have black sidebars, cropping the image. In my example, instead of returning an image with 1280 x 720 pixels, it returns a 960 x 720 image. The same thing happens with a C920 webcam (1920 x 1080). What am I doing wrong? import cv2 video = cv2.VideoCapture(0) video.set(cv2.CAP_PROP_FRAME_WIDTH, 1280) video.set(cv2.CAP_PROP_FRAME_HEIGHT, 720) while True: conected, frame = video.read() cv2.imshow("Video", frame) if cv2.waitKey(1) == ord('s'): video.release() break cv2.destroyAllWindows() Using OpenCV: Using Windows Camera:
has answer: http://stackoverflow.com/a/52471871
has comment: http://stackoverflow.com/comment/91048405

http://stackoverflow.com/comment/90866405
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51957941
score: 4
has text: It's hard to understand the details of your problem without a [Minimal, complete, verifiable example](http://stackoverflow.com/help/mcve). We should be able to paste your posted code into a text file and reproduce the problem you described.

flask-cache
type: Tag
tags question: http://stackoverflow.com/q/52096704
tag name: flask-cache

http://stackoverflow.com/q/52107820
upvote count: 1
type: UnansweredQuestion
tagged with: for-loop
favorite count: 0
has comment: http://stackoverflow.com/comment/91166389
type: Question
has title: What does the word "individual" mean in my code?
has comment: http://stackoverflow.com/comment/91166492
tagged with: python
answer count: 1
score: -1
tagged with: list
downvote count: 2
has answer: http://stackoverflow.com/a/52107856
has body: In the code below the for loop prints out an entire list without brackets and in a straight line. However, I don't understand the word "individual" in it. Shouldn't the computer give me an error message because the word "individual" isn't defined or set to equal something? Furthermore, how does this for loop work to print out this list?

http://stackoverflow.com/comment/91002983
score: 1
has text: Why did you put `snip` into your code if it causes an error?
comment on: http://stackoverflow.com/q/52026382
type: Comment
type: QuestionComment

http://stackoverflow.com/q/52099068
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52099081
has answer: http://stackoverflow.com/a/52099200
has body: I have a dataframe with multiple string columns. I want to use a string method that is valid for a series on multiple columns of the dataframe. Something like this is what I would wish for: df = pd.DataFrame({'A': ['123f', '456f'], 'B': ['789f', '901f']}) df Out[15]: A B 0 123f 789f 1 456f 901f df = df.str.rstrip('f') df Out[16]: A B 0 123 789 1 456 901 Obviously, this doesn't work because str operations are only valid on pandas Series objects. What is the appropriate/most pandas-y method to do this?
upvote count: 24
type: Question
possible better answer: http://stackoverflow.com/a/52099200
score: 24
accepted answer: http://stackoverflow.com/a/52099081
has answer: http://stackoverflow.com/a/52099411
answer count: 3
tagged with: pandas
downvote count: 0
tagged with: string
favorite count: 0
has title: How to apply string methods to multiple columns of a dataframe
tagged with: python

http://stackoverflow.com/comment/92959737
score: 0
type: Comment
has text: Do you think this is due to pythran or clang vs gcc?
type: AnswerComment
comment on: http://stackoverflow.com/a/53029372

http://stackoverflow.com/comment/92528845
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52801679
has text: Perhaps that would happen on normal machines and non-bursting EC2 instances too? Either way you got to the bottom of it!
type: AnswerComment

http://stackoverflow.com/comment/90957171
type: AnswerComment
has text: [See here](https://docs.scipy.org/doc/scipy/reference/tutorial/optimize.html#constrained-minimization-of-multivariate-scalar-functions-minimize): *The method 'trust-constr' requires the constraints to be defined as a sequence of objects `LinearConstraint` and `NonlinearConstraint`. Methods 'SLSQP' and 'COBLYA', on the other hand, require constraints to be defined as a sequence of dictionaries, with keys `type`, `fun` and `jac`.* So the `LinearConstraint` object is only needed if you want to use the trust-region constrained method ('trust-constr').
type: Comment
score: 1
comment on: http://stackoverflow.com/a/52003654

http://stackoverflow.com/q/52089711
possible better answer: http://stackoverflow.com/a/53664480
linked to: http://stackoverflow.com/q/715417
tagged with: python
upvote count: 22
type: AnsweredQuestion
has title: Why is .astype('bool') converting all values to True?
has answer: http://stackoverflow.com/a/52089737
accepted answer: http://stackoverflow.com/a/52089737
has body: I'm trying to convert a column in a dataframe of strings 'TRUE' and 'FALSE' to a boolean. For other data types I've simply used astype and not had any issues, but for some reason using it on this column converts all the values to True. I have repeated the test on a list of strings as follows test = ['False','False','True'] test = pd.DataFrame(test) test = test.astype('bool') But it gives the same result, what is going on here and how do I properly convert the datatype? I've tried using map and replace to change the values before conversion but neither changed the outcome.
has comment: http://stackoverflow.com/comment/91129393
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/91129387
score: 22
tagged with: pandas
has answer: http://stackoverflow.com/a/53664480
favorite count: 0
downvote count: 0

http://stackoverflow.com/comment/111030161
has text: Or shorter with a list comprehension: `len([instance for instance in instances])`
comment on: http://stackoverflow.com/a/52169031
type: AnswerComment
type: Comment
score: 1

http://stackoverflow.com/comment/90980630
has text: Thank you for the detailed explanation. I creating this code while following along with an online python course. I'm not sure why the instructor has me making class attributes and declaring them in the initializer parameters. Hopefully, he explains why in the next few steps. I'll relay that question to their form to see if I can get a good answer. There are a lot of new terms for me in your answer so I have some studying to do. Thanks again.
type: Comment
score: 1
comment on: http://stackoverflow.com/a/52014123
type: AnswerComment

http://stackoverflow.com/comment/90937117
comment on: http://stackoverflow.com/a/51993712
type: AnswerComment
score: 1
type: Comment
has text: This has nothing to do with the issue. I'm not sure where you picked those errors from?

http://stackoverflow.com/q/51979928
has body: I've encountered an inheritance problem in Python. I'd expect the output from by program to be: # url: home/animal response: CLASS: Animal | Ability : none # url: home/animal/bird response: CLASS: Bird | Ability : Fly # url: home/animal/fish response: CLASS: Fish | Ability : Swim But I get the following output: # url: home/animal response: CLASS: Fish | Ability : Swim # url: home/animal/bird response: CLASS: Fish | Ability : Swim # url: home/animal/fish response: CLASS: Fish | Ability : Swim Here is my code: class Animal(http.Controller): name = 'Animal' ability = 'none' @http.route('/animal', auth='public', type='http', website=True, csrf=False) def util(self, **kwargs): return self.message() def message(self): return "Name: "+self.name +" | Ability : " + self.ability class Bird(Animal): name = 'Bird' ability = 'fly' @http.route('/animal/bird', auth='public', type='http', website=True, csrf=False) def util1(self, **kwargs): return self.message() class Fish(Animal): name = 'Fish' ability = 'swim' @http.route('/animal/fish', auth='public', type='http', website=True, csrf=False) def util2(self, **kwargs): return self.message() I've read quite a lot about inheritance, but still couldn't find a solution for this problem. Could it be because it has a different system in odoo python? Edit: Here is the code that works, based on @Bruno's answer. class Animal(): name = 'Animal' ability = 'none' def message(self): return "Name: {self.name} | Ability : {self.ability} ".format(self=self) class Bird(Animal): name = 'Bird' ability = 'fly' class Fish(Animal): name = 'Fish' ability = 'swim' class MyController(http.Controller): def __init__(self): self._animal = Animal() self._bird = Bird() self._fish = Fish() @http.route('/animal', auth='public', type='http', website=True, csrf=False) def animal(self, **kwargs): return self._animal.message() @http.route('/animal/bird', auth='public', type='http', website=True, csrf=False) def bird(self, **kwargs): return self._bird.message() @http.…
favorite count: 0
linked to: http://stackoverflow.com/q/625083
tagged with: python
has comment: http://stackoverflow.com/comment/90910071
has comment: http://stackoverflow.com/comment/90909508
score: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90909722
upvote count: 2
has answer: http://stackoverflow.com/a/51983190
has comment: http://stackoverflow.com/comment/90909561
type: Question
has comment: http://stackoverflow.com/comment/90909981
tagged with: odoo
has comment: http://stackoverflow.com/comment/90910041
accepted answer: http://stackoverflow.com/a/51983190
answer count: 2
has title: How to inherit class in python (odoo framework controller)
possible better answer: http://stackoverflow.com/a/51980640
downvote count: 0
has answer: http://stackoverflow.com/a/51980640

http://stackoverflow.com/a/52121395
accepted answer of: http://stackoverflow.com/q/52085600
answers question: http://stackoverflow.com/q/52085600
upvote count: 0
score: -1
type: AcceptedAnswer
has body: When using Django 1.11 in annotations you have to use a subquery to achieve the desired count of the filtered relationship. queryset = Series.objects.prefetch_related( Prefetch('issue_series', queryset=Issue.objects.filter(hide=False).filter(issue_query_set))) \ .filter(hide=False) \ .annotate(issue_count=Subquery( Issue.objects.filter( series=OuterRef('pk'), hide=False ) .filter(issue_query_set) .values('series') .annotate(cnt=Count('pk')) .values('cnt'), output_field=IntegerField() ) )\ .filter(issue_count__gt=0)
type: Answer
downvote count: 1

http://stackoverflow.com/q/52073564
has comment: http://stackoverflow.com/comment/91097234
has title: Moving a quiver in python matplotlib for animation
favorite count: 0
tagged with: python
has body: I'm trying to animate a bouncing ball in python with matplotlib. I'm trying to add a velocity vector that would point wherever I want, but I want its origin to come from the center of the ball. I did manage to make it so the direction of the quiver changes, but I can't make the origin of the quiver move with the ball. Is there a way to do that? or do I have to delete the previous quiver and redraw it? and if so, how do I do that? I know of quiver.set_UVC but can I change the origin also?
answer count: 0
downvote count: 0
type: UnansweredQuestion
tagged with: animation
has comment: http://stackoverflow.com/comment/91097911
has comment: http://stackoverflow.com/comment/91097054
score: 1
tagged with: matplotlib
type: Question
upvote count: 1

http://stackoverflow.com/a/52079510
score: 0
has body: You can have the input in such a fashion to get your data populated correctly import pandas as pd df=pd.DataFrame({'NAME':['Jack','Jill'],'AGE':[25,35],'CITY':['NYC','BOSTON']})
answers question: http://stackoverflow.com/q/52079192
type: Answer

http://stackoverflow.com/q/52013446
upvote count: 0
type: UnansweredQuestion
tagged with: tensorflow
type: Question
has answer: http://stackoverflow.com/a/52014983
score: -2
has answer: http://stackoverflow.com/a/52015079
tagged with: matplotlib
has title: How to plot loss vs epochs graph using .log file in python
tagged with: graph
answer count: 2
downvote count: 2
linked to: http://stackoverflow.com/q/42112260
tagged with: keras
favorite count: 0
has body: I have a training.log file which contain epoch,acc,loss,val_acc,val_loss 0,0.3362708558291825,1.7554432798434318,0.32878239064221265,1.9248546749544395 1,0.44641053328276503,1.4846536312246443,0.4288102535608254,1.6995067473539371 2,0.48078999617260126,1.3865143429660396,0.5075229869044302,1.34374766792883 3,0.5082378348294684,1.315985157798793,0.5161604904205097,1.2767660616831913 4,0.5180953707906859,1.2740170841302745,0.5090554472080809,1.3178076734115036 5,0.5380194364147063,1.2369382053114344,0.5238227918972441,1.286055219077107
tagged with: python

http://stackoverflow.com/q/52008241
answer count: 2
has answer: http://stackoverflow.com/a/52008852
upvote count: 1
has comment: http://stackoverflow.com/comment/90966935
tagged with: numpy
tagged with: performance
has title: How do I calculate moving average with customized weight in pandas?
type: UnansweredQuestion
has body: I have a dataframe than contains two columns, a: [1,2,3,4,5]; b: [1,0.4,0.3,0.5,0.2]. How can I make a column c such that: c[0] = 1 c[i] = c[i-1]*b[i]+a[i]*(1-b[i]) so that c:[1,1.6,2.58,3.29,4.658] Calculation: 1 = 1 1*0.4+2*0.6 = 1.6 1.6*0.3+3*0.7 = 2.58 2.58*0.5+4*0.5 = 3.29 3.29*0.2+5*0.8 = 4.658 ?
tagged with: for-loop
tagged with: pandas
has answer: http://stackoverflow.com/a/52008612
has comment: http://stackoverflow.com/comment/90967555
downvote count: 0
score: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/90967513
tagged with: python
has comment: http://stackoverflow.com/comment/90967004
has comment: http://stackoverflow.com/comment/90967180

http://stackoverflow.com/q/51960617
has comment: http://stackoverflow.com/comment/90891098
has body: Error while converting .ui file to .py file in QT I am getting error while converting .ui to .py file in QT. Error in input file: not well-formed (invalid token): line 1, column 1 I had used the same command before and it worked fine for me. But right now I am stuck with this error. I am sure i have save .ui file before converting to .py file. Please help as this issue is blocking.
has comment: http://stackoverflow.com/comment/90871521
tagged with: pyqt
answer count: 1
downvote count: 0
favorite count: 0
has title: Error while converting .ui file to .py file in QT
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90873451
tagged with: python
has comment: http://stackoverflow.com/comment/90871795
has answer: http://stackoverflow.com/a/78970241
has comment: http://stackoverflow.com/comment/90872648
score: 1
upvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/90871870

http://stackoverflow.com/comment/90982720
type: Comment
comment on: http://stackoverflow.com/a/51998508
has text: NIhal, I was able to figure it out with xlwt, xlrd, xlutils but I cannot seem to write to an .xlsx file using xlwt. Any ideas?
type: AnswerComment
score: 0

http://stackoverflow.com/comment/91161881
has text: @ALollz: I tried to extract that answer earlier and failed. :-)
type: Comment
score: 1
type: QuestionComment
comment on: http://stackoverflow.com/q/52104500

http://stackoverflow.com/q/52016961
accepted answer: http://stackoverflow.com/a/52017469
score: 0
has body: I have nx.DiGraph like this (toy example) import networkx as nx G = nx.DiGraph() G.add_node('a', weight= 1) G.add_node('b', weight= 2) G.add_node('c', weight= 3) G.add_edge('a', 'b', range = 10) G.add_edge( 'b','a', range = 20) G.add_edge('a', 'c', range = 10) G.add_edge( 'c','a', range = 20) G.add_edge('c', 'b', range = 10) G.add_edge( 'b','c', range = 20) And I build a draw as bellow plt.figure(figsize=(5,5)) edge_labels = nx.get_edge_attributes(G,'range') edge_size= [edge_labels[v] for v in edge_labels] node_labels = nx.get_node_attributes(G,'weight') node_size = [node_labels[v] for v in node_labels] pos = nx.spring_layout(G) # circularspring_layout, scale=1., center=None nx.draw_networkx_edge_labels(G,pos, edge_labels = edge_labels, font_size=25, font_color='k') nx.draw_networkx(G, pos, node_size=[d['weight']*2000 for _, d in G.nodes(data=True)], edge_color='.4', node_color= [d['weight'] for _, d in G.nodes(data=True)], alpha=0.6,with_labels=True, width = [d['range'] for _, _, d in G.edges(data=True)], cmap=plt.cm.seismic, font_size =30, arrows = False) # plt.axis('off') plt.tight_layout() plt.show() I want to show edge labels on the draw (edge attribute 'range'), but one label is superimposed over the other and we see only one (just range = 10, but there are range = 20). How to fix it?
tagged with: digraphs
answer count: 1
has title: How to show edge labes on DiGraph draw_networkx
tagged with: python
tagged with: networkx
type: AnsweredQuestion
type: Question
tagged with: graph
has answer: http://stackoverflow.com/a/52017469

http://stackoverflow.com/comment/91027632
type: Comment
comment on: http://stackoverflow.com/q/52038375
score: 0
has text: I have one button on my GUI to do that
type: QuestionComment

http://stackoverflow.com/a/51981493
downvote count: 0
score: 2
type: AcceptedAnswer
upvote count: 2
type: Answer
has body: Use GroupBy.cumcount by helper Series created by isin and cumsum and for swap ordering add [::-1]: s = pd.Series(df.index.isin(dates), index=df.index)[::-1].cumsum() df['Count'] = df.groupby(s).cumcount(ascending=False) + 1 print (df) Data Count 2018-07-02 15.60 1 2018-07-03 16.14 6 2018-07-09 12.69 5 2018-07-17 12.06 4 2018-07-19 12.87 3 2018-07-27 13.03 2 2018-08-01 13.15 1 2018-08-02 12.19 7 2018-08-07 10.93 6 2018-08-09 11.27 5 2018-08-10 13.16 4 2018-08-16 13.45 3 2018-08-17 12.64 2 2018-08-20 12.49 1
answers question: http://stackoverflow.com/q/51981314
accepted answer of: http://stackoverflow.com/q/51981314

http://stackoverflow.com/comment/91140368
has text: correct me if i am wrong but i think the ascii value for both the chars are diff
comment on: http://stackoverflow.com/q/52095038
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/55346789
downvote count: 0
score: 3
answers question: http://stackoverflow.com/q/51995558
upvote count: 3
has body: You need to first create a column with the regressor value which need to be present in both the fitting and prediction dataframes. Refer prophet docs
type: Answer

http://stackoverflow.com/a/51963556
downvote count: 0
answers question: http://stackoverflow.com/q/51963270
type: Answer
score: 1
has body: Yes, Sayse is right. Its a FileInfo Object and therefore i could use it like this. Sorry for bothering you for this simple solution. for val in files: print (val.path) and for a filepath without dbfs:/ for val in files: print(val.path.partition(':')[2])
upvote count: 1
accepted answer of: http://stackoverflow.com/q/51963270
type: AcceptedAnswer

http://stackoverflow.com/comment/90925614
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51987962
has text: `Download error on https://pypi.python.org/simple/: timed out -- Some packages may not be found!.` setup was installing requirments but failed. may be you are trying to install `pandas` offline. provide internet then run setup.py
score: 0

http://stackoverflow.com/q/52104025
has comment: http://stackoverflow.com/comment/91160067
score: 0
answer count: 2
accepted answer: http://stackoverflow.com/a/52104186
has comment: http://stackoverflow.com/comment/91159254
tagged with: http://stackoverflow.com/tag/csv
has answer: http://stackoverflow.com/a/52104183
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91159147
tagged with: list
possible better answer: http://stackoverflow.com/a/52104183
has body: I have a list of urls in a csv file and I need to run them in for eachUrl in final_url: but I keep getting a traceback error because I find out that when I print the urls from the below code, it is also printing out ['https://www.anyurl.com'] and not just the url. I have tried to run a loop to replace the [' '] but I get the traceback error AttributeError: 'list' object has no attribute 'replace'. How do I open the csv and just pull out the URL's and put them into a list without putting them into a list inside another list? import csv with open('urls_for_BrightScope_Form5500s.csv', 'r') as r: reader = csv.reader(r) for row in reader: final_urls.append(row) print(len(final_urls)) Output from final_url list: ['https://www.brightscope.com/401k-rating/372254/Merritt-Brothers-Lumber-Company/377291/Merritt-Brothers-Lumber-Co-401K-Profit-Sharing-Plan/'], ['https://www.brightscope.com/401k-rating/255132/Merritt-Club-Management-Inc/259235/Merritt-Club-Management-Inc-401K-Profit-Sharing-Plan-And-Trust/'], ['https://www.brightscope.com/401k-rating/404751/Merritt-Equipment-Co/410055/Merritt-Equipment-Co-401K-Profit-Sharing-Plan/'], ['https://www.brightscope.com/401k-rating/256405/Merritt-Hospitality-Llc/260527/Merritt-Hospitality-401K-Plan/']
has answer: http://stackoverflow.com/a/52104186
type: Question
has title: Python CSV reader makes lists inside a list
has comment: http://stackoverflow.com/comment/91159235

http://stackoverflow.com/a/52075654
has body: Turns out this is trivial, just didn't occur to me until I asked - simply use IPython.display to create Markdown or HTML programatically from IPython.display import display, Markdown path = 'https://en.wikipedia.org/static/images/project-logos/enwiki.png' # remote or local for i in range(5): print(f'foo {i}') display(Markdown(f'![]({path})'))
type: AcceptedAnswer
score: 0
accepted answer of: http://stackoverflow.com/q/52074673
type: Answer
answers question: http://stackoverflow.com/q/52074673

http://stackoverflow.com/comment/91042255
type: QuestionComment
type: Comment
score: 2
comment on: http://stackoverflow.com/q/52045659
has text: This question was suggested as a duplicate: https://stackoverflow.com/questions/9561432/what-is-the-equivalence-in-python-3-of-letters-in-python-2 However, as the name suggests, `ascii_letters` returns the ascii characters (a-Z), not the characters of the currently defined locale

http://stackoverflow.com/q/52048904
tagged with: scipy
type: Question
has answer: http://stackoverflow.com/a/52065318
tagged with: numpy
answer count: 2
has title: Solve underdetermined linear equation Ax + By = C where y is constrained by x
score: 0
tagged with: quadratic-programming
has comment: http://stackoverflow.com/comment/91049714
tagged with: linear-programming
has answer: http://stackoverflow.com/a/52048953
type: UnansweredQuestion
tagged with: python
has body: I am new to optimization and have been struggling to solve for variable x and y in linear equation Ax +By = C, while y is constrained by the solution of x. An example of the problem can be: A = np.random.rand(20,100) B = np.random.rand(20,200) C = np.random.rand(20) Solve for x and y so that Ax +By = C, with constraints that x is non-negative and -0.7*x0 &lt; y0,y1 &lt;0.7*x0, -0.7*x1 &lt; y2,y3 &lt;0.7*x1... ( -0.7x[i] &lt; y[2i],y[2i+1]&lt;0.7x[i] ) I would really appreciate if someone can recommend me a python package that solve this problem, or some way to transform my problem into a more conventional format that can be solved directly with libraries like Scipy.optimize

http://stackoverflow.com/q/52011509
upvote count: 3
answer count: 2
has answer: http://stackoverflow.com/a/52406793
favorite count: 0
has comment: http://stackoverflow.com/comment/90974434
linked to: http://stackoverflow.com/q/50029121
tagged with: python
has comment: http://stackoverflow.com/comment/90974175
has answer: http://stackoverflow.com/a/52035621
accepted answer: http://stackoverflow.com/a/52035621
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90974152
downvote count: 0
possible better answer: http://stackoverflow.com/a/52406793
has body: What is difference between tf.layers.conv2d and tf.layers.Conv2D? Why tf.layers.Conv2D used in example code in this paper? Here is a full code snippet: class AddCoords(base.Layer): """Add coords to a tensor""" def __init__(self, x_dim=64, y_dim=64, with_r=False): super(AddCoords, self).__init__() self.x_dim = x_dim self.y_dim = y_dim self.with_r = with_r def call(self, input_tensor): """ input_tensor: (batch, x_dim, y_dim, c) """ batch_size_tensor = tf.shape(input_tensor)[0] xx_ones = tf.ones([batch_size_tensor, self.x_dim], dtype=tf.int32) xx_ones = tf.expand_dims(xx_ones, -1) xx_range = tf.tile(tf.expand_dims(tf.range(self.x_dim), 0), [batch_size_tensor, 1]) xx_range = tf.expand_dims(xx_range, 1) xx_channel = tf.matmul(xx_ones, xx_range) xx_channel = tf.expand_dims(xx_channel, -1) yy_ones = tf.ones([batch_size_tensor, self.y_dim], dtype=tf.int32) yy_ones = tf.expand_dims(yy_ones, 1) yy_range = tf.tile(tf.expand_dims(tf.range(self.y_dim), 0), [batch_size_tensor, 1]) yy_range = tf.expand_dims(yy_range, -1) yy_channel = tf.matmul(yy_range, yy_ones) yy_channel = tf.expand_dims(yy_channel, -1) xx_channel = tf.cast(xx_channel, 'float32') / (self.x_dim - 1) yy_channel = tf.cast(yy_channel, 'float32') / (self.y_dim - 1) xx_channel = xx_channel*2 - 1 yy_channel = yy_channel*2 - 1 ret = tf.concat([input_tensor, xx_channel, yy_channel], axis=-1) if self.with_r: rr = tf.sqrt(tf.square(xx_channel-0.5) + tf.square(yy_channel-0.5)) ret = tf.concat([ret, rr], axis=-1) return ret class CoordConv(base.Layer): """CoordConv layer as in the paper.""" def __init__(self, x_dim, y_dim, with_r, *args, **kwargs): super(CoordConv, self).__init__() self.addcoords = AddCoords(x_dim=x_dim, y_dim=y_dim, with_r=with_r) self.conv = tf.layers.Conv2D(*args, **kwargs) def call(self, input_tensor): ret = self.addcoords(input_tensor) ret = self.conv(ret) return ret
tagged with: tensorflow
type: Question
score: 3
has title: What is difference between tf.layers.conv2d and tf.layers.Conv2D?
has comment: http://stackoverflow.com/comment/90977931

http://stackoverflow.com/q/52039925
tagged with: python
has answer: http://stackoverflow.com/a/52040099
favorite count: 0
has comment: http://stackoverflow.com/comment/91107745
tagged with: save
downvote count: 1
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/52040099
score: -1
type: Question
has body: If I'm trying to write a file in directory which is already contains file with this name, is there a way to pretend rewriting or making it possible just with receiving permission? For example: I calculated a file model.gz, but in my directory there is another file with this exact the same name, how can I in my .py script make this saving step a little bit more safely, for example saving it with different name, like: model_(1).gz or something like this? Thank you in advance!
upvote count: 0
has title: Warnings while deleting file or rewriting
answer count: 1

http://stackoverflow.com/a/51977306
has comment: http://stackoverflow.com/comment/90904952
type: Answer
score: 3
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51974174
answers question: http://stackoverflow.com/q/51974174
upvote count: 3
type: AcceptedAnswer
has body: I think the docs are saying session can be any key/value store, but they are not particularly clear in this regard. So session can be anything from python's builtin dict, to redis, other nosql stores, etc. The implementation details and what class the session object actually is are left to the user. Disclaimer: I know very little about tweepy and fully admit this is some guesswork. I used it once about a year ago and had the exact same question.

http://stackoverflow.com/q/52050160
downvote count: 2
has body: I'm looking at Python patterns from faif/python-patterns, but I have no idea when to use(or pass) a class name without parenthesis (). Original code: import random class PetShop(object): """A pet shop""" def __init__(self, animal_factory=None): """pet_factory is our abstract factory. We can set it at will.""" self.pet_factory = animal_factory def show_pet(self): """Creates and shows a pet using the abstract factory""" pet = self.pet_factory() print("We have a lovely {}".format(pet)) print("It says {}".format(pet.speak())) class Dog(object): def speak(self): return "woof" def __str__(self): return "Dog" class Cat(object): def speak(self): return "meow" def __str__(self): return "Cat" # Additional factories: # Create a random animal def random_animal(): """Let's be dynamic!""" return random.choice([Dog, Cat])() # Show pets with various factories if __name__ == "__main__": # A Shop that sells only cats cat_shop = PetShop(Cat) cat_shop.show_pet() print("") But if I do this, it will throw an error. if __name__ == "__main__": # A Shop that sells only cats cat_shop = PetShop(Cat()) cat_shop.show_pet() print("") TypeError: 'Cat' object is not callable What makes it only accept callable? And I know an instance is not callable, but how a class name is callable?
upvote count: 1
answer count: 1
favorite count: 0
tagged with: python
type: AnsweredQuestion
has title: Python - confused about callable and constructors
type: Question
has answer: http://stackoverflow.com/a/52050185
accepted answer: http://stackoverflow.com/a/52050185
has comment: http://stackoverflow.com/comment/91050715
score: -1

http://stackoverflow.com/comment/90917426
score: 1
comment on: http://stackoverflow.com/q/51961472
type: Comment
type: QuestionComment
has text: For my programm I want a QListView to show the contents of folders. Furthermore I filter the files that are shown. Since the filtered files are already there, i thought it would be nice to get them from the QListView or QFileSystemModel.

series
tag name: series
type: Tag
tags question: http://stackoverflow.com/q/52083304
tags question: http://stackoverflow.com/q/52039703
tags question: http://stackoverflow.com/q/52053698
tags question: http://stackoverflow.com/q/51968542
tags question: http://stackoverflow.com/q/52027033
tags question: http://stackoverflow.com/q/52087029
tags question: http://stackoverflow.com/q/52045995
tags question: http://stackoverflow.com/q/51969234
tags question: http://stackoverflow.com/q/51982417
tags question: http://stackoverflow.com/q/52007584
tags question: http://stackoverflow.com/q/52004346
tags question: http://stackoverflow.com/q/52104576
tags question: http://stackoverflow.com/q/52091718
tags question: http://stackoverflow.com/q/51962778
tags question: http://stackoverflow.com/q/52038896

http://stackoverflow.com/q/52098616
downvote count: 0
has answer: http://stackoverflow.com/a/52279724
score: 1
tagged with: multithreading
has title: terminate a USBdetector Thread using monitor from pyudev
type: Question
upvote count: 1
answer count: 1
favorite count: 0
tagged with: linux
tagged with: pyudev
type: UnansweredQuestion
tagged with: python
has body: I have a python script that I'm running on a remote device. There will be two different threads created. The first thread is created to monitor for USB connections to the device. class USBDetector(threading.Thread): ''' Monitor udev for detection of usb ''' def run(self): ''' Runs the actual loop to detect the events ''' self.context = pyudev.Context() self.monitor = pyudev.Monitor.from_netlink(self.context) self.monitor.filter_by(subsystem='usb') self.monitor.start() for device in iter(self.monitor.poll, None): if device.action == 'add': # some action to run on insertion of usb I've tried to insert a break statement if a global variable state changes. But it didn't work. something simple like if TERMINATE == True: break I looked at https://pyudev.readthedocs.io/en/latest/api/pyudev.html and through the reading it looks like this section of code for device in iter(self.monitor.poll, None): if device.action == 'add': # some function to run on insertion of usb is an endless loop, unless a timeout is inserted instead of None. I want to kill the thread when the other thread ends. If I give the quit command for my main thread, this usbdetector just keeps running. Any suggestions on how to stop it? (UPDATE) Hey, sorry I went with a low tech way of solving my problem for now. If anyone knows how to break out of this for loop without the need of a second loop, let me know def run(self): ''' Runs the actual loop to detect the events ''' global terminate self.rmmod_Module() self.context = pyudev.Context() self.monitor = pyudev.Monitor.from_netlink(self.context) self.monitor.filter_by(subsystem='usb') self.monitor.start() count = 0 while not terminate: count = count + 1 print count for device in iter(partial(self.monitor.poll, 3), None): if device.action == 'add': # some function to run on insertion of usb obviously I have the for loop nested in a while loop waiting for terminate to be true. Its simple and works, however would still like to know if there is a way to kick out o…

http://stackoverflow.com/comment/91157599
type: Comment
comment on: http://stackoverflow.com/a/52100453
has text: I simplified my code but I think it went wrong. I edited the question to reflect the issue, sorry , my fault. How answer changes now?
score: 0
type: AnswerComment

http://stackoverflow.com/q/51956572
type: Question
has title: Modify string values of a pandas dataframe column
has answer: http://stackoverflow.com/a/51956599
downvote count: 0
tagged with: pandas
answer count: 1
accepted answer: http://stackoverflow.com/a/51956599
favorite count: 0
tagged with: python
type: AnsweredQuestion
score: 3
upvote count: 3
tagged with: dataframe
has body: In a dataframe df = pd.DataFrame({'c1': ['c10:b', 'c11', 'c12:k'], 'c2': ['c20', 'c21', 'c22']}) c1 c2 0 c10:b c20 1 c11 c21 2 c12:k c22 I'd like to modify the string values of column c1 so that everything after (and including) the colon removes, so it ends up like this: c1 c2 0 c10 c20 1 c11 c21 2 c12 c22 I've tried slicing df[’c1’].str[:df[’c1’].str.find(’:’)] but it doesn't work. How do I accomplish this?

http://stackoverflow.com/comment/91165694
type: AnswerComment
score: 0
type: Comment
has text: Hello thanks for your response, {{ form.as_p }} does not work, and it's not p tags that I want, but a multiple selection like the example above. For saving data, it is important to know that at the same time I save data in the User model (username, email ..). And my "multiple select" in the Profil that extends from User. I wish above all to succeed in recovering my data "choices" so that the user can select things
comment on: http://stackoverflow.com/a/52107336

http://stackoverflow.com/comment/91293568
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52097835
has text: is there any way to convert the list code to a dataframe code? @miken32
score: 0

http://stackoverflow.com/a/52046354
score: 6
answers question: http://stackoverflow.com/q/52023002
has comment: http://stackoverflow.com/comment/122084711
downvote count: 0
has body: As per @JimMischel's comment, place your tuples in a tuple with the priority as the first element. Then use heapq: import heapq list = [('a', 2), ('b', 1), ('c', 0), ('d', 1)] heap_elts = [(item[1], item) for item in list] heapq.heapify(heap_elts) # you specifically asked about heapify, here it is! while len(heap_elts) &gt; 0: print(heapq.heappop(heap_elts)[1]) # element 1 is the original tuple produces: ('c', 0) ('b', 1) ('d', 1) ('a', 2)
type: Answer
upvote count: 6

http://stackoverflow.com/q/52007488
tagged with: python
has comment: http://stackoverflow.com/comment/90965772
has body: Some web pages extend themselves, via ajax presumably, when you get near the bottom, Facebook being a well known example. I am particularly interested in screenscraping Filmstruck's movie listing page. It does have an end but you can see it adding movies as you scroll down. Is there a way to use BeautifulSoup to get all the content on the page? https://www.filmstruck.com/us/watch/browse-all/
tagged with: screen-scraping
has comment: http://stackoverflow.com/comment/90965842
type: Question
has comment: http://stackoverflow.com/comment/90965278
has title: Is there a way to use BeautifulSoup with self extending pages like Facebook?
tagged with: ajax
has answer: http://stackoverflow.com/a/52007594
score: 0
answer count: 1
tagged with: beautifulsoup
type: UnansweredQuestion

http://stackoverflow.com/a/52002507
type: AcceptedAnswer
downvote count: 0
type: Answer
has body: Pandas v0.24+ See NumPy or Pandas: Keeping array type as integer while having a NaN value Pandas pre-v0.24 You cannot have NaN values in an int dtype series. This is non-avoidable, because NaN values are considered float: import numpy as np type(np.nan) # float Your best bet is to read in these columns as float instead. If you are then able to replace NaN values by a filler value such as 0 or -1, you can process accordingly and convert to int: int_cols = ['col1', 'col2', 'col3'] df[int_cols] = df[int_cols].fillna(-1) df[int_cols] = df[int_cols].apply(pd.to_numeric, downcast='integer') The alternative of having mixed int and float values will result in a series of dtype object. It is not recommended.
score: 12
accepted answer of: http://stackoverflow.com/q/52002271
answers question: http://stackoverflow.com/q/52002271
upvote count: 12

http://stackoverflow.com/comment/91128874
score: 1
has text: This question needs a cleanup (I'm not 100% on what you're asking), but if I understand correctly, you made an instance of a class `A`, but testing it with `isinstance` says it is not an instance of `A`? I'd suggest providing real code, but a common cause of this problem is if you're working in the interactive interpreter and repeatedly defining `A` and `reload`ing the associated module. When you create an instance, it will be based on the currently loaded definition of `A`, but reloading the module will create a new, unrelated definition of `A`.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52089405

http://stackoverflow.com/q/51976930
has answer: http://stackoverflow.com/a/69845812
has body: I would like to slice two columns in my data frame. This is my code for doing this: import pandas as pd df = pd.read_csv('source.txt',header=0) cidf = df.loc[:,['vocab','sumCI']] This is a sample of data: ID vocab sumCI sumnextCI new_diff 450 statu 3.0 0.0 3.0 391 provid 4.0 1.0 3.0 382 prescript 3.0 0.0 3.0 300 lymphoma 2.0 0.0 2.0 405 renew 2.0 0.0 2.0 Firstly I got this error: KeyError: “None of [['', '']] are in the [columns]”' What I have tried: I tried putting a header with index 0 while reading the file, I tried to rename columns with this code: df.rename(columns=df.iloc[0], inplace=True) I also tried this: df.columns = df.iloc[1] df = df.reindex(df.index.drop(0)) Also tried comments in this link None of the above resolved the issue.
upvote count: 33
has answer: http://stackoverflow.com/a/56749311
answer count: 5
tagged with: dataframe
tagged with: slice
has answer: http://stackoverflow.com/a/75334057
accepted answer: http://stackoverflow.com/a/51977057
tagged with: pandas
type: AnsweredQuestion
downvote count: 0
favorite count: 0
tagged with: keyerror
score: 33
linked to: http://stackoverflow.com/q/50239981
type: Question
has title: KeyError: "None of [['', '']] are in the [columns]" pandas python
has answer: http://stackoverflow.com/a/57980581
tagged with: python
has answer: http://stackoverflow.com/a/51977057
possible better answer: http://stackoverflow.com/a/69845812

http://stackoverflow.com/a/52100405
downvote count: 0
has body: You can match using two matching groups, and join: &gt;&gt;&gt; ''.join(re.findall(r'(rcp\d{2}).*?(\_mon\d{2})', s)[0]) 'rcp45_mon10'
has comment: http://stackoverflow.com/comment/91151467
type: Answer
upvote count: 2
score: 2
answers question: http://stackoverflow.com/q/52100291

http://stackoverflow.com/comment/90999428
comment on: http://stackoverflow.com/a/52022168
score: 0
type: Comment
has text: I found a similar instructions [here](https://www.metachris.com/2015/11/create-standalone-mac-os-x-applications-with-python-and-py2app/), but when I typed `py2applet --make-setup main_gui.py` it said that command "py2applet" doesn't exist. I decided to make setup.py by myself, could it be the problem?
type: AnswerComment

http://stackoverflow.com/a/52002011
has comment: http://stackoverflow.com/comment/90953676
has body: As everyone have explained your error message, i would suggest a different method. you can go with list comprehension for that. def return_word(sentence, word): if word in sentence.split(): return [i for i in sentence.split() if i == word][0] else: return '' print(return_word('sample sentence', 'sentence')) This code will get what you need. Though your requirement doesn't seem clear i hope you have something in background of this. Cheers!
type: Answer
has comment: http://stackoverflow.com/comment/90953376
has comment: http://stackoverflow.com/comment/90953518
has comment: http://stackoverflow.com/comment/90953599
has comment: http://stackoverflow.com/comment/90953256
has comment: http://stackoverflow.com/comment/90953716
accepted answer of: http://stackoverflow.com/q/52001828
has comment: http://stackoverflow.com/comment/90953414
score: 0
answers question: http://stackoverflow.com/q/52001828
type: AcceptedAnswer

http://stackoverflow.com/comment/90925420
has text: @Stanley Excellent! I'm glad you were able to solve this little mystery. :)
type: AnswerComment
comment on: http://stackoverflow.com/a/51986582
type: Comment
score: 1

http://stackoverflow.com/comment/90972244
has text: @today Thanks for notice. I'll changed my answer to cover both situation
score: 0
comment on: http://stackoverflow.com/a/52010403
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/91209223
type: Comment
has text: I don't know what I am doing wrong but it doesn't work for me :/
comment on: http://stackoverflow.com/a/52123934
type: AnswerComment
score: 0

http://stackoverflow.com/comment/91118642
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52083015
has text: Martin I cannot thank you enough for the time you spent on this response. As a new Python programmer you have probably saved me weeks of google and youtube searching to try to figure this out on my own.
score: 0

http://stackoverflow.com/q/52081545
upvote count: 10
accepted answer: http://stackoverflow.com/a/52081812
type: Question
has answer: http://stackoverflow.com/a/76487106
has body: I am dealing with a complex nested dictionary and list data structure. I need to flatten the data and bring all nested items to level 0. See below example for more clarity : {a:1,b:2,c:{c1:[{c11:1,c12:2,c13:3},{c21:1,c22:2,c23:3}],d1:[{d11:1,d12:2,d13:3},{d21:1,d22:2,d23:3}]},x:1,y:2} i need to flatten this to: {a:1,b:2,c_c1_c11:1, c_c1_c12:2,c_c1_c13:3,c_c1_c21:1,c_c1_c22:2,c_c1_c23:3, c_d1,d11:1...and so on} I took reference from the first answer in this post, but it can only work if i have nested dictionaries, and not if lists are nested within dictionaries and more dictionaries nested within those lists. I modified the code a bit to fit my use case, but this code doesn't work def flattenDict(d): node_map = {} node_path = [] def nodeRecursiveMap(d, node_path): for key, val in d.items(): if ((type(val) is not dict)&amp;(type(val) is not list)): node_map['_'.join(node_path + [key])] = val if type(val) is list: def nodeListRecursion(val,node_path): for element in val: if ((type(element) is not dict)&amp;(type(element) is not list)) : node_map['_'.join(node_path + [key])] = element if type(element) is list: nodeListRecursion(element,node_map) if type(element) is dict: nodeRecursiveMap(element, node_path + [key]) nodeListRecursion(val,node_path) if type(val) is dict: nodeRecursiveMap(val, node_path + [key]) nodeRecursiveMap(d, node_path) return node_map The indentation is getting messed up when i paste my code here. But i would really appreciate any help here.
has title: Python 3: Flattening nested dictionaries and lists within dictionaries
answer count: 3
downvote count: 0
tagged with: nested
tagged with: flatten
linked to: http://stackoverflow.com/q/28131446
favorite count: 0
has answer: http://stackoverflow.com/a/52081812
tagged with: python
tagged with: dictionary
score: 10
type: AnsweredQuestion
tagged with: list
possible better answer: http://stackoverflow.com/a/55834113
has answer: http://stackoverflow.com/a/55834113

http://stackoverflow.com/q/52035779
has comment: http://stackoverflow.com/comment/91022050
upvote count: 1
has body: I wanted to arrange the "test" list items for the second part = "1_1man:Army" which have similar words and then arrange it so that the values after "1_1man:Army" which is the values for "stack" and "testing" to be next to each other in a new column. Input : test = [[[0.52, '1_1man::army'], 'stack'], [[0.45, '3_3man::army'], 'flow'], [[0.52, '1_1man::army'], 'testing'], [[0.52, '2_2man:army'], 'expert']] code: for x in test: print(x[0][1]) Expected output: print(test) test = [[[0.52, '1_1man::army'], 'stack', 'testing'], [[0.45, '3_3man::army'], 'flow'], [[0.52, '2_2man:army'], 'expert']] Could anyone assist me please. If possible to arrange it in ascending order according to the integer value (0.45,0.52) Sort output : test = [[[0.45, '3_3man::army'], 'flow'], [[0.52, '1_1man::army'], 'stack', 'testing'], [[0.52, '2_2man:army'], 'expert']] Updated: How can I load it if I want to use the example shown by Rahul at below? my text file is like this [0.52, '1_1man::army'], 'stack'] [0.45, '3_3man::army'], 'flow'] [0.52, '1_1man::army'], 'testing'] [0.52, '2_2man:army'], 'expert'] how to load it?
has comment: http://stackoverflow.com/comment/91024324
has comment: http://stackoverflow.com/comment/91021741
favorite count: 0
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/91023795
has answer: http://stackoverflow.com/a/52037806
tagged with: list
has title: How can I arrange the list according to similar item in certain location
score: 1
has comment: http://stackoverflow.com/comment/91021927
type: Question
has comment: http://stackoverflow.com/comment/91021681
answer count: 2
has answer: http://stackoverflow.com/a/52036016
has comment: http://stackoverflow.com/comment/91022104
downvote count: 0
has comment: http://stackoverflow.com/comment/91022067

http://stackoverflow.com/a/52045109
downvote count: 0
has comment: http://stackoverflow.com/comment/91042912
upvote count: 2
answers question: http://stackoverflow.com/q/52044711
type: Answer
has body: Try to load the image using img = cv2.imread('path_to_image',cv2.IMREAD_UNCHANGED) The cv2.IMREAD_UNCHANGED parameter should load the image as it is with default alpha value
score: 2
has comment: http://stackoverflow.com/comment/91043577

http://stackoverflow.com/q/51980503
has answer: http://stackoverflow.com/a/51980684
has title: Editing a dataframe based on another dataframe
type: Question
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/51980746
tagged with: dataframe
has answer: http://stackoverflow.com/a/51980746
tagged with: python-2.7
score: 0
accepted answer: http://stackoverflow.com/a/51980684
answer count: 2
tagged with: pandas
has body: I have one dataframe called _data which looks like this: frame id x1 y1 x2 y2 score class visibility 1 1 1363 569 103 241 1 1 0.86014 2 4 1362 568 103 241 1 1 0.86173 3 4 1362 568 103 241 1 1 0.86173 4 5 1362 568 103 241 1 1 0.86173 5 5 1362 568 103 241 1 1 0.86173 6 5 1362 568 103 241 1 1 0.86173 7 6 1362 568 103 241 1 1 0.86173 8 6 1362 568 103 241 1 1 0.86173 9 7 1362 568 103 241 1 1 0.86173 10 7 1362 568 103 241 1 1 0.86173 . . . There are 108003 rows and 141 unique IDs in the dataframe. An ID represents a specific object and the ID is repeated as long as that frame has that object. In other words, my data has 141 different objects and 108003 frames. I wrote a code to identify frames that have the same objects but is labelled with a different ID. This is saved in another dataframe called _data_to_merge which looks like this. indexID matchID 4 5 6 7 8 9 12 13 18 19 20 21 . . . The second dataframe shows which indexes has been wrongly classified as a different object. The 'indexID' in _data_to_merge is the same as 'id' in _data. Taking the first line in _data_to_merge as an example, it says that index 4 and 5 is the same. Therefore, I need to change the 'id' values of all the 'id' 5 in _data to 4. This is an example of what the final table should look like after changing all the 'id'. _datanew: frame id x1 y1 x2 y2 score class visibility 1 1 1363 569 103 241 1 1 0.86014 2 4 1362 568 103 241 1 1 0.86173 3 4 1362 568 103 241 1 1 0.86173 4 4 1362 568 103 241 1 1 0.86173 5 4 1362 568 103 241 1 1 0.86173 6 4 1362 568 103 241 1 1 0.86173 7 6 1362 568 103 241 1 1 0.86173 8 6 1362 568 103 241 1 1 0.86173 9 6 1362 568 103 241 1 1 0.86173 10 6 1362 568 103 241 1 1 0.86173 . . . All the rows with 'id' 5 has been changed to 4 and all the rows of 'id' 7 has been changed to 6. How do I go about this?
tagged with: python

http://stackoverflow.com/comment/91196393
has text: Thanks, this worked and, while the other answer worked too, this one had the format that best matched our repo.
comment on: http://stackoverflow.com/a/52082324
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/a/52019617
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/90991195
has comment: http://stackoverflow.com/comment/90992819
type: Answer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/52013574
answers question: http://stackoverflow.com/q/52013574
has comment: http://stackoverflow.com/comment/90990358
score: 1
has body: It would take me a bit longer to do in Python, but I tried a few ideas just on the command-line with ImageMagick which is installed on most Linux distros and is available for free for macOS and Windows. First, I trimmed your image to get rid of extraneous junk: Then, the steps I did were: discard the alpha/transparency channel convert to greyscale as there is no useful colour information, normalised to stretch contrast and make all pixels in range 0-255, thresholded to find cells replaced each pixel by the mean of their surrounding 49x49 pixels (box blur) thresholded again at 90% That command looks like this in Terminal/Command Prompt: convert blobs.png -alpha off -colorspace gray -normalize -threshold 50% -statistic mean 49x49 -threshold 90% result.png The result is: If that approach looks promising for your other pictures we can work out a Python version pretty quickly, so let me know. Of course, if you know other useful information about your image that could help improve things... maybe you know the density is always higher at the edges, for example. In case anyone wants to see the intermediate steps, here is the image after grey scaling and normalising: And here it is after blurring:
has comment: http://stackoverflow.com/comment/91001274
upvote count: 1

http://stackoverflow.com/q/51968274
tagged with: python
has title: Similar structures w/ different operations: Would this be a job for decorator functions?
type: Question
answer count: 1
score: 0
has body: I'm putting together something that randomly changes parameters in math problems. As it is now, each problem is its own function—but these functions are very similar. Each of them takes some unformatted text... Sally has {num apples} apples. Billy takes {num_taken}. How many apples does Sally have? (... with the possibility of other arguments in the future.) And each of them returns formatted text. The difference is in what they do in between, and the number of arguments that format() needs in order to appropriately format the unformatted text. Some of them them generate the equations of planes, other just have random numbers, while others might actually need to perform certain operations on certain mathematical structures. Eventually, too, each problem-function will also generate an answer (and return a dictionary instead of just text). Here is an example: # Problem 41 def p41(unformatted_text): plane_1 = math_structures.plane() plane_2 = math_structures.plane() point = math_structures.vector() formatted_text = unformatted_text.format( plane_1=plane_1.get_eqn(), plane_2=plane_2.get_eqn(), point=point.get_eqn() ) return formatted_text # Problem 52 def p52(unformatted_text): num_prof = random.randrange(5, 25) num_teaching = random.randrange(2,5) num_courses = num_prof * num_teaching formatted_text = unformatted_text.format( num_prof=num_prof, num_teaching=num_teaching, num_courses=num_courses ) return formatted_text # Problem 54 def p54(unformatted_text): range_1 = math_structures.interval() range_2 = math_structures.interval() relational = math_structures.random_relational() formatted_text = unformatted_text.format( range_1=range_1.get_eqn(), range_2=range_2.get_eqn(), relational=relational ) return formatted_text Whenever there's a similarity in structure like this, there's something that can be done to make the code more efficient. I've never had the occasion to use decorators before, but I think this might be one. I would create a decorator which takes two argume…
tagged with: python-decorators
tagged with: python-3.x
has answer: http://stackoverflow.com/a/51968875
type: UnansweredQuestion

http://stackoverflow.com/comment/90894639
score: 0
comment on: http://stackoverflow.com/a/51971419
type: Comment
has text: Thank you for the additional explanation. My blood sugar must be low. Makes perfect sense after lunch!
type: AnswerComment

http://stackoverflow.com/comment/91157701
has text: Do some preprocessing first to turn it into something you can easily load and then efficiently process using numpy. I'd try a scheme, where each file contains nth row from each image -- i.e. each file becomes an array with 600 columns and 50000 rows. You should be able to generate those iteratively, so memory shouldn't be much issue. Now process those files one at a time, and then stack the resulting median rows back into a full image. | Your main problem right now is python interpreter overhead.
score: 1
comment on: http://stackoverflow.com/q/52102181
type: QuestionComment
type: Comment

http://stackoverflow.com/q/52052834
has title: What are examples of what the GIL does? And how does it impact memory management when using multiple threads?
upvote count: 3
tagged with: cython
has comment: http://stackoverflow.com/comment/91455424
type: Question
downvote count: 0
tagged with: gil
has comment: http://stackoverflow.com/comment/91056169
linked to: http://stackoverflow.com/q/1294382
has body: Cython's documentation talks about releasing the GIL however it does not explain what exactly the GIL does or allows. Similarly Python's documentation defines the GIL as: The mechanism used by the CPython interpreter to assure that only one thread executes Python bytecode at a time. What does this actually mean? What are some (pseudo code) examples of what is possible if the GIL did not exist and what would not be allowed? How is the memory managed because of the GIL? For example are all objects copied for each thread?
favorite count: 0
answer count: 0
type: UnansweredQuestion
tagged with: cpython
tagged with: python
score: 3

http://stackoverflow.com/comment/90987500
type: QuestionComment
comment on: http://stackoverflow.com/q/52018577
type: Comment
score: 0
has text: @MarcoD.G. If you could help me achieve DB Insertion without a possible need to stop execution of the program, using Scapy, I'd be extremely grateful.

http://stackoverflow.com/q/52062947
has comment: http://stackoverflow.com/comment/91076465
favorite count: 0
tagged with: python-3.x
has title: Python socket OSError
has comment: http://stackoverflow.com/comment/91076315
type: UnansweredQuestion
tagged with: sockets
tagged with: python
has body: I have a file accepting an input as so serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) serversocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) serversocket.bind(('localhost', 8088)) serversocket.listen(5) # become a server socket, maximum 5 connections while True: connection, address = serversocket.accept() recvd_data = connection.recv(4096) if len(recvd_data) &gt; 0: data = pickle.loads(recvd_data) print(data) serversocket.shutdown(socket.SHUT_RDWR) The script prints the data output correctly, but then throws this error. I don't understand it nor have I been able to find a solution. Traceback (most recent call last): File "sending.py", line 21, in &lt;module&gt; connection, address = serversocket.accept() File "/usr/lib/python3.5/socket.py", line 195, in accept fd, addr = self._accept() OSError: [Errno 22] Invalid argument
upvote count: 0
has answer: http://stackoverflow.com/a/52062995
type: Question
score: -1
answer count: 1
downvote count: 1

http://stackoverflow.com/comment/91007076
type: Comment
type: QuestionComment
has text: When I add input in the menu method, it still repeats but with a blank whitespace @SuryaTej
comment on: http://stackoverflow.com/q/52028235
score: 0

http://stackoverflow.com/q/52017327
type: Question
answer count: 2
possible better answer: http://stackoverflow.com/a/52018088
tagged with: image
has title: Change pixels transparent background
has answer: http://stackoverflow.com/a/52017867
upvote count: 2
favorite count: 0
has answer: http://stackoverflow.com/a/52018088
tagged with: python
score: 2
type: AnsweredQuestion
has body: I have several different images in which I want to change every transparent pixel of the image into a different color. I've found a way to extract all the RGB values of the transparent pixels of an image as such: data[data[:,:,3]==0,:3][0] Now when I try to assign a different array to this pixel it doesn't work: data[data[:,:,3]==0,:3][0] = np.array([255,0,255]) print(data[data[:,:,3]==0,:3][0]) Out[1]: [0 0 0] How do I change this pixel?
downvote count: 0
accepted answer: http://stackoverflow.com/a/52017867

http://stackoverflow.com/a/52015281
answers question: http://stackoverflow.com/q/52013486
type: Answer
has comment: http://stackoverflow.com/comment/90981526
has body: You initialise MathsEnd when you initialise the app, so the label that shows the score uses the value of controller.correct at the start of the program, which is 0. You need to create a method in your MathsEnd class which updates the label: class MathsEnd(tk.Frame): def __init__(self, parent, controller): tk.Frame.__init__(self, parent) self.controller = controller self.configure(background="#FFC2B5") # create label, pack seperately so it can be configured later self.score = tk.Label(self) self.score.grid(column=1, row=1) # initalise using method self.update_label() tk.Button(self, text="Back To Home", command = lambda: controller.show_frame("MainPage")) .grid(column=6, row=10, sticky="nesw", pady=10) # new method to update label contents def update_label(self): self.score.config(text='Congrats you got %s/2' % self.controller.correct) (I had to make some changes to how you create the label as well). You then need to call this method to update the score whenever it is changed. def right(self): self.controller.correct += 1 # update score label self.controller.frames['MathsEnd'].update_label() self.controller.show_frame('MathsQ2')
accepted answer of: http://stackoverflow.com/q/52013486
has comment: http://stackoverflow.com/comment/90983170
has comment: http://stackoverflow.com/comment/90981693
has comment: http://stackoverflow.com/comment/90981320
score: 0
type: AcceptedAnswer

http://stackoverflow.com/comment/91176998
comment on: http://stackoverflow.com/a/52108977
score: 0
has text: can you please help me : https://stackoverflow.com/questions/52113262/how-do-i-satisfy-the-my-scope-using-tkinter-using-python
type: Comment
type: AnswerComment

http://stackoverflow.com/a/51969108
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/90894931
answers question: http://stackoverflow.com/q/51968603
has comment: http://stackoverflow.com/comment/90889371
type: Answer
accepted answer of: http://stackoverflow.com/q/51968603
has comment: http://stackoverflow.com/comment/90889542
score: 1
has comment: http://stackoverflow.com/comment/90890550
has body: There must be some spelling mistake in the city name you have entered. I tried running the following code import re import urllib2 city=input("enter city:") url="https://www.weather-forecast.com/locations/" + city +"/forecasts/latest" data=urllib2.urlopen(url).read() print(data.decode('utf-8')) It works properly when i input enter city:'newyork' While the same code throws HTTPError: HTTP Error 404: Not Found error if the input is enter city:'newyolk' You can solve this by using a try-except statement city=input("enter city:") url="https://www.weather-forecast.com/locations/" + city +"/forecasts/latest" try: data=urllib2.urlopen(url).read() print(data.decode('utf-8')) except: print('The entered city does not exist.Please enter a valid city name')
upvote count: 1

http://stackoverflow.com/comment/91213190
comment on: http://stackoverflow.com/a/52121051
type: Comment
has text: `https://www.imdb.com/search/title?groups=top_1000&sort=user_rating&view=simple&page=1` please notice that this link might have different content depending on the country you are in. So it might be that you don't have `üöä`, Python2
score: 0
type: AnswerComment

http://stackoverflow.com/comment/91008735
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52029227
has text: Adding elements to list in the way you suggest would lead to implicit resizing of the list, which is not pythonic.
score: 1

http://stackoverflow.com/q/52052192
upvote count: 1
answer count: 1
favorite count: 0
tagged with: django
tagged with: python
type: AnsweredQuestion
has body: I am using environment key for better settings configuration. Initially, i got the following error django.core.exceptions.ImproperlyConfigured: Set the DATABASE_URL environment variable thus, i searched in google and found the following solution settings/base.py import os with open('.envs/.local/.postgres') as fh: os.environ.update(line.strip().split('=', 1) for line in fh) However, this gives me an error too. I get ValueError: not enough values to unpack (expected 2, got 1) .postgres and .django looks like following .django # General # ------------------------------------------------------------------------------ export USE_DOCKER=yes # Email # DJANGO_EMAIL_BACKEND # Redis # ------------------------------------------------------------------------------ export REDIS_URL=redis://redis:6379/0 # Celery # ------------------------------------------------------------------------------ # CELERY_BROKER_URL= # CELERY_RESULT_BACKEND = 'django-cache' # Flower export CELERY_FLOWER_USER=debug export CELERY_FLOWER_PASSWORD=debug .postgres # PostgreSQL # ------------------------------------------------------------------------------ POSTGRES_HOST=postgres POSTGRES_PORT=5432 POSTGRES_DB=database POSTGRES_USER=username POSTGRES_PASSWORD=password DATABASE_URL=postgres://username:password@localhost:5432/app
downvote count: 0
has answer: http://stackoverflow.com/a/52052292
accepted answer: http://stackoverflow.com/a/52052292
score: 1
type: Question
has title: ValueError: not enough values to unpack (expected 2, got 1) when updating environ

http://stackoverflow.com/comment/107135547
type: AnswerComment
has text: In my case, I forgot to add a new app to the settings.py file and migrate afterward. Out of habit I simply performed migrations which, of course, didn't include the new app's models.
type: Comment
comment on: http://stackoverflow.com/a/55902135
score: 0

http://stackoverflow.com/comment/91087912
type: Comment
score: 0
comment on: http://stackoverflow.com/q/52055072
has text: I suspect you can't take `float` of `data` because `data` isn't a length 1 array, and therefore it can't be converted to a python scalar (i.e. a `float`) use `data.astype('float')`, a numpy method.
type: QuestionComment

http://stackoverflow.com/comment/91119093
comment on: http://stackoverflow.com/q/52084355
score: 0
type: Comment
has text: That was a mis-copy, lemme fix that @MartinSeehafer
type: QuestionComment

http://stackoverflow.com/comment/91050999
type: AnswerComment
comment on: http://stackoverflow.com/a/52048738
has text: ... yeah but the `www-data` user can't just do a `chmod` on files it doesn't already have write access to. I really just care about `www-data` user or group having write access at the point a file is copied (or FTPed) to the server (since later in my scripts they will be doing chmod 664 on everything already). Anything that gets me there without storing my root password for a script is A-OK.
type: Comment
score: 0

http://stackoverflow.com/comment/90959844
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52004937
type: AnswerComment
has text: Can requests handle making ~250K calls in a relatively short amount of time? Because when I try with requests its taking very long time.

http://stackoverflow.com/q/52045899
upvote count: 1
favorite count: 0
has title: Non-greedy regex in Python
has answer: http://stackoverflow.com/a/52045900
downvote count: 0
type: UnansweredQuestion
tagged with: python
has body: Given the text: 'Adf adf asdf asdf asfdf https://.com/abcabcabc kdfja ladsjfladsjf ladksjf ladsjfl adsfadf adf asdf asdf asfdf https://.com/abcabcabc\n kdfja ladsjfladsjf ladksjf ladsjfl adsf https://.com/djflkajdsfl\n\n djldjfld djfladjf ldfdjlkfj ldfj.' How can I match any url in the form https://.com/subdir[until it hits some space or new line, comma, or full-stop]? Tried: re.findall('http.*',s) ['https://&lt;somepage&gt;.com/abcabcabc kdfja ladsjfladsjf ladksjf ladsjfl adsfadf adf asdf asdf asfdf https://&lt;somepage&gt;.com/abcabcabc', 'https://&lt;somepage&gt;.com/djflkajdsfl'] re.findall('http.* ',s) ['https://&lt;somepage&gt;.com/abcabcabc kdfja ladsjfladsjf ladksjf ladsjfl adsfadf adf asdf asdf asfdf '] re.findall('http.* ?',s) ['https://&lt;somepage&gt;.com/abcabcabc kdfja ladsjfladsjf ladksjf ladsjfl adsfadf adf asdf asdf asfdf https://&lt;somepage&gt;.com/abcabcabc', 'https://&lt;somepage&gt;.com/djflkajdsfl'] re.findall('http.* {1}?',s) ['https://&lt;somepage&gt;.com/abcabcabc kdfja ladsjfladsjf ladksjf ladsjfl adsfadf adf asdf asdf asfdf '] re.findall('http.* +?',s) ['https://&lt;somepage&gt;.com/abcabcabc kdfja ladsjfladsjf ladksjf ladsjfl adsfadf adf asdf asdf asfdf '] re.findall('http.*[^ \n]',s) ['https://&lt;somepage&gt;.com/abcabcabc kdfja ladsjfladsjf ladksjf ladsjfl adsfadf adf asdf asdf asfdf https://&lt;somepage&gt;.com/abcabcabc', 'https://&lt;somepage&gt;.com/djflkajdsfl'] re.findall('http.*[^ \\n]',s) ['https://&lt;somepage&gt;.com/abcabcabc kdfja ladsjfladsjf ladksjf ladsjfl adsfadf adf asdf asdf asfdf https://&lt;somepage&gt;.com/abcabcabc', 'https://&lt;somepage&gt;.com/djflkajdsfl'] re.findall('http.*[^ \\\n]',s) ['https://&lt;somepage&gt;.com/abcabcabc kdfja ladsjfladsjf ladksjf ladsjfl adsfadf adf asdf asdf asfdf https://&lt;somepage&gt;.com/abcabcabc', 'https://&lt;somepage&gt;.com/djflkajdsfl'] re.findall('http.* *?',s) ['https://imgur.com/abcabcabc kdfja ladsjfladsjf ladksjf ladsjfl adsfadf adf asdf asdf asfdf https://imgur.com/ab…
score: 1
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/52045901

http://stackoverflow.com/comment/91132056
type: QuestionComment
comment on: http://stackoverflow.com/q/52090826
type: Comment
has text: OpenCv handles images in Python as numpy arrays. Have you tried https://stackoverflow.com/questions/37182774/creating-mat-with-opencv-in-python or https://stackoverflow.com/questions/9710520/opencv-createimage-function-isnt-working ?
score: 1

http://stackoverflow.com/a/52098912
has body: By seeing the error it seems the path is not present. I suspect you have kept your file in local file system. If so try appending the path like below file:/yourpath/filename.csv
type: Answer
score: 0
answers question: http://stackoverflow.com/q/52098650

http://stackoverflow.com/q/51959268
type: UnansweredQuestion
tagged with: python
linked to: http://stackoverflow.com/q/7671886
has title: SQLAlchemy : 'InstrumentedList' object has no attribute/Bad Request The browser (or proxy) sent a request that this server could not understand
upvote count: 3
has answer: http://stackoverflow.com/a/51959350
type: Question
score: 3
has body: I am adding items to a SQLALchemy menu using multiple forms in a Flaskapp, like so: # query by user user = User.query.filter_by(restaurant=session['user']).first() # if user does not have a menu, create one if user.menu == []: menu = Menu() db.session.add(menu) db.session.commit() else: user = User.query.filter_by(restaurant=session['user']).first() menu = user.menu #item 1 try: add = request.form['dish'] dish = Dish() db.session.add(dish) dish.name = add db.session.commit() # add dish to menu menu.dishes.append(dish) # add menu to user user.menu.append(menu) db.session.commit() print (menu, user) except Exception as e: print str(e) #item 2 try: add2 = request.form['dish'] dish = Dish() db.session.add(dish) dish.name = add2 db.session.commit() # add dish to menu menu.dishes.append(dish) # add menu to user user.menu.append(menu) db.session.commit() print (menu, user) except Exception as e: print str(e) and so on. first menu and user print: &lt;Dishes [&lt;ID 1&gt;, &lt;Name u'pasta'&gt;]&gt; &lt;ID 1&gt;, &lt;User u'Suplicy'&gt;, &lt;Username u'me'&gt;, &lt;Email u'me@mac.com'&gt;, &lt;Menu [&lt;Dishes [&lt;ID 1&gt;, &lt;Name u'pasta'&gt;]&gt;]&gt; but second menu and user throws me the errors: 'InstrumentedList' object has no attribute 'dishes' and, at second submit: Bad Request The browser (or proxy) sent a request that this server could not understand models.py class User(db.Model): __tablename__='user' id = db.Column(db.Integer, primary_key=True) restaurant = db.Column(db.String(50)) username = db.Column(db.String(80), unique=True) email = db.Column(db.String(120), unique=True) address = db.Column(db.String(30), unique=True) menu = db.relationship("Menu", backref=db.backref('user'), uselist=True) class Menu(db.Model): __tablename__='menu' id = db.Column(db.Integer, primary_key=True) user_id = db.Column(db.Integer, db.ForeignKey('user.id')) dishes = db.relationship('Dish', back_populates='menu', uselist=True) class Dish(db.Model): __tablename__='dish' menu_id = db…
answer count: 1
downvote count: 0
tagged with: flask-sqlalchemy
favorite count: 0

http://stackoverflow.com/comment/91101691
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52075814
score: 0
has text: data=d.read() print this data as well.

http://stackoverflow.com/q/52079895
tagged with: methods
has comment: http://stackoverflow.com/comment/91109955
has body: I have a class "NN" which trains a neural network. The problem is that some of the methods in the class can not be seen/used by the others, line 47 and 50 says "undefined name truncated_normal". I can create an "NN"-class, but when I try call say nn.create_weights() it throws an error, that "truncated_normal" does not exists. The same goes for af(x) and daf(x) Any suggestions?
has comment: http://stackoverflow.com/comment/91109942
type: Question
has comment: http://stackoverflow.com/comment/91109901
has title: local methods in a class (python)
has comment: http://stackoverflow.com/comment/91110456
has answer: http://stackoverflow.com/a/52080004
tagged with: class
upvote count: 0
answer count: 1
tagged with: undefined
favorite count: 0
has comment: http://stackoverflow.com/comment/91109781
linked to: http://stackoverflow.com/q/5615648
type: UnansweredQuestion
score: -3
has comment: http://stackoverflow.com/comment/91109860
tagged with: python
duplicate of: http://stackoverflow.com/q/5615648
has comment: http://stackoverflow.com/comment/91109853
downvote count: 3

http://stackoverflow.com/q/52079774
has title: Python All my keys are using the same values
has answer: http://stackoverflow.com/a/52080175
tagged with: python
has comment: http://stackoverflow.com/comment/91109591
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91109562
downvote count: 3
has comment: http://stackoverflow.com/comment/91109616
accepted answer: http://stackoverflow.com/a/52080175
type: Question
has body: I have a problem with my code! I am in the process of making a program that will create a file that will store words alongside thee definitions using dictionaries. So far, I have gotten it to work the way I intended, but when I see the results, each key that returns all have the same value. Why/ words = {} word = raw_input("What word is it? ") definition = raw_input("What's the meaning of the word ") words[word] = definition addition = raw_input('Have another word you need to remember? Y/N ') while addition == "Y": word = raw_input("What word is it? ") definition = raw_input("What's the meaning of the word ") words[word] = definition addition = raw_input('Have another word you need to rememeber? Y/N ') # How to get my key to display the correct information. for key, value in words.items(): print(key + ": " + definition) f = open("Dcitionary.txt", "w") for key, value in words.items(): f.write(key + ": " + definition) f.close
upvote count: 0
answer count: 1
score: -3
favorite count: 0
tagged with: python-2.7

http://stackoverflow.com/q/51961472
has body: I created a QFileSystemModel to display all files in a folder within a QListView item. This works how I want it to, but now I'd like to get the filenames with path of all the files that are shown in the QListView. My code for the Interface looks like this: self.input_ = QListView() self.input_model = QFileSystemModel() self.input_model.setFilter(QDir.NoDotAndDotDot | QDir.Files) self.input_.setModel(self.input_model) self.input_.setRootIndex(self.input_model.index(self.path)) self.input_model.setNameFilters(self.filters) self.input_model.setNameFilterDisables(False) self.input_.setRootIndex( self.input_model.setRootPath(self.path)) I already tried the SelectAll() and getIndexes() methods of the QListView Object, but for some reason the SelectAll() doesn't work. Thanks for your help.
favorite count: 0
tagged with: python
has comment: http://stackoverflow.com/comment/133676370
has comment: http://stackoverflow.com/comment/90878189
tagged with: python-3.x
answer count: 0
type: UnansweredQuestion
tagged with: pyqt5
upvote count: 1
has comment: http://stackoverflow.com/comment/90917426
type: Question
score: 1
has title: PyQT5: Iterate all items in QFileSystemModel
tagged with: pyqt
downvote count: 0

http://stackoverflow.com/comment/103937375
has text: @Carlos I agree with adr: I am still confused. Let's say I have en environment, X, that only has numpy as a dependency, but want to run Spyder as my IDE, without installing Spyder and all its dependencies, in environment X. Is this possible? Is this a separate question?
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52043159

http://stackoverflow.com/comment/91074354
score: 0
comment on: http://stackoverflow.com/q/52061936
type: QuestionComment
has text: Can you post some code of what you have tried so far? Do you have some example inputs / outputs?
type: Comment

http://stackoverflow.com/comment/90994350
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52014131
has text: @abarnert Wow, i never new there was a python 0.9
type: AnswerComment

http://stackoverflow.com/q/52016751
has answer: http://stackoverflow.com/a/52017083
has comment: http://stackoverflow.com/comment/90984336
accepted answer: http://stackoverflow.com/a/52017083
has comment: http://stackoverflow.com/comment/90984500
answer count: 1
has title: Regular expression to take on letter from imput
favorite count: 0
has comment: http://stackoverflow.com/comment/90983969
has comment: http://stackoverflow.com/comment/90984464
has comment: http://stackoverflow.com/comment/90984622
has comment: http://stackoverflow.com/comment/90983691
tagged with: python
tagged with: regex
tagged with: text
type: AnsweredQuestion
has body: I'm making a question and answer sheet and need a Regular expression which takes an input, and replaces it with the first letter of the input For Example: hello world Becomes: h w And more, I am trying to change: (hello world) to: (___)HW This is to create memory cues for the answer sheet
has comment: http://stackoverflow.com/comment/90984448
upvote count: 2
score: 1
has comment: http://stackoverflow.com/comment/90983987
has comment: http://stackoverflow.com/comment/90984348
downvote count: 1
type: Question

http://stackoverflow.com/comment/90962814
type: QuestionComment
comment on: http://stackoverflow.com/q/52005830
has text: First of all, it is a xls file, so I gave you the wrong information. Sorry! I get this error message when running my first code: CompDocError: Workbook: size exceeds expected 27286528 bytes; corrupt?
score: 0
type: Comment

http://stackoverflow.com/q/52011902
has answer: http://stackoverflow.com/a/78995710
upvote count: 2
has answer: http://stackoverflow.com/a/68886539
downvote count: 1
has answer: http://stackoverflow.com/a/52012182
has body: I'm using pdf2image which uses poppler to convert PDF to images. However, when you use it in Python it opens a new console every time to convert a PDF. Is there a way to hide this console? for file_name in os.listdir(path): if file_name.endswith('.pdf'): pages = convert_from_path(path + file_name, thread_count=4) idx = 1 for page in pages: page.save(file_name + '-page-' + str(idx) + '.jpg', 'JPEG') idx += 1
favorite count: 0
has title: Python pdf2image: hide consoles
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/pdf
tagged with: python
answer count: 4
tagged with: poppler
has answer: http://stackoverflow.com/a/65056458
type: Question
score: 1

http://stackoverflow.com/comment/91110202
score: 0
has text: thats a nice solution. Thanks!
type: Comment
comment on: http://stackoverflow.com/a/52066633
type: AnswerComment

http://stackoverflow.com/comment/91099368
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/52074188
has text: Is it open source with a permissive license right now?

http://stackoverflow.com/comment/91160537
type: AnswerComment
has text: Can you include the data you are using?
type: Comment
score: 0
comment on: http://stackoverflow.com/a/52104647

http://stackoverflow.com/comment/91033806
comment on: http://stackoverflow.com/q/52041448
score: 0
has text: You want the intersection of the 2 lists
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/90903152
has text: Just use dataframe.sample(4) , refer the docs - https://pandas.pydata.org/pandas-docs/version/0.17.0/generated/pandas.DataFrame.sample.html
comment on: http://stackoverflow.com/q/51976425
type: Comment
type: QuestionComment
score: 1

http://stackoverflow.com/comment/91151441
has text: I'm not sure I buy that you need to retrain from scratch if a large-dimensional matrix changes by 1, but I agree that some kind of interpolation or broadcasting method is beyond the scope of this question
score: 1
comment on: http://stackoverflow.com/a/52100375
type: AnswerComment
type: Comment

http://stackoverflow.com/a/52079909
has body: put both statements into one! myName = input("My Name is: ") This way, "My name is Alex" will be printed for Alex input. Also, Alex is assigned to "myName". EDIT: Obviously, this is only a workaround and does not answer your question specifically.
answers question: http://stackoverflow.com/q/52079846
score: 1
upvote count: 2
downvote count: 1
type: Answer

http://stackoverflow.com/comment/91063462
comment on: http://stackoverflow.com/q/52056572
has text: You need to tell your script what it's working directory is [link]https://stackoverflow.com/questions/5137497/find-current-directory-and-files-directory
type: Comment
type: QuestionComment
score: 2

http://stackoverflow.com/comment/91090610
type: Comment
type: QuestionComment
has text: updated to a current working solution
comment on: http://stackoverflow.com/q/52070040
score: 0

http://stackoverflow.com/comment/90871674
type: Comment
score: 0
has text: my user defines fsym= with an input to the telegram chat. return self.callback(dispatcher.bot, update, **optional_args) TypeError: test() missing 1 required positional argument: 'fsym' is the error i get
type: AnswerComment
comment on: http://stackoverflow.com/a/51960531

http://stackoverflow.com/comment/91039796
has text: A [tab](https://en.wikipedia.org/wiki/Tab_key) isn't simply a sequence of spaces. Do you mean that you want to print each char in a string so that it's [left-justified](https://docs.python.org/3/library/stdtypes.html#str.ljust) in a field of a given width? There are several ways to do that efficiently in Python.
score: 2
comment on: http://stackoverflow.com/q/52044392
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/91159237
type: AnswerComment
has text: brilliant. Thank you. This opened up a new understanding of grouping and pivoting. can I also use `'id': lambda x: some function`? -as in what if I wanted to have some unique function?
type: Comment
comment on: http://stackoverflow.com/a/52104007
score: 0

http://stackoverflow.com/comment/90937151
has text: have you tried `print(len(calendar.month_name))` and see what it outputs?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51993725

http://stackoverflow.com/q/52034749
answer count: 2
upvote count: 0
has answer: http://stackoverflow.com/a/52034934
has answer: http://stackoverflow.com/a/52035522
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/91019509
tagged with: python
has body: def write_csv_file(filename): with open(filename, "w") as csv_file: file_name = csv_file write = input("please enter the number of times you would like to enter " "a text into then file onto a different line: ") write = int(write) for write in range(write): x = input("please enter what you would like to add: ") file_name.write(x) exit() xxx = input("please enter the name of the file you would like to print into: ") print(write_csv_file(xxx))
score: -1
type: UnansweredQuestion
downvote count: 1
type: Question
has title: how do I put each seperate input onto a different txt file line

http://stackoverflow.com/a/52085336
type: AcceptedAnswer
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/52054414
answers question: http://stackoverflow.com/q/52054414
upvote count: 1
has body: multiprocessing.Pool is not a thread-pool, it's a process-pool. Windows doesn't support forking hence you would have to pass something explicitly to a new process. If you want to use a thread-pool, use from multiprocessing.dummy import Pool instead.
score: 1
has comment: http://stackoverflow.com/comment/91140539

http://stackoverflow.com/comment/90992276
has text: Thanks for answer, I'll try it later and give a feedback
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52020081
type: Comment

http://stackoverflow.com/q/51961426
tagged with: python
tagged with: flask-socketio
has comment: http://stackoverflow.com/comment/90902242
type: Question
has answer: http://stackoverflow.com/a/68961413
has body: I'm using flask-socketio for server side in python. When running on windows10 the .stop() function of the flask_socketio.SocketIO works and closes the socket which terminates my script but on Unubtu it thrown exception. I want it to be closed properly. My code: import time import threading import flask import flask_socketio def start_server( vars ): vars[ "app" ] = flask.Flask(__name__) vars[ "app" ].config['SECRET_KEY'] = 'secret!' vars[ "socketio" ] = flask_socketio.SocketIO( vars[ "app" ] ) vars[ "thread" ] = threading.Thread( target= vars[ "socketio" ].run , kwargs={ "app": vars[ "app" ], "host": '127.0.0.1', "port": 5000, }) vars["thread"].start() return vars vars = {} print( "flask version: {}".format( flask.__version__ ) ) print( "flask_socketio version: {}".format( flask_socketio.__version__ ) ) start_server( vars ) time.sleep( 20 ) print( "Stopps" ) vars[ "socketio" ].stop() print( "Done" ) I get the following output: flask version: 1.0.2 flask_socketio version: 3.0.1 WebSocket transport not available. Install eventlet or gevent and gevent-websocket for improved performance. * Serving Flask app "socket_closer" (lazy loading) * Environment: production WARNING: Do not use the development server in a production environment. Use a production WSGI server instead. * Debug mode: off * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit) Stopps Traceback (most recent call last): File "socket_closer.py", line 30, in &lt;module&gt; vars[ "socketio" ].stop() File "/home/administrator/miniconda3/envs/main/lib/python3.6/site-packages/flask_socketio/__init__.py", line 564, in stop func = flask.request.environ.get('werkzeug.server.shutdown') File "/home/administrator/miniconda3/envs/main/lib/python3.6/site-packages/werkzeug/local.py", line 347, in __getattr__ return getattr(self._get_current_object(), name) File "/home/administrator/miniconda3/envs/main/lib/python3.6/site-packages/werkzeug/local.py", line 306, in _get_current_object return self.__local() File "/home/a…
score: 0
answer count: 2
has title: Closing Flask-SocketIO gracefully in python
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51975884

http://stackoverflow.com/a/52072046
downvote count: 1
has comment: http://stackoverflow.com/comment/91094800
type: AcceptedAnswer
has body: You may use import re s = "Employee ID DF856, Year 2016, Department Finance, Team 2, Location 112 20161 12016 120162" print(re.findall(r'(?&lt;!\d)(?!2016(?!\d))\d{3,}', s)) See the Python demo and a regex demo. Details (?&lt;!\d) - no digit allowed iommediately to the left of the current location (?!2016(?!\d)) - no 2016 not followed with another digit is allowed immediately to the right of the current location \d{3,} - 3 or more digits. An alternative solution with some code: import re s = "Employee ID DF856, Year 2016, Department Finance, Team 2, Location 112 20161 12016 120162" print([x for x in re.findall(r'\d{3,}', s) if x != "2016"]) Here, we extract any chunks of 3 or more digits (re.findall(r'\d{3,}', s)) and then filter out those equal to 2016.
has comment: http://stackoverflow.com/comment/91094106
has comment: http://stackoverflow.com/comment/91094650
upvote count: 2
type: Answer
accepted answer of: http://stackoverflow.com/q/52071899
has comment: http://stackoverflow.com/comment/91094215
answers question: http://stackoverflow.com/q/52071899
score: 1
has comment: http://stackoverflow.com/comment/91094985

http://stackoverflow.com/comment/90903898
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/51976878
has text: `time.sleep()` is measured in seconds not milliseconds, I believe you meant to say `time.sleep(2)`

http://stackoverflow.com/q/52052187
type: UnansweredQuestion
has title: Newline character at the end of bulk index Elasticsearch python
upvote count: 1
score: 1
type: Question
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/91054597
tagged with: elasticsearch
has body: I want to bulk update using python elasticsearch. I have a list containing dictionary of metadata (_id, _type, _doc) follow by dictionary of actual data (the data will be in _source) repeatedly. I am experiencing some missing documents when bulk index more than 50000 documents. Follow this guide: https://www.elastic.co/guide/en/elasticsearch/guide/1.x/bulk.html . Do I need to add '\n' character at the end of each object? How can I add ' \n' when all my element in list is dictionary? What is the correct format? Thank you
tagged with: python
answer count: 0

http://stackoverflow.com/q/52015272
downvote count: 1
type: AnsweredQuestion
tagged with: routes
type: Question
has answer: http://stackoverflow.com/a/52015299
answer count: 1
has body: I have made two routes in Flask. I want to send variables to a route from another route but I don't want it to get redirect to it the route. @app.route('/') def index(): name = 'Hello' return redirect(url_for('a', name=name) @app.route('/&lt;name&gt;') def a(name): return name What I want is that my index should not redirect to 'a' route. 'a' route should work only whenever I type it manually.
tagged with: flask
favorite count: 0
tagged with: python
score: 2
accepted answer: http://stackoverflow.com/a/52015299
upvote count: 3
has title: Flask - How to send variables to different routes without redirecting?

http://stackoverflow.com/q/52009351
has answer: http://stackoverflow.com/a/75470492
tagged with: python
upvote count: 4
has answer: http://stackoverflow.com/a/75812070
tagged with: selenium-webdriver
tagged with: selenium-chromedriver
has answer: http://stackoverflow.com/a/75910621
score: 3
has answer: http://stackoverflow.com/a/69735247
has title: The process started from chrome location C:\..\Chrome\Application\chrome.exe is no longer running, so ChromeDriver is assuming that Chrome has crashed
has answer: http://stackoverflow.com/a/61238289
has comment: http://stackoverflow.com/comment/90970021
tagged with: selenium
tagged with: google-chrome
type: Question
has body: Chrome version: 68.0.3440.106 Chrome webdriver version: ChromeDriver 2.41.578737 Python Version : Python 3.5.2 I write this code in python: from selenium import webdriver from selenium.webdriver.common.keys import Keys o = webdriver.ChromeOptions() o.add_argument("disable-extensions"); o.add_argument("--start-maximized"); driver = webdriver.Chrome(executable_path=r"chromedriver.exe",options=o) driver.get("http://www.python.org") assert "Python" in driver.title elem = driver.find_element_by_name("q") elem.clear() elem.send_keys("pycon") elem.send_keys(Keys.RETURN) assert "No results found." not in driver.page_source driver.close() after few seconds chrome opened with this error: and nothing happend till i close chrome and get this exception: Traceback (most recent call last): File ".../game.py", line 8, in &lt;module&gt; driver = webdriver.Chrome(executable_path=r"chromedriver.exe",options=o) File "...\Python\Python35-32\lib\site-packages\selenium\webdriver\chrome\webdriver.py", line 75, in __init__ desired_capabilities=desired_capabilities) File "...\Python\Python35-32\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 156, in __init__ self.start_session(capabilities, browser_profile) File "...\Python\Python35-32\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 251, in start_session response = self.execute(Command.NEW_SESSION, parameters) File "...\Python\Python35-32\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 320, in execute self.error_handler.check_response(response) File "...\Python\Python35-32\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 242, in check_response raise exception_class(message, screen, stacktrace) selenium.common.exceptions.WebDriverException: Message: unknown error: Chrome failed to start: exited normally (unknown error: unable to discover open pages) (The process started from chrome location C:\Program Files (x86)\Google\Chrome\Application\chrome.exe is no longer running, so Chr…
has answer: http://stackoverflow.com/a/52009668
has answer: http://stackoverflow.com/a/52011058
linked to: http://stackoverflow.com/q/34164831
has comment: http://stackoverflow.com/comment/90969846
downvote count: 1
answer count: 7
has comment: http://stackoverflow.com/comment/90969920
favorite count: 0
linked to: http://stackoverflow.com/q/50138615
type: UnansweredQuestion

bias-neuron
tags question: http://stackoverflow.com/q/51959507
type: Tag
tag name: bias-neuron

http://stackoverflow.com/q/52038056
has title: Constraint is sometimes not being strictly adhered to using GLOP_LINEAR_PROGRAMMING
tagged with: python
tagged with: linear-programming
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/92498880
downvote count: 1
type: Question
tagged with: or-tools
has comment: http://stackoverflow.com/comment/97353199
score: -1
upvote count: 0
answer count: 1
favorite count: 0
has body: I'm using Google's ortools for Python to solve a problem. A constraint that I provide is sometimes not being strictly adhered to when running with various data through it. I've created a test to run 1000 optimisations and change the data input with random values of which the Objective is set to Maximisation. Every now and again the test will fail as one results price is over 1000. It is possible not to go over, so why does it choose to? How can I enforce the strict use of constraints? # Price constraint - must NOT be more than 1000 cons = solver.Constraint(0, 1000)
has answer: http://stackoverflow.com/a/52040065

http://stackoverflow.com/comment/90958306
type: Comment
comment on: http://stackoverflow.com/q/52004018
type: QuestionComment
score: 0
has text: please remove the index method since it is not essential. I'll remove it from the example

http://stackoverflow.com/a/52276457
type: Answer
has comment: http://stackoverflow.com/comment/91516330
score: 2
upvote count: 2
accepted answer of: http://stackoverflow.com/q/52069057
has body: You could try something like that: @hybrid_property def max_size(self): return ( db.session.query(func.max(Screen.height, Screen.width)) .filter(Screen.id == self.id) .scalar() ) @max_size.expression def max_size(cls): return ( select([func.max(Screen.height, Screen.width)]) .where(Screen.id == cls.id) .label("max_size") )
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/52069057

http://stackoverflow.com/comment/91020928
type: Comment
score: 1
has text: Could you please provide the error message you get?
comment on: http://stackoverflow.com/q/52035388
type: QuestionComment

http://stackoverflow.com/comment/130157985
has text: Does this answer your question? [Why do these list operations (methods) return None, rather than the resulting list?](https://stackoverflow.com/questions/11205254/why-do-these-list-operations-methods-return-none-rather-than-the-resulting-li)
comment on: http://stackoverflow.com/q/52083510
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/90867957
type: Comment
comment on: http://stackoverflow.com/q/51958143
type: QuestionComment
score: 0
has text: Do you want to choose `N` indices such that change around those indices falls in the `N` largest values?

http://stackoverflow.com/comment/91033072
has text: When possible create the dot file of the failing graph for inspection, or otherwise at least make a file with the ids as you are using in that file.
comment on: http://stackoverflow.com/q/52041076
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/52038992
score: 0
type: Answer
has comment: http://stackoverflow.com/comment/91030111
has comment: http://stackoverflow.com/comment/91030589
has body: Updating my answer accordingly to, temp = [] for i in paosted: temp.append("_".join(i)) " ".join(temp)
has comment: http://stackoverflow.com/comment/91028909
answers question: http://stackoverflow.com/q/52037228

http://stackoverflow.com/q/52097967
tagged with: seaborn
has answer: http://stackoverflow.com/a/52100896
type: Question
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91159197
has body: I feel quite dumb but it seems like I can't make my line graph work properly with seaborn. Seems to be related to x Axis but I don't get it. My source data is raw files from https://www.insee.fr/fr/statistiques/2540004 . ch3 looks like this just before seaborn: annais dpt nombre 18 1952 23 3 23 1956 23 3 29 1961 23 4 31 1962 23 4 33 1963 23 8 35 1964 23 12 37 1965 23 16 39 1966 23 26 41 1967 23 37 43 1968 23 35 47 1969 23 58 51 1970 23 64 55 1971 23 39 59 1972 23 42 63 1973 23 48 67 1974 23 32 71 1975 23 27 75 1976 23 21 79 1977 23 17 83 1978 23 23 87 1979 23 15 91 1980 23 18 95 1981 23 14 99 1982 23 9 103 1983 23 8 107 1984 23 11 111 1985 23 3 115 1986 23 7 119 1987 23 5 129 1990 23 4 .. ... .. ... 98 1981 93 208 102 1982 93 209 106 1983 93 162 110 1984 93 180 114 1985 93 136 118 1986 93 126 122 1987 93 112 125 1988 93 100 128 1989 93 64 132 1990 93 61 135 1991 93 71 138 1992 93 56 141 1993 93 40 144 1994 93 54 147 1995 93 42 150 1996 93 30 153 1997 93 17 156 1998 93 21 159 1999 93 14 162 2000 93 17 165 2001 93 28 168 2002 93 16 171 2003 93 10 174 2004 93 11 177 2005 93 4 180 2006 93 4 184 2008 93 5 187 2009 93 4 191 2011 93 4 198 2017 93 4 [199 rows x 3 columns] Basically trying to plot frequency of first names (y axis) by year (x axis) for 4 dept. Years ('annais') are a four digit integer. I sorted values just to be safe. Yet the line graph keeps breaking, the values can't stay continuously right to left. Pandas plot() required a an ad hoc pivot but at least it works. Any idea ? Code that works (Pandas plot() ): import numpy as np from matplotlib import pyplot as plt from matplotlib import cm %matplotlib inline plt.rcParams['figure.figsize'] = [12, 8] import pandas as pd import seaborn as sns df = pd.read_csv('dpt2017.txt', sep = '\t') ##df = pd.read_csv('nat2017.txt', sep = '\t') ch = df.loc[df['preusuel'].isin(['CHRISTOPHE'])] ch = ch[ch.annais != 'XXXX'] ch.nombre.astype(int) ch.annais.astype(int) ch = ch.drop(columns=['sexe']) ch = ch[ch.dpt.isin(['75', '92',…
tagged with: matplotlib
has title: Issues with Seaborn line graphs going "back left"
has comment: http://stackoverflow.com/comment/91150579
answer count: 1
accepted answer: http://stackoverflow.com/a/52100896
has comment: http://stackoverflow.com/comment/91151888
score: 0
tagged with: pandas
tagged with: python
has comment: http://stackoverflow.com/comment/91152526
has comment: http://stackoverflow.com/comment/91151534

http://stackoverflow.com/comment/91038371
comment on: http://stackoverflow.com/q/52043718
has text: You want to implement recursive algorithms in C so you get a segfault instead of a nice exception when the stack overflows? =P
type: Comment
type: QuestionComment
score: 3

http://stackoverflow.com/comment/91027101
type: QuestionComment
comment on: http://stackoverflow.com/q/52038416
has text: Does it make sense to `print` an integer? Does it make sense to `print` a dictionary? Does it make sense to `capitalize` an integer? Does it make sense to `capitalize` a dictionary?
type: Comment
score: 1

http://stackoverflow.com/q/51994464
answer count: 1
has comment: http://stackoverflow.com/comment/90938854
tagged with: documentation
favorite count: 0
tagged with: exception
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/90938772
has comment: http://stackoverflow.com/comment/112813283
has answer: http://stackoverflow.com/a/57220960
linked to: http://stackoverflow.com/q/33262919
type: Question
score: 5
upvote count: 5
downvote count: 0
has body: In Python, should we document in the docstrings exceptions that can be raised in other functions/classes besides the ones that are raised in the body of current function/method? Obs.: I'm considering the Google Python docstring style https://sphinxcontrib-napoleon.readthedocs.io/en/latest/example_google.html It has been a long time since I don't play with Java, but there you would explicitly say what kind of exceptions that your method could raise with the "throws" keyword. Eg.: class MyException(Exception): pass class A(object): def foo(self): """This class does foo Returns: Int: The number of foo. Raises: MyException - In case something happen """ if True: raise MyException return 0 class B(object): def __init__(self): self._a = A() def bar(self): """This class does bar Returns: Int: number of bar Raises: MyException ????? Should this be here? """ return self._a.foo()
has title: Documenting exceptions that can happen in other functions in python docstrings
tagged with: docstring
has comment: http://stackoverflow.com/comment/90938879

http://stackoverflow.com/comment/91087291
comment on: http://stackoverflow.com/q/52068557
score: 0
type: Comment
has text: I tried now @Darkonaut.. But it is not reflecting :(
type: QuestionComment

http://stackoverflow.com/q/51979554
answer count: 1
downvote count: 0
favorite count: 0
has title: TypeError: Cannot handle the data type in PIL Image
accepted answer: http://stackoverflow.com/a/51979744
tagged with: python
type: AnsweredQuestion
score: 2
has body: I have a Pytorch tensor of size (4,3,224,224). When I am trying to convert the first tensor into an Image object, it says: TypeError: Cannot handle this data type I ran the following command: img = Image.fromarray(data[0][i].numpy().astype(np.uint8)) where data is the Pytorch tensor I tried other solutions but couldn't find any solution. Please suggest !!
tagged with: python-imaging-library
upvote count: 2
tagged with: pytorch
tagged with: image-processing
type: Question
tagged with: numpy
has answer: http://stackoverflow.com/a/51979744

http://stackoverflow.com/q/52084486
favorite count: 0
tagged with: python
type: AnsweredQuestion
upvote count: 2
has answer: http://stackoverflow.com/a/52084599
tagged with: django
type: Question
has body: To wrap some text around one of my CreatView classes I use a HTML template to wrap the form. However, when using this template everything works as expected except that the image passed to the ImageField of the form is not saved. Commenting out the the line where the template of the CreateView is set solves the problem. But I would like to use the template to have the option to show more on the page than just the form. How does the logic of the form change when wrapping it into a template? views.py class PieceInstanceCreate(LoginRequiredMixin, CreateView): model = PieceInstance fields = ['version', 'piece_image', 'status'] # commenting out the below line makes the form save the image template_name = 'pieceinstance_create.html' def form_valid(self, form): form.instance.piece = Piece.objects.get(id=self.kwargs['pk']) return super(PieceInstanceCreate, self).form_valid(form) def get_success_url(self): return reverse_lazy('piece-detail', kwargs={'pk': self.kwargs['pk']}) pieceinstance_create.html {% extends "base_generic.html" %} {% block content %} Add a Version {% csrf_token %} {{ form.as_p }} {% endblock %}
has title: Django: image not saved when using CreateView with a HTML template
accepted answer: http://stackoverflow.com/a/52084599
score: 2
answer count: 1
downvote count: 0

http://stackoverflow.com/q/52018403
has title: Central control of importing different versions of script as I save up
has comment: http://stackoverflow.com/comment/90987038
score: 1
has comment: http://stackoverflow.com/comment/90987030
favorite count: 0
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52018569
has body: As I improve my code each time, for big structural changes in flow and other features I save up and add a new number... so when I use the code it looks like this: import custom3 as c function = c.do_thing() as I save up to custom4, I change it to import custom4 as c function = c.do_thing() very simple update. My problem is that I have many scripts where i'm using import custom# as c so when I update the version number, I have to go back and change the number everywhere. Is there a way to centrally control this? Basically dynamically importing a library using another script? I guess I can use something like modules = map(__import__, moduleNames) and keep a spreadsheet of latest version? And write a script to access that file first every time? Has anybody implemented anything else more elegant?
upvote count: 2
downvote count: 1
type: Question
tagged with: python-import
possible better answer: http://stackoverflow.com/a/52018516
has answer: http://stackoverflow.com/a/52018516
accepted answer: http://stackoverflow.com/a/52018569
answer count: 2

http://stackoverflow.com/a/52085981
type: Answer
has comment: http://stackoverflow.com/comment/91122885
answers question: http://stackoverflow.com/q/52085191
upvote count: 0
has body: I ran into the same error a few days ago! Thankfully, I found the answer. You see, the problem is that pyodbc comes in a .whl (wheel) file/package. So, as a result, you have to pip install it. Pip installing is a very tricky process, so please be careful. The steps are:- Step1. Go to C:/Python (whatever version you are using)/Scripts. Scroll down. If you see a file named pip.exe, then that means that you are in the right folder. Copy the path. Step2. In your computer, search for Environment Variables. You should see an option labeled 'Edit the System Environment Variables'. Click on it. Step3. There, you should see a dialogue box appear. Click 'Environment Variables'. Click on 'Path'. Then, click 'New'. Paste the path that you copied earlier. Step4. Click 'Ok'. Step5. Open the Windows File Explorer. Shift + Right Click wherever your pyodbc.whl file is installed. Select 'Open Command Window Here' from the dropdown menu. Type in 'pip install py', then click tab and the full file name should fill in. Then, press Enter, and you're ready to go! Now you shouldn't get the error again!!!
score: -1
has comment: http://stackoverflow.com/comment/91472374
downvote count: 1

http://stackoverflow.com/q/52039621
has comment: http://stackoverflow.com/comment/91033749
favorite count: 0
has answer: http://stackoverflow.com/a/52044253
has comment: http://stackoverflow.com/comment/96372524
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/91030057
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/110566184
has comment: http://stackoverflow.com/comment/91030804
tagged with: python
has title: Tkinter Button text invisible until window resize
has body: I have Python 3.6.3. I'm trying to program a simple GUI app with Submit and Quit buttons. I've got this GUI code: from tkinter import * from sys import exit ... some = True stuff = False here = "bar" top = Tk() submitButton = Button(top, text="Submit", command=lambda: submit(some, things, set, here)).pack(pady=50, side=LEFT) exitButton = Button(top, text="Quit", command=exit).pack(pady=50, side=RIGHT) top.mainloop() However, upon running this code, my button labels are invisible: And I need to resize the window, even only a little, in order to see them again: Am I doing something wrong here, or is this a bug with tkinter?
score: 3
tagged with: tkinter
has comment: http://stackoverflow.com/comment/91040291
has comment: http://stackoverflow.com/comment/91033838
has comment: http://stackoverflow.com/comment/91040404
upvote count: 3
has comment: http://stackoverflow.com/comment/91030441
has comment: http://stackoverflow.com/comment/91040296
has comment: http://stackoverflow.com/comment/91041763
has comment: http://stackoverflow.com/comment/91040387
has comment: http://stackoverflow.com/comment/91040532
has comment: http://stackoverflow.com/comment/91030265
type: Question
has comment: http://stackoverflow.com/comment/91040581
has comment: http://stackoverflow.com/comment/91040336
has comment: http://stackoverflow.com/comment/94290072
answer count: 1
tagged with: button
downvote count: 0

http://stackoverflow.com/q/51989544
tagged with: google-cloud-python
type: Question
has comment: http://stackoverflow.com/comment/90929408
linked to: http://stackoverflow.com/q/4254678
tagged with: google-cloud-platform
has answer: http://stackoverflow.com/a/51991317
accepted answer: http://stackoverflow.com/a/51991317
answer count: 1
downvote count: 0
favorite count: 0
tagged with: google-app-engine
tagged with: python
type: AnsweredQuestion
has title: App Engine Python, Standard Environment, using time.sleep
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/90929799
has body: I read that using time.sleep counts against some CPU quota. I never heard of such a quota before or could find anything in the docs. Can someone enlighten me please? EDIT: Since the other questions are 8 years old and I couldnt find anything in the docs or in the Google Cloud Console (at IAM &amp; admin, Quota), I suspect the Quota is obsolete now and a updated clarification is in order IMO.

http://stackoverflow.com/q/52109506
has body: How can I get the region in which the current Glue job is executing? When the Glue job starts executing, I see the output Detected region eu-central-1. In AWS Lambda, I can use the following lines to fetch the current region: import os region = os.environ['AWS_REGION'] However, it seems like the AWS_REGION environment variable is not present in Glue and therefore a KeyError is raised: KeyError: 'AWS_REGION' The reason why I need the region is I am trying to fetch all databases and tables as described in this question and I do not want to hard code the region when creating the boto client.
tagged with: amazon-web-services
favorite count: 0
upvote count: 3
answer count: 3
has answer: http://stackoverflow.com/a/52149901
accepted answer: http://stackoverflow.com/a/52149901
tagged with: python
linked to: http://stackoverflow.com/q/56692091
linked to: http://stackoverflow.com/q/46080504
has title: AWS region in AWS Glue
possible better answer: http://stackoverflow.com/a/61085582
downvote count: 0
has answer: http://stackoverflow.com/a/61085582
type: Question
type: AnsweredQuestion
score: 3
tagged with: aws-glue
has answer: http://stackoverflow.com/a/72467100

http://stackoverflow.com/comment/91336274
type: Comment
has text: As I said at the beginning, I’m less concerned with the specific results and more with consistency. From my perspective as a user, I would expect *all* of the assignments in my question to be equivalent. Judging from your statements, I would think that they should probably **all throw an exception**. By the way, is it documented anywhere that this kind of use is not recommended? Otherwise this non-recommendation is, unfortunately, not very useful to users.
type: AnswerComment
comment on: http://stackoverflow.com/a/52167790
score: 0

http://stackoverflow.com/q/52019808
has comment: http://stackoverflow.com/comment/90995041
type: AnsweredQuestion
score: 1
accepted answer: http://stackoverflow.com/a/52021000
tagged with: machine-learning
tagged with: text-classification
has title: RNN: Get prediction from a text input after the model is trained
downvote count: 1
tagged with: tensorflow
type: Question
has comment: http://stackoverflow.com/comment/91003698
answer count: 1
has answer: http://stackoverflow.com/a/52021000
has body: I am new to RNNs and I have been working on a small binary label classifier. I have been able to get a stable model with satisfactory results. However, I am having a hard time using the model to classify new inputs and I was wondering if any of you could help me. Please see my code below for reference. Thank you very much. from tensorflow.keras import preprocessing from sklearn.utils import shuffle import pandas as pd import numpy as np from sklearn.model_selection import train_test_split from sklearn.preprocessing import LabelEncoder from tensorflow.keras.models import Model from tensorflow.keras import models from tensorflow.keras.layers import LSTM, Activation, Dense, Dropout, Input, Embedding from tensorflow.keras.optimizers import RMSprop, Adam from tensorflow.keras.preprocessing import sequence, text from tensorflow.keras.callbacks import EarlyStopping from matplotlib import pyplot class tensor_rnn(): def __init__(self, hidden_layers=3): self.data_path = 'C:\\\\Users\\cmazz\\PycharmProjects\\InvestmentAnalysis_2.0\\Sentiment\\Finance_Articles\\' # self.corp_paths = corpora_paths self.h_layers = hidden_layers self.num_words = [] good = pd.read_csv(self.data_path + 'GoodO.csv') good['Polarity'] = 'pos' for line in good['Head'].tolist(): counter = len(line.split()) self.num_words.append(counter) bad = pd.read_csv(self.data_path + 'BadO.csv') bad['Polarity'] = 'neg' for line in bad['Head'].tolist(): counter = len(line.split()) self.num_words.append(counter) self.features = pd.concat([good, bad]).reset_index(drop=True) self.features = shuffle(self.features) self.max_len = len(max(self.features['Head'].tolist())) # self.train, self.test = train_test_split(features, test_size=0.33, random_state=42) X = self.features['Head'] Y = self.features['Polarity'] le = LabelEncoder() Y = le.fit_transform(Y) Y = Y.reshape(-1, 1) self.X_train, self.X_test, self.Y_train, self.Y_test = train_test_split(X, Y, test_size=0.30) self.tok = preprocessing.text.Tokenizer(num_words=len(self…
tagged with: keras
favorite count: 0
upvote count: 2
tagged with: python

http://stackoverflow.com/comment/91044671
score: 1
comment on: http://stackoverflow.com/q/52046777
type: QuestionComment
type: Comment
has text: But if you *insist* on the poor design, you can use `import importlib; importlib.reload('test')`

http://stackoverflow.com/comment/90885112
has text: Hint: look into `set`s and set differences…
comment on: http://stackoverflow.com/q/51967507
type: Comment
type: QuestionComment
score: 1

http://stackoverflow.com/q/52071820
favorite count: 0
has body: From the django documentation ( https://docs.djangoproject.com/el/2.1/topics/db/sql/ ) I'm using the function: def dictfetchall(cursor): "Return all rows from a cursor as a dict" columns = [col[0] for col in cursor.description] return [ dict(zip(columns, row)) for row in cursor.fetchall() ] together with def my_custom_sql(self,sql): with connection.cursor() as cursor: cursor.execute(sql) row = dictfetchall(cursor) return row trying in the console: testen = my_custom_sql(Ausgaben,"SELECT TYP, count(*) Anzahl, sum(Summe) Summe FROM hhdata_Ausgaben group by typ") testen [{'Typ': 'Drogerie', 'Anzahl': 1, 'Summe': 6.0}, {'Typ': 'Essengehen', 'Anzahl': 1, 'Summe': 4.0}, {'Typ': 'Lieferant', 'Anzahl': 1, 'Summe': 50.0}, {'Typ': 'Taschengeld', 'Anzahl': 1, 'Summe': 5.0}] type(testen) &lt;class 'list'&gt; The result looks like a dictionary but it is a list and I can't access the key and values in my template: {% for key,value in testen.items %} &lt;li&gt;&lt;a href="{{key}}"&gt;{{value}}&lt;/a&gt;&lt;/li&gt; {% endfor %} What am I doing wrong here?
tagged with: django
tagged with: python
type: AnsweredQuestion
has title: Django: SQL result as dictionary
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/91093344
has comment: http://stackoverflow.com/comment/91093556
type: Question
has comment: http://stackoverflow.com/comment/91093333
has answer: http://stackoverflow.com/a/52071863
accepted answer: http://stackoverflow.com/a/52071863
upvote count: 1
answer count: 1

http://stackoverflow.com/comment/91152038
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/52100572
has text: @EdChum, Thanks for your inputs, understand your concern, though i'm not really asking for tutorials just opinions , i'm already doing my homework just came across to demystify my understanding, hope you don't mind.

request
tags question: http://stackoverflow.com/q/52042848
tags question: http://stackoverflow.com/q/51977824
tags question: http://stackoverflow.com/q/52101717
tag name: request
tags question: http://stackoverflow.com/q/52111530
tags question: http://stackoverflow.com/q/52027498
type: Tag
tags question: http://stackoverflow.com/q/52073963
tags question: http://stackoverflow.com/q/52056032

http://stackoverflow.com/a/52012341
score: 0
has body: Here is a (kind-of) functional approach (I haven't tried this on Python 2.x): from operator import itemgetter def get_lista(a): if a and len(set(map(' '.join, map(str, map(itemgetter(0), a))))) == 1: return [a[0][0]] + [min(map(itemgetter(1), a), key=itemgetter(1))] return [] a = [[[1, 2, 3, 4, 5, 6, 7, 8, 9], [0.4, 3]], [[1, 2, 3, 4, 5, 6, 7, 8, 9], [1.8, 1]]] lista = get_lista(a) print(lista) # [[1, 2, 3, 4, 5, 6, 7, 8, 9], [1.8, 1]] get_lista(a) will return an empty list, [], if a is empty or if the first sub-item of each of the items of a do not match. a = [[[1, 2, 3, 4, 5, 6, 7, 8, 9], [0.4, 3]], [[2, 3, 4, 5, 6, 7, 8, 9, 10], [1.8, 1]]] print(get_lista(a)) # []
type: Answer
answers question: http://stackoverflow.com/q/52012126

http://stackoverflow.com/a/51993145
answers question: http://stackoverflow.com/q/51992946
has body: I suggest you this solution, which is not optimized but easily readable: from collections import defaultdict myList = [ [26, 'hello'], [26, 'hola'], [26, 'hi'], [26, 'bonjour'], [27, 'bye'],[27, 'doei'], [27, 'see you'], [27, 'tot ziens'] ] d = defaultdict(list) for [k,v] in myList: d[k].append(v) newList = [[k,*v] for k,v in d.items()] print(newList) # [[26, 'hello', 'hola', 'hi', 'bonjour'], [27, 'bye', 'doei', 'see you', 'tot ziens']]
score: 0
type: Answer
upvote count: 1
downvote count: 1

http://stackoverflow.com/comment/91075612
type: Comment
type: QuestionComment
has text: Could you post what's in `request.form` object when the error happen?
score: 0
comment on: http://stackoverflow.com/q/52061812

http://stackoverflow.com/q/51994752
has answer: http://stackoverflow.com/a/51994922
has body: I want to use some tools from shogun machine learning library through Google Colab. However, I cannot install the package. I tried to install Anaconda and install shogun using conda, but after installation, importing shogun is unsuccessful. I tried to follow the instructions provided by the shogun official website, though it didn't help. So, my question is how to install shogun in a Google Colab document? Is it possible in the first place?
has title: How to install shogun library on Google Colaboratory
tagged with: anaconda
type: Question
answer count: 2
tagged with: google-colaboratory
score: 0
tagged with: shogun
has answer: http://stackoverflow.com/a/58916337
tagged with: python
type: UnansweredQuestion

path
tags question: http://stackoverflow.com/q/52036055
tags question: http://stackoverflow.com/q/52033346
tags question: http://stackoverflow.com/q/52021126
tags question: http://stackoverflow.com/q/52048801
type: Tag
tags question: http://stackoverflow.com/q/52073396
tags question: http://stackoverflow.com/q/52036396
tags question: http://stackoverflow.com/q/52058768
tag name: path

http://stackoverflow.com/q/52085276
type: Question
has title: Selecting minimum valued element of nested list after sorting
has comment: http://stackoverflow.com/comment/91120942
has comment: http://stackoverflow.com/comment/91120911
possible better answer: http://stackoverflow.com/a/52085346
has answer: http://stackoverflow.com/a/52085471
score: 0
answer count: 3
has answer: http://stackoverflow.com/a/52085426
upvote count: 1
has comment: http://stackoverflow.com/comment/91120834
favorite count: 0
has comment: http://stackoverflow.com/comment/91120825
tagged with: python-3.x
has answer: http://stackoverflow.com/a/52085346
tagged with: python
has body: I want to select the minimum value of a nested list of the second element (the float part). Code n=int(input("Enter the number: ")) arr=[[input(),float(input())] for _ in range(0,n)] arr.sort(key=lambda x: (x[1],x[0])) min_val=min(arr) print(min_val) Input Enter the number: 3 arp 5 grp 4 drp 3 Output ['arp', 5.0] Expected output ['drp',3.0]
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/52085471
downvote count: 1

http://stackoverflow.com/q/52008233
tagged with: python
has body: I have trained a PySpark ML model with a job submitted using spark-submit. I fail to load this model with another job. I use spark 2.2.0 and python 2.6 My code from pyspark.sql import SparkSession from pyspark.ml.regression import LinearRegression spark = SparkSession.builder.appName("load_model").enableHiveSupport().getOrCreate() model_path = "/home/lr_model" lr_model = LinearRegression.load(model_path) print("Coefficients: " + str(lr_model.coefficients)) print("Intercept: " + str(lr_model.intercept)) And the unclear error message I get: Traceback (most recent call last): File "load_model.py", line 6, in lr_model = LinearRegression.read().load(model_path) File "/hadoop/yarn/local/usercache/appcache/pyspark.zip/pyspark/ml/util.py", line 176, in load File "/hadoop/yarn/local/usercache/appcache/py4j-0.10.1-src.zip/py4j/java_gateway.py", line 933, in call File "/hadoop/yarn/local/usercache/appcache/pyspark.zip/pyspark/sql/utils.py", line 63, in deco File "/hadoop/yarn/local/usercache/appcache/py4j-0.10.1-src.zip/py4j/protocol.py", line 312, in get_return_value py4j.protocol.Py4JJavaError: An error occurred while calling o41.load. : java.lang.NoSuchMethodException: org.apache.spark.ml.regression.LinearRegressionModel.(java.lang.String) at java.lang.Class.getConstructor0(Class.java:3082) at java.lang.Class.getConstructor(Class.java:1825) at org.apache.spark.ml.util.DefaultParamsReader.load(ReadWrite.scala:337) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:498) at py4j.reflection.MethodInvoker.invoke(MethodInvoker.java:237) at py4j.reflection.ReflectionEngine.invoke(ReflectionEngine.java:357) at py4j.Gateway.invoke(Gateway.java:280) at py4j.commands.AbstractCommand.invokeMethod(AbstractCommand.java:128) at py4j.commands.CallCommand.execute(Ca…
answer count: 0
type: UnansweredQuestion
tagged with: machine-learning
tagged with: pyspark
has comment: http://stackoverflow.com/comment/90967250
has title: Pyspark - Error while loading ML model
type: Question
has comment: http://stackoverflow.com/comment/90967891
score: 0
tagged with: apache-spark

http://stackoverflow.com/a/74001070
answers question: http://stackoverflow.com/q/52085191
score: 0
type: Answer
has body: In my case i just replace: #!/usr/bin/env python with: #!/usr/bin/python3